【发布时间】: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