gpt4 book ai didi

python - Pandas DataFrame --> GroupBy --> 多索引过程

转载 作者:行者123 更新时间:2023-12-01 08:38:58 24 4
gpt4 key购买 nike

我正在尝试将以下形式的大型 DataFrame 重组为 MultiIndex:

        date  store_nbr  item_nbr  units  snowfall  preciptotal  event
0 2012-01-01 1 1 0 0.0 0.0 0.0
1 2012-01-01 1 2 0 0.0 0.0 0.0
2 2012-01-01 1 3 0 0.0 0.0 0.0
3 2012-01-01 1 4 0 0.0 0.0 0.0
4 2012-01-01 1 5 0 0.0 0.0 0.0

我想按 store_nbr (1-45) 进行分组,在每个 store_nbr 组中按 item_nbr (1-111) 进行分组,然后进行分组相应的索引对(例如,store_nbr=12、item_nbr=109),按时间顺序显示行,以便排序的行看起来像,例如:

store_nbr=12, item_nbr=109:   date=2014-02-06, units=0, snowfall=...
date=2014-02-07, units=0, snowfall=...
date=2014-02-08, units=0, snowfall=...
... ...
store_nbr=12, item_nbr=110: date=2014-02-06, units=0, snowfall=...
date=2014-02-07, units=1, snowfall=...
date=2014-02-08, units=1, snowfall=...
...

看起来groupbyset_index的某种组合在这里可能有用,但我在下面的行之后陷入困境:

grouped = stores.set_index(['store_nbr', 'item_nbr'])

这会产生以下多重索引:

                         date  units  snowfall  preciptotal  event
store_nbr item_nbr
1 1 2012-01-01 0 0.0 0.0 0.0
2 2012-01-01 0 0.0 0.0 0.0
3 2012-01-01 0 0.0 0.0 0.0
4 2012-01-01 0 0.0 0.0 0.0
5 2012-01-01 0 0.0 0.0 0.0

有人对这里有什么建议吗?有没有一种简单的方法可以通过操作 groupby 对象来做到这一点?

最佳答案

您可以使用以下方式对行进行排序:

df.sort_values(by='date')

关于python - Pandas DataFrame --> GroupBy --> 多索引过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53575037/

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