python - 如何在 Pandas 中连接可变数量的列
问题描述
我有一个像这样的数据框:
name aka fka
0 Alex Al NaN
1 Bob Bobbert Robert
2 Carol NaN NaN
我想以一系列串联的可能名称结束,例如:
0 Alex,Al
1 Bob,Bobbert,Robert
2 Carol
但是str.cat
会给我额外,
的s:
df.name.str.cat([df.aka, df.fka], sep=',', na_rep='')
0 Alex,Al,
1 Bob,Bobbert,Robert
2 Carol,,
Name: name, dtype: object
我可以通过一堆特殊情况的str.replace
s 来确保没有前导/尾随/重复,
的 s,但是有没有更好的方法来加入可变数量的列?
解决方案
您可以使用
In [489]: df.apply(lambda x: x.str.cat(sep=','), axis=1)
Out[489]:
0 Alex,Al
1 Bob,Bobbert,Robert
2 Carol
dtype: object
推荐阅读
- json - 如何从具有单个“键值”的 JSON 对象中提取单个值?
- google-analytics - Google Signals/Remarketing - check if it's enabled?
- amazon-web-services - 使用 Cognito 和 Lambda 函数的 AWS 无服务器 DynamoDB 行级授权
- android - AAPT:错误:找不到资源 attr/(各种)
- dictionary - 如何在颤动中操作地图?
- javascript - 在单选按钮中显示布尔值
- python - 另一个框架内的框架在python Tkinter中
- mysql - 使用多种编码生成包含列的表
- ms-access - 访问功能区 OnAction
- android - TextView 文本更改但布局不更新(Kotlin - Android)