Python,重新组织Pandas数据帧中的列

2024-09-19 23:27:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为“class_price_df”的熊猫数据帧:

                            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

我按“email”和“cat”分组,以获得“class”的最大值:

^{pr2}$

输出为:

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  

如何获得类似以下内容的输出:

                 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

我试过了

class_price_df.reset_index(inplace=True, level='class')

但结果是:

                            email                 class           \
cat                                       Automotive & Gadgets  Cameras   
0                +841869087649@gmail.com                     0        0   
1                  +coicon7879@gmail.com                     0        0   
2                +haiphong82lk@yahoo.com                     0        0   
3           +nguyentrungchanhbd@gmai.com                     0        0 

Tags: comdfemailpriceyahoogmailclasscat