Reputation: 5299
I have a dataframe like this
A B
0 a 1
1 b 2
2 c 3
3 d nan
4 e nan
I would like to add column C like below
A B C
0 a 1 a1
1 b 2 b2
2 c 3 c3
3 d nan d
4 e nan e
So I tried
df["C"]=df.A+df.B
but It returns
C
a1
b2
c3
nan
nan
How can get correct result?
Upvotes: 4
Views: 1549
Reputation: 294488
You can use add
method with the fill_value
parameter
df['C'] = df.A.add(df.B, fill_value='')
df
Upvotes: 0
Reputation: 17468
In your code, I think the data type of the element in the dataframe is str, so, try fillna.
In [10]: import pandas as pd
In [11]: import numpy as np
In [12]: df = pd.DataFrame({'A': ['a', 'b', 'c', 'd', 'e'],
'B': ['1', '2', '3', np.nan, np.nan]})
In [13]: df.B.fillna('')
Out[13]:
0 1
1 2
2 3
3
4
Name: B, dtype: object
In [14]: df
Out[14]:
A B
0 a 1
1 b 2
2 c 3
3 d NaN
4 e NaN
[5 rows x 2 columns]
In [15]: df.B = df.B.fillna('')
In [16]: df["C"]=df.A+df.B
In [17]: df
Out[17]:
A B C
0 a 1 a1
1 b 2 b2
2 c 3 c3
3 d d
4 e e
[5 rows x 3 columns]
Upvotes: 2
Reputation: 12515
df['C'] = pd.Series(df.fillna('').values.tolist()).str.join(' ')
Upvotes: 0