简体   繁体   中英

Dropping the sum column in pandas pivot table, but keeping the row

So I have a pandas pivot table and I want to keep the sum of the columns at the bottom (so the sum row). However, there is also a column that is added when I say margins=True and I don't want that.

I have tried dropping the column, but dropping a column from a multiindex table just resulted in errors. If I do drop('All', axis=1), it says KeyError: 'All', and if I do axis=0 it gets rid of the total on the bottom (which I want).

artist_table = pd.pivot_table(total_df,
                              values=['Records Created', 
                                      'Tickets Sold'],
                              index=['artist name',
                                     'artist id'],
                              columns=['date'],
                              aggfunc=np.sum,
                              fill_value=0,
                              margins=True)

What I want is:

                                 Leads Created       Revenue     
 date                             6/1                 6/2                                        
    artist_id    artist_name      
    XXX           YYY            x                   y            
    AAA           BBB            a                   b            
    All                         (x+a)             (y+b)    

What I have now is:

                                Leads Created       Revenue     
date                              6/1                 6/2           All                                
artist_id    artist_name      
    XXX           YYY              x                   y          (x+y)
    AAA           BBB              a                   b          (a+b)
    All                           (x+a)             (y+b)                    

I would like that All on the right (the sums of the rows) to be gone. Can anyone please help? Thank you in advance!

I ended up converting Pivot Table to Dataframe using the alternative option suggested here:

transform pandas pivot table to regular dataframe

...and then dropped the 'All' column from that new dataframe.

You can swap the headers level by

artist_table=artist_table.swaplevel(0,1,axis=1).sort_index(axis=1)

and then drop the "All" column

artist_table.drop("All", axis=1)

then you can swap the levels back

artist_table=artist_table.swaplevel(0,1,axis=1).sort_index(axis=1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM