【问题标题】:Python, Pandas Dataframe get the index back after a group byPython,Pandas Dataframe 在分组后取回索引
【发布时间】:2015-01-26 19:57:47
【问题描述】:

我有一个名为“class_price_df”的 Pandas 数据框:

                           email                   cat           class
0               trangthanhtin@yahoo.com     Mobiles & Tablets      1
1                    concomai@yahoo.com     Mobiles & Tablets      4
2                   yenvo.ier@gmail.com     Mobiles & Tablets      2
3                   quyenvy71@yahoo.com     Mobiles & Tablets      4

我按“电子邮件”和“猫”分组以获得最大“类”:

class_price_df = class_price_df.groupby(['email','cat']).max().unstack('cat').fillna(0)

但是输出是:

cat                               Computers & Laptops  Consumer Electronics   
email                                                                         
+coicon7879@gmail.com                               2                     0   
+haiphong82lk@yahoo.com                             0                     2   
+nguyentrungchanhbd@gmai.com                        0                     0   
-abc@gmail.com                                      0                     0   
001kukuku@gmail.com                                 0                     4   
002pnk@gmail.com                                    1                     0   
007.heineken@gmail.com                              4                     0   
007.leson@gmail.com                                 0                     0   

我怎样才能找回我的“索引”并获得类似于以下内容的输出:

                email                 Computers & Laptops        Consumer Electronics
0      +coicon7879@gmail.com                   2                             0  
1      +haiphong82lk@yahoo.com                 0                             2 
2      +nguyentrungchanhbd@gmai.com            0                             0   
3      -abc@gmail.com                          0                             4

【问题讨论】:

    标签: python pandas indexing group-by dataframe


    【解决方案1】:

    只需使用reset_index 方法:

    class_price_df.reset_index(inplace=True)
    

    【讨论】:

    • 谢谢,但是当我在做 class_price_df.columns 时,我有 MultiIndex(levels=[[u'class', u'email'], [u'Automotive & Gadgets', u'Cameras' , u'Computers & Laptops'.......) 我怎样才能得到 Index([u'email', u'Automotive & Gadgets', u'Cameras', u'Computers & Laptops'..... ....) ?
    • @user1754181 您可以在调用 reset_index 时使用 int 或字符串名称指定级别:pandas.pydata.org/pandas-docs/stable/generated/… 例如 class_price_df.reset_index(inplace=True, level='class')
    • 感谢@EdChum,但我仍然有 MultiIndex(levels=[[u'class', u'email'], [u'Automotive & Gadgets', u'Cameras', u'Computers & Laptops '
    猜你喜欢
    • 2015-09-29
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 2019-04-22
    • 2022-01-09
    • 2019-04-13
    • 2020-03-10
    相关资源
    最近更新 更多