首页 > 解决方案 > 如何在 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.replaces 来确保没有前导/尾随/重复,的 s,但是有没有更好的方法来加入可变数量的列?

标签: pythonpandas

解决方案


您可以使用

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

推荐阅读