[英]Pandas add a column and fill values by using list comprehension if else
I want to add a column name A
in df
, and fill the values. 我想在
df
添加列名A
并填充值。 If column a1
has value, fill df.A with df.a1, else fill df.A with df.a2. 如果
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
I want this. 我要这个。
a1 a2 A
0 str1 NaN str1
1 NaN NaN NaN
2 str2 NaN str2
3 NaN str2 str2
You can use numpy.where
with mask created by isnull
: 您可以使用
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
Another solutions with combine_first
or fillna
: 另一个带有
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
And last solution with update
: 最后
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
In addition to jezraels answer, you can also use pandas assign function . 除了jezraels答案外,您还可以使用pandas Assign 函数 。 For example his fillna solution maybe recast in the form
例如,他的fillna解决方案可能会以以下形式重铸
tm.assign(A = lambda x:x.a1.fillna(x.a2))
This may be advantageous in pandas pipelines 这在熊猫管道中可能是有利的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.