为列表中的元素过滤 Pandas DataFrame
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32618812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filter Pandas DataFrame for elements in list
提问by MichaelA
I have a pandas DataFrame that contains values and additional information. I'd like to be able to extract values that only belong to one sort of information. I don't know upfront which and how many values will be queried. So it would be possible that one time only values with the additional information "foo" will be called, sometimes with the additional information 'bar' and 'baz', so with a simplified DataFrame
我有一个包含值和附加信息的 Pandas DataFrame。我希望能够提取仅属于一种信息的值。我不知道将查询哪些值和多少值。因此,有可能一次只调用具有附加信息“foo”的值,有时会调用附加信息“bar”和“baz”,因此使用简化的 DataFrame
import pandas as pd
df = pd.DataFrame(
[[1, 'foo'], [2, 'bar'], [3, 'baz']], columns=['value', 'id'])
I tried
我试过
result = df[df.id in ['foo', 'bar']]
But I just get a ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). But I can't geht the any()-Function to give me results... .
但我只是得到一个 ValueError:一个系列的真值是不明确的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。但是我不能用 any()-Function 来给我结果......
回答by EdChum
Use isinto test membership of a column against the passed in list:
用于isin根据传入的列表测试列的成员资格:
In [30]:
df[df['id'].isin(['foo','bar'])]
Out[30]:
value id
0 1 foo
1 2 bar
Here isingenerates a boolean mask, we use this to filter the df:
这里isin生成一个布尔掩码,我们用它来过滤 df:
In [31]:
df['id'].isin(['foo','bar'])
Out[31]:
0 True
1 True
2 False
Name: id, dtype: bool

