Pandas pd.cut 和 pd.groupby 不匹配循环聚合

Pandas pd.cut with pd.groupby not matching loop aggregation

提问人:AKA_Tom 提问时间:11/6/2023 更新时间:11/6/2023 访问量:40

问:

我正在计算热图的一些统计数据(分箱数据的平均值)。我对使用 pandorable 方法的结果持怀疑态度,因此我尝试使用嵌套的 for 循环和数据帧掩码重新计算。除了 1 或 2 条记录外,结果几乎相同。

聚合方法#1

intervals = pd.cut(df['BC'], bins=16, right=True)

df = df.groupby(['A',intervals]).mean().unstack(fill_value=0).stack().reset_index(names=['A', 'BC_bins'])

| A  | BC_bins    | Y Mean |
| ---|------------|--------|
| 0  | (.05,.07]  | 464    |
| 1  | (.07,.09]  | 417    | 
| 2  | (.09,.12]  | 377    |
| 3  | (.12,.14]  | 338    |
| 4  | (.14,.16]  | 309    |
| 5  | (.16,.18]  | 290    |
| 6  | (.18,.20]  | 277    |
| 7  | (.20,.23]  | 268    |
| 8  | (.23,.25]  | 234    |
| 9  | (.25,.27]  | 239    |
| 10 | (.27,.29]  | 233    |
| 11 | (.29,.31]  | 230    |
| 12 | (.31,.34]  | 228    |
| 13 | (.34,.36]  | 226    |
| 14 | (.36,.38]  | 223    |
| 15 | (.38,.40]  | 221    |

方法 2

intervals = pd.cut(df['BC'], bins=16, right=True)

for a in (df['A'].unique()):
    for i in intervals.unique():
        subset = df[(df['BC'] > i.left) & (df['BC'] <= i.right) & (df['A'] == a)]
        subset.mean()  # --> send to excel sheet and compare with approach
| A  | BC_bins    | Y Mean |
| ---|------------|--------|
| 0  | (.05,.07]  | 464    |
| 1  | (.07,.09]  | 417    | 
| 2  | (.09,.12]  | 377    |
| 3  | (.12,.14]  | 338    |
| 4  | (.14,.16]  | 309    |
| 5  | (.16,.18]  | 290    |
| 6  | (.18,.20]  | 277    |
| 7  | (.20,.23]  | 254    |
| 8  | (.23,.25]  | no data?|
| 9  | (.25,.27]  | 239    |
| 10 | (.27,.29]  | 233    |
| 11 | (.29,.31]  | 230    |
| 12 | (.31,.34]  | 228    |
| 13 | (.34,.36]  | 226    |
| 14 | (.36,.38]  | 223    |
| 15 | (.38,.40]  | 221    |

一切看起来都很好,直到.当我查看方法 2 的汇总统计数据时,我在该箱中没有任何样本,所以我的结果只是 NA?我认为这是歪曲的.希望有人能阐明这种行为。我将更改箱的数量,看看我是否进行了相同的观察。A=7,8A=8A=7

我对方法 #1 的实现是否有效,似乎是有效的。我在教科书和其他帖子中看到过使用 pd.cut 和 pd.groupby 完成的类似技术。

另外,我应该注意,箱子内样本的分布不一定是正常的,但我目前并不真正关心这种特定的分析。我可能会查看 pd.qcut() 看看是否有任何变化。只是试图在差异之间弄清楚。

Python Pandas 统计 分析 分箱

评论

1赞 Panda Kim 11/6/2023
stackoverflow.com/help/minimal-reproducible-example
0赞 mozway 11/6/2023
你有整数吗?您确定要对所有数据进行采样吗?A

答: 暂无答案