给定一个数据框,如下所示:
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
我需要的过滤器分组的行city
和district
当同时满足以下两个条件得到满足:date
是2019-04-01
和price
是NaN
。
我已经使用以下代码进行了测试:
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 |
, isnull
to notna
, eq
tone
和any
to 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 True
toFalse
和False
to True
:
f = lambda x: not (x['price'].isnull() & x['date'].eq('2019-04-01')).any()
df = df.groupby(['city','district']).filter(f)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句