python-3.x - 根据 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 。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
布尔值反转True
为False
和:False
True
f = lambda x: not (x['price'].isnull() & x['date'].eq('2019-04-01')).any()
df = df.groupby(['city','district']).filter(f)
推荐阅读
- angular - 如何在 Angular 6+ 中为库级接口的应用程序级具体实现定义可摇树的提供程序?
- python - 如果它们包含给定的短语,则删除python中字符串列表的所有元素
- sql - 使用带有窗口函数的递归 CTE
- makefile - 传递要在 MAKEFLAGS 中扩展的变量
- rust - 如何在 Rust 中开发词典?
- google-apps-script - 无法在电子表格上创建可安装触发器
- python-3.x - RobotFramework:在 For 循环中使用变量列表
- c# - 为什么 sonarlint 建议结合 try...catch 语句?
- amazon-web-services - 如何更改 API Gateway 响应
- php - 如何使用 PHP 将文件池图像上传到 MySql?