gpt4 book ai didi

python - Python 中的双 IIF 语句

转载 作者:太空宇宙 更新时间:2023-11-03 16:11:38 24 4
gpt4 key购买 nike

我有一个 SQL 代码,其中有两个 IIF 语句,也就是说,if true 部分是另一个 IIF 语句,我正在尝试使用 np.where 在 python 中重新创建它

SQL 代码是:

IIF ([STATE] Is Null, IIF ([COUNTRY] Is Null,'No Country',[COUNTRY]), [STATE])

我已经尝试过这个:

DF['NewCol'] = np.where(DF['STATE'].isnull(),(np.where(DF['COUNTRY'].isnull(),'No Country','DF['COUNTRY']'),DF['STATE']))

感谢任何帮助

最佳答案

我认为你需要:

DF['NewCol'] = np.where(DF['STATE'].isnull(),
np.where(DF['COUNTRY'].isnull(),'No Country', DF['COUNTRY']),DF['STATE'])

示例:

DF = pd.DataFrame({'STATE':[np.nan,'a','b',np.nan],
'COUNTRY':[np.nan,'c',np.nan, 'd']})

print (DF)
COUNTRY STATE
0 NaN NaN
1 c a
2 NaN b
3 d NaN

DF['NewCol'] = np.where(DF['STATE'].isnull(),
np.where(DF['COUNTRY'].isnull(),'No Country', DF['COUNTRY']),DF['STATE'])

print (DF)
COUNTRY STATE NewCol
0 NaN NaN No Country
1 c a a
2 NaN b b
3 d NaN d

如果需要首先在 COUNTRY 列的输出列值中:

DF['NewCol'] = np.where(DF['COUNTRY'].isnull(),
np.where(DF['STATE'].isnull(),'No Country', DF['STATE']),DF['COUNTRY'])

print (DF)
COUNTRY STATE NewCol
0 NaN NaN No Country
1 c a c
2 NaN b b
3 d NaN d

关于python - Python 中的双 IIF 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39244955/

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