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.
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)
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.
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)