将列表转换为聚合列表

时间:2017-05-29 14:16:03

标签: python python-2.7

所以我有一个这样的列表:

date, type
29-5-2017, x
30-5-2017, x
31-5-2017, y
1-6-2017, z
2-6-2017, z
3-6-2017, y
28-5-2017, y
29-5-2017, z
30-5-2017, z
31-5-2017, y
1-6-2017, z
2-6-2017, z
3-6-2017, x
29-5-2017, x
30-5-2017, z
31-5-2017, z
1-6-2017, y
2-6-2017, x
3-6-2017, z
4-6-2017, y

我如何创建此列表的聚合版本?所以我只给每个日期一次,看看在给定日期有多少种类型。

像这样:

date, no._of_x, no._of_y, no._of_z
28-5-2017, 0, 1, 0
29-5-2017, 2, 0, 1
30-5-2017, 1, 0, 2
31-5-2017, 0, 2, 1
1-6-2017, 0, 1, 2
2-6-2017, 1, 0, 2
3-6-2017, 1, 1, 1
4-6-2017, 0, 1, 0

1 个答案:

答案 0 :(得分:0)

假设您的列表是包含日期字符串且包含xyz的每个子列表的列表列表,您可以先按日期对列表进行分组。只需创建一个字典,或collections.defaultdict,将日期映射到x / z / y列表。

dates = collections.defaultdict(list)
for date, xyz in data:
    dates[date].append(xyz)

接下来,您可以创建另一个字典,将每个x / y / z列表映射到Counter字典:

counts = {date: collections.Counter(xyz) for date, xyz in dates.items()}

之后,counts就是这样:

{'2-6-2017,': Counter({'z': 2, 'x': 1}), 
 '29-5-2017,': Counter({'x': 2, 'z': 1}), 
 '3-6-2017,': Counter({'x': 1, 'y': 1, 'z': 1}), 
 '28-5-2017,': Counter({'y': 1}), 
 '1-6-2017,': Counter({'z': 2, 'y': 1}), 
 '4-6-2017,': Counter({'y': 1}), 
 '31-5-2017,': Counter({'y': 2, 'z': 1}), 
 '30-5-2017,': Counter({'z': 2, 'x': 1})}