将 Python 数据框列与包含 None 值的变量进行比较
Compare Python dataframe columns to variables containing None values
我正在将数据框与多个变量进行如下比较...
if not ( (df['Column1'] == variableA) & (df['Column2'] == variableB) & (df['Column3'] == variableC) ).any():
print("row not in dataframe")
我的数据框和变量都可能包含一个 None 值,但我注意到当比较 2 个 None 值时,它们不是 return True,所以我' m 打印“不在列表中”,即使 df 和变量都具有相同的 (None) 值。
如能提出解决此问题的最佳方法,我们将不胜感激。也许我必须将 None 值转换为比较时 return 为真的字符串?
原因是断言 None
的相等性无法使用简单的相等运算符。
考虑以下示例:
s = pd.Series([1, "a", None])
s == 1
Out[4]:
0 True
1 False
2 False
dtype: bool
s == "a"
Out[5]:
0 False
1 True
2 False
dtype: bool
s == None
Out[6]:
0 False
1 False
2 False
dtype: bool
s.isna()
Out[7]:
0 False
1 False
2 True
dtype: bool
因此,如果您想收集 None
之间的任何潜在相等性,您需要检查这些值是否为 na
。
如果您有两个系列(例如数据框的两个列),您将需要创建一个结果联合:
d = pd.Series([2, "a", None])
s == d
Out[12]:
0 False
1 True
2 False
dtype: bool
(s == d) | (s.isna() & d.isna())
Out[13]:
0 False
1 True
2 True
dtype: bool
这意味着您的问题的解决方案类似于:
(df['Column1'] == variableA) & (df['Column2'] == variableB) & (df['Column3'] == variableC)
|
(df['Column1'].isna() & df['Column2'].isna() & df['Column3'].isna())
我正在将数据框与多个变量进行如下比较...
if not ( (df['Column1'] == variableA) & (df['Column2'] == variableB) & (df['Column3'] == variableC) ).any():
print("row not in dataframe")
我的数据框和变量都可能包含一个 None 值,但我注意到当比较 2 个 None 值时,它们不是 return True,所以我' m 打印“不在列表中”,即使 df 和变量都具有相同的 (None) 值。
如能提出解决此问题的最佳方法,我们将不胜感激。也许我必须将 None 值转换为比较时 return 为真的字符串?
原因是断言 None
的相等性无法使用简单的相等运算符。
考虑以下示例:
s = pd.Series([1, "a", None])
s == 1
Out[4]:
0 True
1 False
2 False
dtype: bool
s == "a"
Out[5]:
0 False
1 True
2 False
dtype: bool
s == None
Out[6]:
0 False
1 False
2 False
dtype: bool
s.isna()
Out[7]:
0 False
1 False
2 True
dtype: bool
因此,如果您想收集 None
之间的任何潜在相等性,您需要检查这些值是否为 na
。
如果您有两个系列(例如数据框的两个列),您将需要创建一个结果联合:
d = pd.Series([2, "a", None])
s == d
Out[12]:
0 False
1 True
2 False
dtype: bool
(s == d) | (s.isna() & d.isna())
Out[13]:
0 False
1 True
2 True
dtype: bool
这意味着您的问题的解决方案类似于:
(df['Column1'] == variableA) & (df['Column2'] == variableB) & (df['Column3'] == variableC)
|
(df['Column1'].isna() & df['Column2'].isna() & df['Column3'].isna())