Skip to main content
 首页 » 编程设计

python之分组值并使用 Python 在 Pandas 上合并

2025年05月04日27TianFang

我在 csv 上有以下数据:

c1    c2 
1     2 
1     3 
3     4 
3     5 
4     6 

我需要做的是处理该数据并获得以下输出:

c1    c2 
1     2,3 
3     4,5 
4     6 

这对 Pandas 来说可能吗?

谢谢

请您参考如下方法:

您可以先通过 astype 将 c2 列转换为 string然后 groupby与 apply 加入。最后 reset_index :

df['c2'] = df['c2'].astype(str) 
print df.groupby('c1')['c2'].apply(','.join).reset_index() 
   c1   c2 
0   1  2,3 
1   3  4,5 
2   4    6 

如果需要drop_duplicates :

print df 
   c1  c2 
0   1   2 
1   1   3 
2   1   2 
3   1   3 
4   3   4 
5   3   5 
6   4   6 
 
df['c2'] = df['c2'].astype(str) 
df = df.groupby('c1')['c2'].apply(lambda x: ','.join(x.drop_duplicates())).reset_index() 
print df 
   c1   c2 
0   1  2,3 
1   3  4,5 
2   4    6 

如果您需要按 c2 列中值的长度对 DataFrame 进行排序,请使用 str.len和 sort_values .最后你可以drop列排序:

print df 
   c1  c2 
0   1   4 
1   1   5 
2   4   6 
3   2   7 
4   2   3 
5   2   2 
6   2   3 
 
df['c2'] = df['c2'].astype(str) 
df = df.groupby('c1')['c2'].apply(lambda x: ','.join(x.drop_duplicates())).reset_index() 
 
df['sort'] = df['c2'].str.len() 
df = df.sort_values('sort') 
df = df.drop('sort',axis=1) 
print df 
   c1     c2 
2   4      6 
0   1    4,5 
1   2  7,3,2 
 
print df.reset_index(drop=True) 
   c1     c2 
0   4      6 
1   1    4,5 
2   2  7,3,2