Pandas:基于组聚合筛选DataFrameGroupBy(df.groupby)

2024-09-28 20:48:38 发布

您现在位置:Python中文网/ 问答频道 /正文

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 |

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

^{} returns a ^{}

在基于.aggreate()函数进行过滤时,是否有办法保留组?谢谢


Tags: falsetrue元素dffilterminconditionselector
3条回答

遗憾的是,我没有找到一个直接的解决办法。。所以我用2groupby解决了这个问题:

# 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')

对于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事情

您可以使用^{}(峰到峰)

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

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

相关问题 更多 >