kris
kris

Reputation: 23591

How to concatenate a variable number of columns in Pandas

I have a dataframe like:

    name  aka     fka
0   Alex  Al      NaN
1   Bob   Bobbert Robert
2   Carol NaN     NaN

I'd like to end up with a series of concatenated possible names, like:

0  Alex,Al
1  Bob,Bobbert,Robert
2  Carol

But str.cat will give me extra ,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

I could go through with a bunch of special-cased str.replaces to make sure there are no leading/trailing/duped ,s, but is there a better way to join a variable number of columns?

Upvotes: 1

Views: 1012

Answers (2)

Zero
Zero

Reputation: 76997

You can use

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

Upvotes: 3

sacuL
sacuL

Reputation: 51395

For a quick fix to your str.cat solution, just add 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

Upvotes: 1

Related Questions