繁体   English   中英

pandas:按多种条件过滤组?

[英]pandas: filter group by multiple conditions?

我有一个如下所示的数据框:

df = pd.DataFrame([
  {'id': 123, 'date': '2016-01-01', 'is_local': True },
  {'id': 123, 'date': '2017-01-01', 'is_local': False },
  {'id': 124, 'date': '2016-01-01', 'is_local': True },
  {'id': 124, 'date': '2017-01-01', 'is_local': True }
])
df.date = df.date.astype('datetime64[ns]')

我希望获得2016 is_local为True的所有ID列表,但2017年初为False。我开始按ID进行分组:

gp = df.groupby('id')

然后我试过这只是为了过滤这些条件中的第二个(作为一种入门方式),但它返回所有组:

gp.apply(lambda x: ~x.is_local & (x.date > '2016-12-31'))

如何以我需要的方式过滤?

d1 = df.set_index(['id', 'date']).is_local.unstack()
d1.index[d1['2016-01-01'] & ~d1['2017-01-01']].tolist()

[123]

另一种方法是通过旋转

In [24]: ids_by_dates = df.pivot(index='id', columns='date',values='is_local')

In [25]: ids_by_dates['2016-01-01'] & ~ids_by_dates['2017-01-01']
Out[25]: 
id
123     True
124    False

您可以尝试使用datetime库中的datetime模块,并为数据帧传递多个条件

from datetime import datetime
df = pd.DataFrame([
  {'id': 123, 'date': '2016-01-01', 'is_local': True },
  {'id': 123, 'date': '2017-01-01', 'is_local': False },
  {'id': 124, 'date': '2016-01-01', 'is_local': True },
  {'id': 124, 'date': '2017-01-01', 'is_local': True }
])
df.date = df.date.astype('datetime64[ns]')

使用多个条件来切割所需的数据帧

a = df[(df.is_local==True) & (df.date<datetime(2016,12,31) & (df.date>datetime(2015,12,31))]
b = df[(df.is_local==False) & (df.date<datetime(2017,12,31)) & (df.date>datetime(2016,12,31))]

稍后使用pandas连接

final_df = pd.concat((a,b))

将输出第1行和第2行

    date        id  is_local
2   2016-01-01  124 True
1   2017-01-01  123 False

单行如下

final_df = pd.concat((df[(df.is_local==True) & (df.date<datetime(2016,12,31) & (df.date>datetime(2015,12,31))], df[(df.is_local==False) & (df.date<datetime(2017,12,31)) & (df.date>datetime(2016,12,31))]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM