python - pandas DataFrame 列中的布尔运算
问题描述
我试图找出我的 DataFrame 列中是否存在特定列,但我遇到了一些问题。
我做什么:使用布尔运算“not in”(我已经尝试过any(),all(),“in”)来查找特定的列标题,它似乎无法正常工作!
假设我的 DataFrame 列标题是:
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 具有所有询问的列标题,if 语句仍然显示“不完整的数据集”消息!!我也尝试过“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
和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')
或者(这实际上只是为了最小的性能增益),您可以使用设置的差异(返回所有值而不是 innames
但不是 in df.columns
):
if not set(names) - set(df.columns):
...
推荐阅读
- java - 无法从 EditText 中获取文本
- python - python中的树不打印子元素
- python - SQLite3:运行python代码后的空数据库
- c++ - C++ 多类型赋值
- github-actions - 在 Github 操作上安装 R 包本身
- julia - LoadError:Julia for 循环中的 UndefVarError
- java - Android WorkManager 和 Worker
- gcc - arm-none-eabi-gcc 与 nucleo L432KC 板
- java - 无法为简单的控制器运行 Spring Boot 测试
- python - 是否可以从条目小部件或文本小部件在树视图中插入多行文本?或类似的东西?