gpt4 book ai didi

python - 尝试用 python 进行分组和总结

转载 作者:太空宇宙 更新时间:2023-11-03 20:46:23 24 4
gpt4 key购买 nike

基本上,我希望垃圾箱位于其自身的一列中,请参阅代码和输出。 Python

    graph_data = housing_data.groupby(['Date','Bins']).Price.mean()

graph_data
Date     Bins    
2016-01 (5, 10] NaN
(10, 15] 1.009000e+06
2016-03 (0, 5] 1.244532e+06
(5, 10] 1.221559e+06
(10, 15] 1.098541e+06
2016-04 (0, 5] 1.085015e+06
(5, 10] 1.086503e+06
(10, 15] 9.220241e+05
2016-05 (0, 5] 1.019418e+06
(5, 10] 1.139064e+06
(10, 15] 9.416809e+05

任何帮助将不胜感激。

最佳答案

我认为您要求将数据 reshape 为所谓的宽格式数据。您当前拥有的是长格式数据。要在 pandas 中在两者之间来回切换,请使用 meltpivot (或 stackunstack )。 ( Check out this postmy more general post 。)

我没有你的数据,但请尝试

(housing_data.groupby(['Date', 'Bins'])
.agg({'Price': 'mean'})
.reset_index()
.pivot(index='Date', columns='Bins',
values='Price'))

(不幸的是,reset_index 行强制 pandas 在执行 agg 命令之后再次将 Date 识别为列。)

如果你想重命名垃圾箱,你可以使用 renamegroupby 调用之前,但如果您使用 pd.cut 创建自己的 bin,会更容易。以下是使用iris的示例:

import seaborn as sns
import pandas as pd

iris = sns.load_dataset('iris')
iris['bins'] = pd.cut(iris['sepal_length'],
bins=3,
labels=['lo', 'med', 'hi'])
(iris.groupby(['species', 'bins'])
.agg({'sepal_length': 'mean'})
.reset_index()
.pivot(index='species', columns='bins',
values='sepal_length'))
bins        lo          med         hi
species
setosa 4.959574 5.733333 NaN
versicolor 5.281818 6.055556 6.900000
virginica 4.900000 6.265625 7.294118

关于python - 尝试用 python 进行分组和总结,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56572359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com