繁体   English   中英

熊猫groupby筛选器,删除一些组

[英]pandas groupby filter, drop some group

我有groupby对象

grouped = df.groupby('name')
for k,group in grouped:    
    print group

有3组barfoofoob​​ar

  name  time  
2  bar     5  
3  bar     6  


  name  time  
0  foo     5  
1  foo     2  

  name      time  
4  foobar     20  
5  foobar     1  

我需要过滤这些组并删除所有时间不超过5的组。在我的示例中,应该删除组foo。 我正在尝试使用功能filter()

grouped.filter(lambda x: (x.max()['time']>5))

但是x显然不仅是数据帧格式的组。

假设您的最后一行代码实际上应该是>5而不是>20 ,那么您将执行以下操作:

grouped.filter(lambda x: (x.time > 5).any())

正如您正确地发现的那样, x实际上是所有索引的DataFrame ,其中name列与for循环中k中的键匹配。

因此,您要根据时间列中是否有大于5的时间进行过滤,请执行上述(x.time > 5).any()进行测试。

我还不习惯python,numpy或pandas。 但是我正在研究类似问题的解决方案,所以让我以这个问题为例来报告我的答案。

import pandas as pd

df = pd.DataFrame()
df['name'] = ['foo', 'foo', 'bar', 'bar', 'foobar', 'foobar']
df['time'] = [5, 2, 5, 6, 20, 1]

grouped = df.groupby('name')
for k, group in grouped:
    print(group)

我的答案1:

indexes_should_drop = grouped.filter(lambda x: (x['time'].max() <= 5)).index
result1 = df.drop(index=indexes_should_drop)

我的答案2:

filter_time_max = grouped['time'].max() > 5
groups_should_keep = filter_time_max.loc[filter_time_max].index
result2 = df.loc[df['name'].isin(groups_should_keep)]

我的答案3:

filter_time_max = grouped['time'].max() <= 5
groups_should_drop = filter_time_max.loc[filter_time_max].index
result3 = df.drop(df[df['name'].isin(groups_should_drop)].index)

结果

    name    time
2   bar     5
3   bar     6
4   foobar  20
5   foobar  1

我的Answer1不使用群组名称删除群组。 如果需要组名,可以通过编写以下df.loc[indexes_should_drop].name.unique()获得它们: df.loc[indexes_should_drop].name.unique()

grouped['time'].max() <= 5grouped.apply(lambda x: (x['time'].max() <= 5)).index返回相同的结果。

filter_time_max的索引是组名。 它不能用作直接删除的索引或标签。

name
foo        True
bar       False
foobar    False
Name: time, dtype: bool

暂无
暂无

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

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