Reputation: 1467
I want to add a column name A
in df
, and fill the values. If column a1
has value, fill df.A with df.a1, else fill df.A with df.a2.
tm = pd.DataFrame({'a1':['astr1',np.nan,'astr2',np.nan],'a2':[np.nan,np.nan,np.nan,'astr3']})
tm
a1 a2
0 str1 NaN
1 NaN NaN
2 str2 NaN
3 NaN str2
I want this.
a1 a2 A
0 str1 NaN str1
1 NaN NaN NaN
2 str2 NaN str2
3 NaN str2 str2
Upvotes: 2
Views: 1388
Reputation: 5437
In addition to jezraels answer, you can also use pandas assign function. For example his fillna solution maybe recast in the form
tm.assign(A = lambda x:x.a1.fillna(x.a2))
This may be advantageous in pandas pipelines
Upvotes: 3
Reputation: 863166
You can use numpy.where
with mask created by isnull
:
tm['A'] = np.where(tm.a1.isnull(), tm.a2, tm.a1)
print (tm)
a1 a2 A
0 astr1 NaN astr1
1 NaN NaN NaN
2 astr2 NaN astr2
3 NaN astr3 astr3
Another solutions with combine_first
or fillna
:
tm['A'] = tm.a1.combine_first(tm.a2)
print (tm)
a1 a2 A
0 astr1 NaN astr1
1 NaN NaN NaN
2 astr2 NaN astr2
3 NaN astr3 astr3
tm['A'] = tm.a1.fillna(tm.a2)
print (tm)
a1 a2 A
0 astr1 NaN astr1
1 NaN NaN NaN
2 astr2 NaN astr2
3 NaN astr3 astr3
And last solution with update
:
tm['A'] = tm.a1
tm.A.update(tm.a2)
print (tm)
a1 a2 A
0 astr1 NaN astr1
1 NaN NaN NaN
2 astr2 NaN astr2
3 NaN astr3 astr3
Upvotes: 3