np.select()条件中的否定 [英] Negation in np.select() condition
本文介绍了np.select()条件中的否定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码:
import pandas as pd
import numpy as np
df = pd.DataFrame({ 'var1': ['a', 'b', 'c',np.nan, np.nan],
'var2': [1, 2, np.nan , 4, np.nan]
})
conditions = [
(not(pd.isna(df["var1"]))) & (not(pd.isna(df["var2"]))),
(pd.isna(df["var1"])) & (pd.isna(df["var2"]))]
choices = ["No missing", "Both missing"]
df['Result'] = np.select(conditions, choices, default=np.nan)
输出:
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py", line 1478, in __nonzero__
f"The truth value of a {type(self).__name__} is ambiguous. "
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
问题出在行(not(pd.isna(df["var1"]))) & (not(pd.isna(df["var2"])))
上.当同时在var1
和var2
中使用时,此行应使用TRUE
而不是NaN
值.这里的问题在于否定,因为没有否定的条件就没有问题.
Problem is with line (not(pd.isna(df["var1"]))) & (not(pd.isna(df["var2"])))
. This line should give TRUE
when in both var1
and var2
in not a NaN
value. Problem here is with negation, because with conditions without negation there is no problem.
问题:如何纠正(not(pd.isna(df["var1"]))) & (not(pd.isna(df["var2"])))
行,以便在var1
和var2
两者中都没有NaN
值的情况下应该给出TRUE
? >
Question: How can to correct (not(pd.isna(df["var1"]))) & (not(pd.isna(df["var2"])))
line so in case when in both var1
and var2
in not a NaN
value the condition should give TRUE
?
推荐答案
尝试:
conditions = [(~pd.isna(df["var1"]) & ~pd.isna(df["var2"])),
(pd.isna(df["var1"]) & pd.isna(df["var2"]))]
这篇关于np.select()条件中的否定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文