gpt4 book ai didi

python - 将多索引 pandas 数据框转换为单索引

转载 作者:行者123 更新时间:2023-12-02 03:59:10 24 4
gpt4 key购买 nike

我有一个如下所示的数据框:

        i_id    q_id
month category_bucket
Aug Algebra Tutoring 187 64
Balloon Artistry 459 401
Carpet Installation or Replacement 427 243
Dance Lessons 181 46
Landscaping 166 60
Others 9344 4987
Tennis Instruction 161 61
Tree and Shrub Service 383 269
Wedding Photography 161 49
Window Repair 140 80
Wiring 439 206
July Algebra Tutoring 555 222
Balloon Artistry 229 202
Carpet Installation or Replacement 140 106
Dance Lessons 354 115
Landscaping 511 243
Others 9019 4470
Tennis Instruction 613 324
Tree and Shrub Service 130 100
Wedding Photography 425 191
Window Repair 444 282
Wiring 154 98

这是一个多索引数据框,以月份和类别桶作为索引。并将 i_id、q_id 作为列

我通过对正常数据框执行 groupby 操作得到了这个,如下所示

invites_combined.groupby(['month', 'category_bucket'])[["i_id","q_id"]].count()

我基本上想要一个数据框,其中有 4 列,每列 2 列代表 i_id,q-Id 代表月份,还有一列代表类别_bucket。因此,基本上将上述多索引数据帧转换为单个索引,以便我可以访问这些值。

目前,我很难访问特定月份和类别值的 i_id、q_id 值。

如果您觉得有一种更简单的方法来访问每个类别和月份的 i_id 和 q_id 值,而无需转换为单个索引,那也很好。

不过,单个索引会更容易循环到月份和类别的每个组合的每个值中。

最佳答案

看来你需要reset_indexMultiIndex 转换为 columns:

df = df.reset_index()

关于python - 将多索引 pandas 数据框转换为单索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42642095/

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