熊猫:按组列出

2024-05-12 13:20:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有如下数据:

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'])对数据进行了分组。但在那之后,我无法访问组并获取上述格式的数据。


Tags: andthe数据id列表forbytime
3条回答

您可以执行以下操作:

import pandas as pd

data = [[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]]

df = pd.DataFrame(data=data, columns=['id', 'value', 'year'])

result = []
for name, group in df.groupby(['id']):
    result.append([g['value'].values.tolist() for _, g in group.groupby(['year'])])

for e in result:
    print(e)

输出

[[5, 6, 7], [5]]
[[3], [3], [4, 5]]
[[3], [6]]

如果要计算多个列的列表,可以执行以下操作:

df = pd.DataFrame(
    {'A': [1,1,2,2,2,2,3],
     'B':['a','b','c','d','e','f','g'],
     'C':['x','y','z','x','y','z','x']})

df.groupby('A').agg({ 'B': lambda x: list(x),'C': lambda x: list(x)})

同时计算B和C的列表:

              B             C
A                            
1        [a, b]        [x, y]
2  [c, d, e, f]  [z, x, y, z]
3           [g]           [x]

您可以使用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

如果您真的希望它的格式与您显示的完全一样,那么您可以按id分组,然后再次应用list,但这并不高效,而且这种格式可能更难使用。。。

>>> df.groupby(['id','time'])['value'].apply(list).groupby('id').apply(list).tolist()
[[[5, 6, 7], [5]], [[3], [3], [4, 5]], [[3], [6]]]

相关问题 更多 >