首页 > 解决方案 > Pandas 按类型将列值组合成一行的单元格

问题描述

我有这个数据框

ID  type    name    number  description comments
1   short   A       2       XX          xxx
1   short   B                               
1   short   C       4       YY          yyy
1   full    A/B/C
2   short   E       
2   short   F       9       ZZ          zzz                     
2   short   G       7       WW          www
2   short   H       
2   full    E/F/G/H 

我想通过在行中折叠行type full中的number,descriptioncomments列值(如果它们存在)来将其转换为type short

id  type    name    number  description comments
1   full    A/B/C   2/4     XX/YY       xxx/yyy
2   full    E/F/G/H 9/7     ZZ/WW       zzz/www

我尝试使用聚合和 groupby 函数但没有成功。

你可以帮帮我吗?

提前致谢!

标签: pythonpandasdataframepandas-groupby

解决方案


您可以dict.fromkeys使用 lambda 函数为所有没有id和来自字典的键的列创建动态字典d1并传递给GroupBy.agg

f = lambda x: '/'.join(x.dropna().astype(str))

d1 = {'type':'last', 'name':'last'}
d2 = dict.fromkeys(df.columns.difference(['id'] + list(d1.keys())), f)
d = {**d1, **d2}    

df = df.groupby('id', sort=False, as_index=False).agg(d)
print (df)
   id  type     name comments description   number
0   1  full    A/B/C  xxx/yyy       XX/YY  2.0/4.0
1   2  full  E/F/G/H  zzz/www       ZZ/WW  9.0/7.0

如果需要按类型处理 lambda 函数中的值 - 例如数字的总和和非数字列的连接:

f = lambda x: x.sum() if np.issubdtype(x.dtype, np.number) else '/'.join(x.dropna())

d1 = {'type':'last', 'name':'last'}
d2 = dict.fromkeys(df.columns.difference(['id'] + list(d1.keys())), f)
d = {**d1, **d2}           
df = df.groupby('id', sort=False, as_index=False).agg(d)
print (df)
   id  type     name comments description  number
0   1  full    A/B/C  xxx/yyy       XX/YY     6.0
1   2  full  E/F/G/H  zzz/www       ZZ/WW    16.0

推荐阅读