我有如下数据:
id value time
1 5 2000
1 6 2000
1 7 2000
1 5 2001
2 3 2000
2 3 2001
2 4 2005
2 5 2005
3 3 2000
3 6 2005
我的最终目标是将数据放在如下列表中:
[[5,6,7],[5]] (this is for id 1 grouped by the id and year)
[[3],[3],[4,5]] (this is for id 2 grouped by the id and year)
[[3],[6]] (same logic as above)
我使用以下方法对数据进行了分组df.groupby(['id', 'year'])
。但之后,我无法访问这些组并获取上述格式的数据。
您可以使用apply(list)
:
>>> df.groupby(['id', 'time'])['value'].apply(list)
id time
1 2000 [5, 6, 7]
2001 [5]
2 2000 [3]
2001 [3]
2005 [4, 5]
3 2000 [3]
2005 [6]
Name: value, dtype: object
如果您确实希望它的格式与您显示的完全相同,则可以 groupbyid
并申请list
again,但这效率不高,而且这种格式可能更难使用......
>>> df.groupby(['id','time'])['value'].apply(list).groupby('id').apply(list).tolist()
[[[5, 6, 7], [5]], [[3], [3], [4, 5]], [[3], [6]]]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)