【问题标题】:how to filter a data frame based on a column value (country) in pandas [duplicate]如何根据熊猫中的列值(国家)过滤数据框[重复]
【发布时间】:2021-12-30 07:52:21
【问题描述】:

我有一个大数据框,我想根据COUNTRY 列对其进行过滤。我需要来自欧洲国家的数据,我写道:

country=['Austria', 'Belgium', 'Bulgaria', 'Croatia', 'Republic of Cyprus', 'Czech Republic', 
'Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary', 'Ireland', 'Italy', 
'Latvia', 'Lithuania', 'Luxembourg', 'Malta', 'Netherlands', 'Poland', 'Portugal', 'Romania', 
'Slovakia', 'Slovenia', 'Spain' , 'Sweden']
filtered_df = Data[Data.COUNTRY.isin(country)]'

但它没有在数据框中显示这些提到的国家的行!有什么想法吗?

【问题讨论】:

  • 试试filtered_df = Data[Data.COUNTRY.str.isin(country)]
  • 您可以发布数据框的示例吗?
  • @thomask 我得到了这个:StringMethods'对象没有属性'isin'

标签: python pandas dataframe filtering


【解决方案1】:

我会使用query,这是使用 iris 数据集的示例。

iris = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv')
x1 = ['setosa', 'versicolor']
iris.query('species in @x1')

所以对你来说是

Data.query('COUNTRY in @country')

【讨论】:

  • country=['Austria', 'Belgium', 'Bulgaria', 'Croatia', 'Republic of Cyprus', 'Czech Republic', 'Denmark', 'Estonia', 'Finland', 'France', 'Germany', 'Greece', 'Hungary', 'Ireland', 'Italy', 'Latvia', 'Lithuania', 'Luxembourg', 'Malta', 'Netherlands', 'Poland', 'Portugal', 'Romania', 'Slovakia', 'Slovenia', 'Spain' , 'Sweden'] Data.query('species in @country')
  • 但它不起作用!
  • 查看编辑,speciesiris 中的一列
猜你喜欢
  • 2020-08-08
  • 2016-08-31
  • 2020-08-16
  • 1970-01-01
  • 2021-12-01
  • 2019-12-12
  • 1970-01-01
  • 2013-06-09
  • 2020-05-05
相关资源
最近更新 更多