python - 过滤 Pandas 中的数据帧 : use a list of conditions

标签 python pandas

我有一个具有两个维度的 Pandas 数据框:“col1”和“col2”

我可以使用以下方法过滤这两列的某些值:

df[ (df["col1"]=='foo') & (df["col2"]=='bar')]

有什么方法可以同时过滤两列吗?

我天真地尝试将数据帧限制为两列,但我对等式第二部分的最佳猜测不起作用:

df[df[["col1","col2"]]==['foo','bar']]

给我这个错误

ValueError: Invalid broadcasting comparison [['foo', 'bar']] with block values

我需要这样做,因为列的名称以及设置条件的列数会有所不同

最佳答案

据我所知,在 Pandas 中没有办法让你做你想做的事。然而,尽管以下解决方案可能不是最漂亮的,但您可以按如下方式压缩一组并行列表:

cols = ['col1', 'col2']
conditions = ['foo', 'bar']

df[eval(" & ".join(["(df['{0}'] == '{1}')".format(col, cond) 
   for col, cond in zip(cols, conditions)]))]

字符串连接结果如下:

>>> " & ".join(["(df['{0}'] == '{1}')".format(col, cond) 
    for col, cond in zip(cols, conditions)])

"(df['col1'] == 'foo') & (df['col2'] == 'bar')"

然后您可以使用 eval 有效地评估:

df[eval("(df['col1'] == 'foo') & (df['col2'] == 'bar')")]

例如:

df = pd.DataFrame({'col1': ['foo', 'bar, 'baz'], 'col2': ['bar', 'spam', 'ham']})

>>> df
  col1  col2
0  foo   bar
1  bar  spam
2  baz   ham

>>> df[eval(" & ".join(["(df['{0}'] == {1})".format(col, repr(cond)) 
            for col, cond in zip(cols, conditions)]))]
  col1 col2
0  foo  bar

关于python - 过滤 Pandas 中的数据帧 : use a list of conditions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33699886/

相关文章:

python - Node.js/Electron 和 Python 之间的异步 IPC

python - Pandas to_datetime() 没有检测到列

python - 我应该如何在不删除行的情况下将值更改为 0

python - 将 DataFrame 变量名称作为字符串传递

python - 从字典中读取字典

python - 将 SSML 和 Python 与 Azure 语音结合使用

python - 为什么我的第二个标签没有更新?

python - 了解与 Pandas 连接时使用 join_axes 的 FutureWarning

python - 将评论插入 jupyter notebook

Python 正则表达式匹配段落