我有一个具有两个维度的 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/