熊猫:根据组汇总过滤DataFrameGroupBy(df.groupby)

时间:2020-04-28 19:23:30

标签: python pandas dataframe pandas-groupby

df
| a  | b |
|----|---|
| 10 | 1 |
| 10 | 5 |
| 11 | 1 |

使用

直接将其分组

grouped = df.groupby('a')

让我们只获得其中的组

selector = grouped.b.max() - grouped.b.min() >= 3

收益

df
| a  |       |
|----|-------|
| 10 | True  |
| 11 | False |

我的问题是,在使用df = df.loc[<filter condition>]元素时,DataFrameGroupBy等价是什么?

grouped.filter(..) returns a DataFrame

在基于.aggreate()函数进行过滤的同时,是否可以保留组?谢谢!

3 个答案:

答案 0 :(得分:2)

您可以使用np.ptp(峰到峰)

df.groupby('a').b.agg(np.ptp) > 3

a
10     True
11    False
Name: b, dtype: bool

答案 1 :(得分:1)

对于df.loc[]等价问题,您可以执行以下操作:

df=df.set_index('a')\
    .loc[df.groupby('a').b.agg(np.ptp).gt(3)]\
    .reset_index()

或者(内部联接解决方案):

selector=df.groupby('a').b.agg(np.ptp).gt(3)
selector=selector.loc[selector]
df=df.merge(selector, on='a', suffixes=["", "_dropme"])
df=df.loc[:, filter(lambda col: "_dropme" not in col, df.columns)]

输出:

    a  b
0  10  1
1  10  5

PS +1 @rafaelc-对于.ptp事物

答案 2 :(得分:0)

可悲的是,我没有找到一个直接的解决方案。所以我使用2 groupby来解决这个问题:

# Build True/False Series for filter criteria
selector = df.groupby('a').b.agg(np.ptp) > 3

# Only select those 'a' which have True in filter criteria
selector = selector.loc[selector == True]

# Re-Create groups of 'a' with the filter criteria in place
# Only those groups for 'a' will be created, where the MAX-MIN of 'b' are > 3.
grouped = df.loc[df['a'].isin(selector.index)].groupby('a')
相关问题