如果一列中有重复项,我正在尝试合并数据帧的行。数据框如下所示。
Name Code X Y
A 123 10 11
B 456 12 13
C 123 15 16
Run Code Online (Sandbox Code Playgroud)
我想结合代码。因此,如果代码相同,则合并其他用逗号分隔的数据。产生的df如下所示:
Name Code X Y
A,C 123 10,15 11,16
B 456 12 13
Run Code Online (Sandbox Code Playgroud)
我的方法如下:
df = df.groupby(['Name','Code','Y'])['X'].astype(str).apply(', '.join).reset_index()
df = df.groupby(['Name','Code','X'])['Y'].astype(str).apply(', '.join).reset_index()
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
"Cannot access callable attribute 'astype' of 'SeriesGroupBy' objects, try using the 'apply' method"
Run Code Online (Sandbox Code Playgroud)
我一直无法弄清楚如何使用str类型的强制转换,有什么提示吗?
从Code列fo 创建索引,避免转换为字符串,然后转换所有列并通过index函数进行汇总join:
df = df.set_index('Code').astype(str).groupby(level=0).agg(', '.join).reset_index()
#pandas 0.24+
#df = df.set_index('Code').astype(str).groupby('Code').agg(', '.join).reset_index()
print (df)
Code Name X Y
0 123 A, C 10, 15 11, 16
1 456 B 12 13
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
56 次 |
| 最近记录: |