我是 Pandas 的初学者,所以请耐心等待。我知道这是一个非常基本的问题/
我正在使用 pandas 处理以下数据框:
x y w
1 2 5
1 2 7
3 4 3
5 4 8
3 4 5
5 9 9
我想要以下输出:
x y w
1 2 5,7
3 4 2,5
5 4 8
5 9 9
谁能告诉我如何使用 pandas groupby 来做到这一点。
最佳答案
#if type of column w is not string, convert it
print type(df.at[0,'w'])
<type 'numpy.int64'>
df['w'] = df['w'].astype(str)
print df.groupby(['x','y'])['w'].apply(','.join).reset_index()
x y w
0 1 2 5,7
1 3 4 3,5
2 5 4 8
3 5 9 9
如果有重复项,请使用 drop_duplicates
:
print df
x y w
0 1 2 5
1 1 2 5
2 1 2 5
3 1 2 7
4 3 4 3
5 5 4 8
6 3 4 5
7 5 9 9
df['w'] = df['w'].astype(str)
print df.groupby(['x','y'])['w'].apply(lambda x: ','.join(x.drop_duplicates()))
.reset_index()
x y w
0 1 2 5,7
1 3 4 3,5
2 5 4 8
3 5 9 9
或修改EdChum解决办法:
print df.groupby(['x','y'])['w'].apply(lambda x: ','.join(x.astype(str).drop_duplicates()))
.reset_index()
x y w
0 1 2 5,7
1 3 4 3,5
2 5 4 8
3 5 9 9
关于python - Pandas 数据框分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37048952/