pandas DataFrame 列中的布尔运算
Boolean operation in pandas DataFrame columns
我试图查明特定列是否存在于我的 DataFrame 列中,但我遇到了一些问题。
我做什么:使用布尔运算 "not in"(我试过 any()、all()、"in")来查找特定的列 header,它似乎是工作不正常!
假设我的 DataFrame 列 header 是:
df.columns = ['El-array', 'a', 'b', 'm', 'n', 'Rho', 'dev', 'ip', 'sp', 'vp', 'i',
'M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9', 'M10', 'M11',
'M12', 'M13', 'M14', 'M15', 'M16', 'M17', 'M18', 'M19', 'M20', 'TM1',
'TM2', 'resist', 'DC_slope']
我正在尝试查看 'M1'、'M2'、... 'M20' 和 'TM1' 是否全部存在。如果缺少一个或多个代码将不起作用。
所以我说:
if any(['M1','M2','M3','M4','M5','M6','M7','M8','M9','M10','M11',
'M12','M13','M14','M15','M16','M17','M18','M19','M20', 'TM1']) not in df.columns:
print('Incomplete dataset')
现在,假设 df 具有所有询问的列 headers,if 语句仍然显示 "Incomplete dataset' message!! I have tried "all() not in" 但结果相同!我也尝试过:
if 'M1' and 'M2' and ... and 'M20' and 'TM1' in df.columns:
"Do this"
elif:
print('Incomplete dataset')
或
if 'M1' or 'M2' or ... or 'M20' and 'TM1' not in df.columns:
print('Incomplete dataset')
elif:
"Do this"
仍然打印不完整的数据集!!
现在对于一个真正不完整的数据集,我也得到了相同的结果!!
您对 any
and or
的工作原理存在根本性的误解。我建议回去看看我链接到的文档。
你想要:
names = ['M1','M2','M3','M4','M5','M6','M7','M8','M9','M10','M11',
'M12','M13','M14','M15','M16','M17','M18','M19','M20', 'TM1']
if any(name not in df.columns for name in names):
...
else:
print('incompatable dataset')
或者(这实际上只是为了获得最小的性能提升),您可以使用 set difference(returns 所有值都在 names
中,但不在 df.columns
):
if not set(names) - set(df.columns):
...
我试图查明特定列是否存在于我的 DataFrame 列中,但我遇到了一些问题。
我做什么:使用布尔运算 "not in"(我试过 any()、all()、"in")来查找特定的列 header,它似乎是工作不正常!
假设我的 DataFrame 列 header 是:
df.columns = ['El-array', 'a', 'b', 'm', 'n', 'Rho', 'dev', 'ip', 'sp', 'vp', 'i',
'M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'M8', 'M9', 'M10', 'M11',
'M12', 'M13', 'M14', 'M15', 'M16', 'M17', 'M18', 'M19', 'M20', 'TM1',
'TM2', 'resist', 'DC_slope']
我正在尝试查看 'M1'、'M2'、... 'M20' 和 'TM1' 是否全部存在。如果缺少一个或多个代码将不起作用。
所以我说:
if any(['M1','M2','M3','M4','M5','M6','M7','M8','M9','M10','M11',
'M12','M13','M14','M15','M16','M17','M18','M19','M20', 'TM1']) not in df.columns:
print('Incomplete dataset')
现在,假设 df 具有所有询问的列 headers,if 语句仍然显示 "Incomplete dataset' message!! I have tried "all() not in" 但结果相同!我也尝试过:
if 'M1' and 'M2' and ... and 'M20' and 'TM1' in df.columns:
"Do this"
elif:
print('Incomplete dataset')
或
if 'M1' or 'M2' or ... or 'M20' and 'TM1' not in df.columns:
print('Incomplete dataset')
elif:
"Do this"
仍然打印不完整的数据集!!
现在对于一个真正不完整的数据集,我也得到了相同的结果!!
您对 any
and or
的工作原理存在根本性的误解。我建议回去看看我链接到的文档。
你想要:
names = ['M1','M2','M3','M4','M5','M6','M7','M8','M9','M10','M11',
'M12','M13','M14','M15','M16','M17','M18','M19','M20', 'TM1']
if any(name not in df.columns for name in names):
...
else:
print('incompatable dataset')
或者(这实际上只是为了获得最小的性能提升),您可以使用 set difference(returns 所有值都在 names
中,但不在 df.columns
):
if not set(names) - set(df.columns):
...