【发布时间】:2016-04-03 19:11:43
【问题描述】:
DataFrameGroupby.filter 方法过滤组,并返回包含通过过滤器的行的DataFrame。
但是我可以做些什么来获得一个新的DataFrameGroupBy 对象而不是过滤后的DataFrame?
例如,假设我有一个 DataFrame df 有两列 A 和 B。我想为列A 的每个值获取列B 的平均值,只要该组中至少有5 行:
# pandas 0.18.0
# doesn't work because `filter` returns a DF not a GroupBy object
df.groupby('A').filter(lambda x: len(x)>=5).mean()
# works but slower and awkward to write because needs to groupby('A') twice
df.groupby('A').filter(lambda x: len(x)>=5).reset_index().groupby('A').mean()
# works but more verbose than chaining
groups = df.groupby('A')
groups.mean()[groups.size() >= 5]
【问题讨论】:
标签: python python-3.x pandas dataframe grouping