使用排序数据创建表

时间:2018-01-16 14:48:07

标签: python python-3.x pivot-table

我有来自数据库的数据(许多记录):

('group1', 272, 'Alex')
('group1', 268, 'Alex1')
('group2', 267, 'Kate')
('group2', 138, 'Stive')
('group2', 3081, 'Stive2')
...
('group3', 265, 'Dave')

我可以将这些数据写入CSV文件或列表,但是如何使用结构并按名称和group_name通过python 3.4进行排序:

Name  group1 group2 group3 ... groupN
Alex  True   False  False  ... 
Alex1 True   False  False  ...
...

也许你可以帮助我。

2 个答案:

答案 0 :(得分:1)

假设您已将数据从数据库读入元组列表,您可以试试这个:

import csv
data = [('group1', 272, 'Alex'), ('group1', 268, 'Alex1'), ('group2', 267, 'Kate'), ('group2', 138, 'Stive'), ('group2', 3081, 'Stive2'),('group3', 265, 'Dave')]
final_data = sorted([(c, *[a == i for i in ['group1', 'group2', 'group3']]) for a, b, c in data], key=lambda x:x[0])
print(final_data)
write = csv.writer(open('filename.csv'))
write.writerows([['Name', 'group1', 'group2', 'group3']]+final_data)

输出:

[('Alex', True, False, False), 
 ('Alex1', True, False, False), 
 ('Dave', False, False, True), 
 ('Kate', False, True, False), 
 ('Stive', False, True, False), 
 ('Stive2', False, True, False)]

编辑:对于许多可能的群组:

groups = list(set(map(lambda x:x[0], data)))
final_data = sorted([(c, *[a == i for i in groups]) for a, b, c in data], key=lambda x:x[0])
write = csv.writer(open('filename.csv'))
write.writerows([['Name', *groups]]+final_data)

答案 1 :(得分:1)

首先通过创建一组使用过的名称然后对它们进行排序来确定所需列名cols的列表。然后,您可以构建一个包含所有条目的字典:

from collections import defaultdict
import csv

data = [('group1', 272, 'Alex'), ('group1', 268, 'Alex1'), ('group2', 267, 'Kate'), ('group2', 138, 'Stive'), ('group2', 3081, 'Stive2'),('group3', 265, 'Dave')]
cols = sorted(set(g for g, v1, v2 in data))
names = defaultdict(list)

for group, value, name in data:
    names[name].append(group)

with open('output.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(['Name'] + cols)

    for name in sorted(names.keys()):
        csv_output.writerow([name] + [col in names[name] for col in cols])

给你一个输出文件:

Name,group1,group2,group3
Alex,True,False,False
Alex1,True,False,False
Dave,False,False,True
Kate,False,True,False
Stive,False,True,False
Stive2,False,True,False