python - 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
,description
和comments
列值(如果它们存在)来将其转换为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 函数但没有成功。
你可以帮帮我吗?
提前致谢!
解决方案
您可以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
推荐阅读
- java - 使用一份 Jasper 报告生成 2 个文档
- html - UI-选择默认占位符而不是可以更改
- python-3.x - DNS 查询未指定或太小
- c++ - 无法使用基类右值初始化指向子类的指针
- xml - Haskell - 如何将 XML 响应解析为 Haskell 数据类型?
- node.js - 不能在异步函数上调用 nodeify 但可以调用 then()
- android - ScrollView 内的 ConstraintLayout,constraintHeight_percent 中断滚动
- laravel - 使用 Laravel + Vue 正确处理 404 响应
- html - 在悬停时停止文本向下移动
- sql - 在年月字段中获取最近一年的记录