gpt4 book ai didi

python - Pandas 添加一列并使用列表推导式填充值 if else

转载 作者:行者123 更新时间:2023-11-28 21:07:55 25 4
gpt4 key购买 nike

我想在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_firstfillna :

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

关于python - Pandas 添加一列并使用列表推导式填充值 if else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40884882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com