【问题标题】:Filter Pandas DataFrame for elements in list [duplicate]过滤列表中元素的 Pandas DataFrame [重复]
【发布时间】:2015-12-13 15:25:49
【问题描述】:

我有一个包含值和附加信息的 pandas DataFrame。我希望能够提取仅属于一种信息的值。我不知道会查询哪些值和多少个值。因此,有可能一次只调用具有附加信息“foo”的值,有时会调用附加信息“bar”和“baz”,因此使用简化的 DataFrame

import pandas as pd
df = pd.DataFrame(
    [[1, 'foo'], [2, 'bar'], [3, 'baz']], columns=['value', 'id'])

我试过了

result = df[df.id in ['foo', 'bar']]

但我只是得到一个 ValueError:一个系列的真值是模棱两可的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。但是我无法使用 any()-Function 来给我结果...... .

【问题讨论】:

  • 是的,它是重复的。搜索的时候没找到上面那个。。。。

标签: python pandas


【解决方案1】:

使用isin 根据传入列表测试列的成员资格:

In [30]:
df[df['id'].isin(['foo','bar'])]

Out[30]:
   value   id
0      1  foo
1      2  bar

这里isin生成一个布尔掩码,我们用它来过滤df:

In [31]:    
df['id'].isin(['foo','bar'])

Out[31]:
0     True
1     True
2    False
Name: id, dtype: bool

【讨论】:

    猜你喜欢
    • 2018-01-02
    • 2020-03-22
    • 1970-01-01
    • 2016-10-31
    • 2018-09-02
    • 2015-12-22
    • 2021-06-16
    • 1970-01-01
    • 2016-02-22
    相关资源
    最近更新 更多