如何连接数据中可变数量的列

2024-09-27 23:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个数据帧:

    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会给我额外的,

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来确保没有前导/尾随/重复的,,但是有没有更好的方法来连接数量可变的列呢?你知道吗


Tags: 数据name名称dfnanrobertcataka
2条回答

你可以用

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

要快速修复str.cat解决方案,只需添加str.strip(',')

df.name.str.cat([df.aka, df.fka], sep=',', na_rep='').str.strip(',')
0               Alex,Al
1    Bob,Bobbert,Robert
2                 Carol
Name: name, dtype: object

相关问题 更多 >

    热门问题