首页 > 解决方案 > 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"

仍然打印不完整的数据集!!


现在对于一个真正不完整的数据集,我也得到了相同的结果!!

标签: pythonpandasif-statementbooleanboolean-logic

解决方案


你对如何anyor工作有一个根本性的误解。我建议回去看看我链接到的文档。

你要:

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):
   ...

推荐阅读