我在 .txt 文件中有一个表格,如下所示:
GROUP TYPE FRACTION
1 A 0.1
1 B 0.6
1 C 0.3
2 A 0.7
2 C 0.3
如何重新排列记录以使表格看起来像这样并在 Python 中写入另一个 txt 文件:
GROUP TYPE_A TYPE_B TYPE_C
1 0.1 0.6 0.3
2 0.7 0.0 0.3
谢谢!
from collections import defaultdict
d = defaultdict(dict)
with open('test.txt') as f:
next(f, None) # skip header
for line in f:
group, type_, fraction = line.split()
d[group][type_] = fraction
types = sorted(set(k for g in d.values() for k in g))
print 'GROUP ' + ''.join('{:<7}'.format('TYPE_' + t) for t in types)
for i, g in sorted(d.items()):
print '{0:<6}'.format(i) + ''.join('{:<7}'.format(g.get(k, 0.0))
for k in types)
输出:
GROUP TYPE_A TYPE_B TYPE_C
1 0.1 0.6 0.3
2 0.7 0.0 0.3