给出如下数据框:
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
是{{ 1}}。
我已经用以下代码进行了测试:
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
答案 0 :(得分:1)
我认为您需要反转掩码-这里&
到|
,isnull
到notna
,eq
到ne
和{{1 }}到any
:
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
转换为True
并将False
转换为False
:
True