根据 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

我需要的过滤器分组的行citydistrict当同时满足以下两个条件得到满足:date2019-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
耶斯列

我认为你需要反转掩码 - 这里&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用于 invert boolean TruetoFalseFalseto True

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章