给出以下内容df
Id other concat
0 A z 1
1 A y 2
2 B x 3
3 B w 4
4 B v 5
5 B u 6
我想要的结果是new
包含分组值作为列表的列
Id other concat new
0 A z 1 [1, 2]
1 A y 2 [1, 2]
2 B x 3 [3, 4, 5, 6]
3 B w 4 [3, 4, 5, 6]
4 B v 5 [3, 4, 5, 6]
5 B u 6 [3, 4, 5, 6]
这类似于以下问题:
在 pandas groupby 中对列表中的行进行分组 https://stackoverflow.com/questions/22219004/grouping-rows-in-list-in-pandas-groupby
为 pandas.DataFrame 复制 GROUP_CONCAT https://stackoverflow.com/questions/18138693/replicating-group-concat-for-pandas-dataframe
但是,它应用您从中获得的分组df.groupby('Id')['concat'].apply(list)
,这是一个Series
比数据帧更小的尺寸,到原始数据帧。
我已经尝试了下面的代码,但它不适用于数据框:
import pandas as pd
df = pd.DataFrame( {'Id':['A','A','B','B','B','C'], 'other':['z','y','x','w','v','u'], 'concat':[1,2,5,5,4,6]})
df.groupby('Id')['concat'].apply(list)
我知道transform
可用于将分组应用于数据帧,但在这种情况下不起作用。
>>> df['new_col'] = df.groupby('Id')['concat'].transform(list)
>>> df
Id concat other new_col
0 A 1 z 1
1 A 2 y 2
2 B 5 x 5
3 B 5 w 5
4 B 4 v 4
5 C 6 u 6
>>> df['new_col'] = df.groupby('Id')['concat'].apply(list)
>>> df
Id concat other new_col
0 A 1 z NaN
1 A 2 y NaN
2 B 5 x NaN
3 B 5 w NaN
4 B 4 v NaN
5 C 6 u NaN