首页 > 解决方案 > 根据 Pandas 中的多个条件过滤分组的行

问题描述

给定如下数据框:

  city district        date  price
0   bj       cy  2019-03-01    NaN
1   bj       cy  2019-04-01    6.0
2   sh       hp  2019-03-01    4.0
3   sh       hp  2019-04-01    3.0
4   bj       hd  2019-03-01    7.0
5   bj       hd  2019-04-01    NaN

当满足以下两个条件时,我需要过滤分组的行: iscity和is 。districtdate2019-04-01priceNaN

我已经使用以下代码进行了测试:

df['date'] = pd.to_datetime(df['date']).dt.date.astype(str)
df.groupby(['city','district']).filter(lambda x: (x['price'].isnull() & x['date'].isin(['2019-04-01'])).any())

出去:

  city district        date  price
4   bj       hd  2019-03-01    7.0
5   bj       hd  2019-04-01    NaN

另一个测试:

df.groupby(['city','district']).filter(lambda x: (x['price'].isnull() & x['date']).any())

出去:

  city district        date  price
0   bj       cy  2019-03-01    NaN
1   bj       cy  2019-04-01    6.0
4   bj       hd  2019-03-01    7.0
5   bj       hd  2019-04-01    NaN

但我需要如下。如何修改上面的代码?非常感谢。

  city district      date  price
0   bj       cy  2019/3/1    NaN
1   bj       cy  2019/4/1    6.0
2   sh       hp  2019/3/1    4.0
3   sh       hp  2019/4/1    3.0

标签: python-3.xpandasdataframe

解决方案


我认为你需要反转掩码 - 在这里&to |, isnullto notna, eqtoneanyto all

df['date'] = pd.to_datetime(df['date'])

f = lambda x: (x['price'].notna() | x['date'].ne('2019-04-01')).all()
df = df.groupby(['city','district']).filter(f)
print (df)
  city district       date  price
0   bj       cy 2019-03-01    NaN
1   bj       cy 2019-04-01    6.0
2   sh       hp 2019-03-01    4.0
3   sh       hp 2019-04-01    3.0

或者可能用于将not布尔值反转TrueFalse和:FalseTrue

f = lambda x: not (x['price'].isnull() & x['date'].eq('2019-04-01')).any()
df = df.groupby(['city','district']).filter(f)

推荐阅读