python - Pandas 数据框分组

标签 python pandas

我是 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 来做到这一点。

最佳答案

您可以使用groupbyapply 加入:

#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/

相关文章:

python - 比较两个文件中的 x、y、z 坐标

python - 如何判断一个序列是否可变?

python - 绘制 pandas 聚合对象

python - 属性错误: 'str' object has no attribute 'update'

python - 多指数作图

python - 根据多个数据帧的公共(public)时间戳创建数据帧

python-2.7 - 我如何使用 Pandas (python) 读取 7z 文件并将其转换为 csv?

Python 3 将单列拆分为多列,不带逗号

python - 属性错误: 'CategoricalBlock' object has no attribute 'sp_index'

python - 创建字符串数组