合并特定列上的重复行

时间:2019-03-12 14:16:43

标签: python pandas

如果一列中有重复项,我正在尝试合并数据帧的行。数据框如下所示。

Name   Code   X   Y
 A     123   10   11
 B     456   12   13
 C     123   15   16

我想结合代码。因此,如果代码相同,则合并其他用逗号分隔的数据。生成的df如下所示:

Name   Code    X       Y
A,C    123   10,15   11,16
 B     456    12       13

我的方法如下:

    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() 

我收到以下错误:

"Cannot access callable attribute 'astype' of 'SeriesGroupBy' objects, try using the 'apply' method"

我一直无法弄清楚如何使用apply来强制转换为str类型,有任何提示吗?

2 个答案:

答案 0 :(得分:3)

另一种布局

getUriForFile

答案 1 :(得分:1)

更多一般解决方案:

requests.post(URL, headers=HEADERS, data=PAYLOAD[0])

最后一行将索引从import pandas as pd df = pd.DataFrame([['A',123,10,11],['B',456,12,13],['C',123,15,16]],columns=['Name','Code','X','Y']) def f(x): return ','.join(x) df = df.astype(str).groupby('Code').agg(f) df.index = [int(i) for i in df.index.tolist()] 更改回string类型。 我添加此解决方案是因为它易于理解,但不是最优雅的。

相关问题