[英]Pandas add a column and fill values by using list comprehension if else
我想在df
添加列名A
并填充值。 如果a1
列具有值,则用df.a1填充df.A,否则用df.a2填充df.A。
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
我要这个。
a1 a2 A
0 str1 NaN str1
1 NaN NaN NaN
2 str2 NaN str2
3 NaN str2 str2
您可以使用numpy.where
通过创建面膜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
另一个带有combine_first
或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
最后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
除了jezraels答案外,您还可以使用pandas Assign 函数 。 例如,他的fillna解决方案可能会以以下形式重铸
tm.assign(A = lambda x:x.a1.fillna(x.a2))
这在熊猫管道中可能是有利的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.