【问题标题】:python pandas loc - filter for list of values [duplicate]python pandas loc - 过滤值列表[重复]
【发布时间】:2018-01-29 21:59:15
【问题描述】:

这应该非常简单,但我无法让它工作。

我想根据两个或多个值过滤我的数据集。

#this works, when I filter for one value
df.loc[df['channel'] == 'sale'] 

#if I have to filter, two separate columns, I can do this
df.loc[(df['channel'] == 'sale')&(df['type']=='A')] 

#but what if I want to filter one column by more than one value?
df.loc[df['channel'] == ('sale','fullprice')] 

这必须是 OR 语句吗?我可以使用 in? 在 SQL 中执行类似操作?

【问题讨论】:

  • df.loc[df['channel'].isin(['sale','fullprice'])]

标签: python pandas filter pandas-loc


【解决方案1】:

有一个 df.isin(values) 方法用于测试 DataFrame 中的每个元素是否包含在 values 中。 因此,正如@MaxU 在评论中所写,您可以使用

df.loc[df['channel'].isin(['sale','fullprice'])]

按多个值过滤一列。

【讨论】:

  • df.loc[df['channel'].apply(lambda x: x in ['sale','fullprice'])] 也可以。它不像使用df.isin 那样简洁,但可以修改为仅根据一列检查任何复杂的条件。
  • 是的,当然。
猜你喜欢
  • 2018-01-02
  • 2018-03-21
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
  • 2019-07-26
  • 2016-11-10
  • 2020-08-13
  • 2020-01-16
相关资源
最近更新 更多