python - 最小组大小的 Pandas groupby

标签 python python-2.7 pandas grouping

我有一个形状为 (450 000, 15) 的数据框 df,其中包含有关用户的信息,每一行都是一个不同的用户,具有 13 个特征(年龄、性别、家乡.. .) 和 1 个 bool 变量,用户是否有车。

我想重新分组我的用户以找出哪些组拥有最多的汽车,但我需要在一个组中保留至少 2500 个用户以保持统计相关性。

test= df.groupby(['Gender'])
test.size() # check the groups size
Gender
Female    150000
Male      300000
dtype: int64

到目前为止一切顺利,我有超过 2500 个用户组。所以我有另一个分组标准:

test2= df.groupby(['Gender','Age'])  
test2.size()
Gender   Age
Female   <30     15022
         30-90   134960
         90+     18
Male     <20     5040
         20-90   291930
         90+     3030    
dtype: int64

如我们所料,我现在的群组用户很少...

我想要这样的东西:

Gender   
Female   150 000 # Don't split here because groups will be too small

# Here I can split, because group size > 2500 :
Gender   Age
Male     <20     5040 
         20-90   291930
         90+     3030    
dtype: int64

我没有找到根据大小标准对 groupby 数据框进行分组的方法,所以我想知道处理这个问题的 pythonic 方法是什么。

由于我有 13 个特征来对我的用户进行分组,我也想知道分组顺序:我应该先按性别再按年龄分组,还是相反?这在使用具有停止条件的多个变量时会产生影响。

我不需要使用 pandas,但我认为它是合适的。输出应如下所示:

name_of_group  group_size
Female         150000
Male, <20      5040
Male, 20-90    291930
Male, 90+      3030

最佳答案

groupby 必须根据“键”进行分组,该“键”对于每一行都必须单独计算。也就是说,无法根据某些标准进行分组,这些标准取决于您在创建组之前不会知道的聚合特征(例如其大小)。您可以编写代码来尝试不同的分组并使用一些启发式方法来决定哪个是“最佳”,但没有为此内置任何内容。

关于python - 最小组大小的 Pandas groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41941062/

相关文章:

python - Seaborn countplot,每组归一化 y 轴

python - 使用 pandas datareader 时出现 Keyerror 'Date'

python - 找不到满足 mediapipe 要求的版本(来自版本 : none)

python - 从 csv 数据集在 python 中创建邻接矩阵

Python:Groupby 第一个非 NaN 值

python - 如何重命名 Pandas 系列?

python - 用一个副本遍历所有列表

rest - Tornado 可以处理分页吗?

python - Pyramid BeforeRender 订阅和访问 .request

python - tkinter 选项菜单不显示选择