【问题标题】:Using the "in" operator in pandas.DataFrame without getting "ambiguous error [duplicate]在 pandas.DataFrame 中使用“in”运算符而不会出现“模糊错误 [重复]
【发布时间】:2020-06-09 18:13:34
【问题描述】:

我有一个pd.DataFrame

import pandas as pd
country = ['US', 'US', 'US', 'UK', 'UK', 'UK']
year = ['1990', '1991', '2020', '1990', '1991', '2020']
people = [20, 34, 456, 5, 7, 300]

df = pd.DataFrame(zip(country, year, people), columns = ['country', 'year', 'people'])
country year    people
0   US  1990    20
1   US  1991    34
2   US  2020    456
3   UK  1990    5
4   UK  1991    7
5   UK  2020    300

我希望找到年份“2020”和“1990”。 我知道这可以通过以下方式实现:

df.loc[(df.year == '2020') | (df.year == '1990')]

df.query('year == [\'2020\', \'1990\']')

获取输出:

country year    people
0   US  1990    20
2   US  2020    456
3   UK  1990    5
5   UK  2020    300

但是,我想使用 in 运算符执行此“查询”。 尝试:

df.loc[df['year'] in ['2020', '1990']]

引发错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我希望在我的 pandas.DataFrame 子集中使用 in 运算符,因为它需要最少的输入。

缓解in 运算符引发的此错误的最佳方法是什么?

【问题讨论】:

  • df.loc[df['year'].isin(['2020', '1990'])]

标签: python-3.x pandas dataframe subset boolean-expression


【解决方案1】:
df[df['year'].isin(['1990','2020'])]

df.loc[df['year'].isin(['1990','2020'])]

【讨论】:

    【解决方案2】:

    使用 .isin() 函数。

    df.loc[df['year'].isin(['1990','2020'])]

    您输入一个您想要“年份”的选项列表,pandas 将返回一系列布尔值。该系列将依次由 .loc() 解释以仅返回 df['year'] == 所需值的行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-12
      • 2023-01-18
      • 1970-01-01
      • 2018-08-29
      • 2018-09-13
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      相关资源
      最近更新 更多