Concatenate numbers as strings in pandas dataframe

Question:

I have an excel file with data as below:

A  B  C
1  0  
1  1  1
1  1  0

I want to write a python code which would concatenate the values in A, B & C in column D as shown below:

A  B  C  D
1  0     10
1  1  1  111
1  1  0  110

In excel this can be done by =A1&B1&C1&D1

I want to replicate the same with pandas.

Asked By: MDJ

||

Answers:

Use list comprehension with replace missing values and converting to strings if necessary:

df['D'] = [''.join(x) for x in df.fillna('').astype(str).to_numpy()]
print (df)
   A  B    C    D
0  1  0  NaN   10
1  1  1    1  111
2  1  1    0  110

If performance is not important:

df['D'] = df.fillna('').astype(str).agg(''.join, axis=1)
df['D'] = df.fillna('').astype(str).apply(''.join, axis=1)
Answered By: jezrael
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.