Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas pivot table - changing order of non-index columns

Tags:

python

pandas

I created a pivot table using:

table2 = pandas.pivot_table(df, index=['Salesperson'], values=['Gross Sales', 'Gross Profit'], aggfunc=numpy.sum)
table2['Profit Margin'] = table2['Gross Profit'] / table2['Gross Sales']
table2_rounded = table2.round({'Gross Profit': 2, 'Gross Sales': 2, 'Profit Margin': 2})

which gives me:

in: table2.info
out: Salesperson Gross Profit Gross Sales Profit Margin
  ((((values as row data))))

as columns. HOWEVER - Gross Sales should display before Gross Profit. How do I change the order of the non-index columns? The dataframe was 1000 rows long before I pivoted. I searched high and low for a solution. This seems rather basic (or should be...)

like image 804
Arbitrage84 Avatar asked Apr 01 '16 00:04

Arbitrage84


People also ask

Can we change the order in columns of pivot table?

Change the order of row or column items In the PivotTable, right-click the row or column label or the item in a label, point to Move, and then use one of the commands on the Move menu to move the item to another location.

Does Pandas Tolist preserve order?

Order will always be preserved. When you use the list function, you provide it an iterator, and construct a list by iterating over it.


2 Answers

You can reindex the axis in the order you want. The appropriate method is called reindex_axis.

_note: reindex_axis is deprecated since version 0.21.0: Use reindex instead._

column_order = ['Gross Sales', 'Gross Profit', 'Profit Margin']
# before pandas 0.21.0
table3 = table2.reindex_axis(column_order, axis=1)
# after pandas 0.21.0
table3 = table2.reindex(column_order, axis=1)

The method info is not meant to display the DataFrame, and it is not being called correctly. To call info, try typing in table2.info() instead. It is possible to examine the DataFrame by just typing the variable name, calling the print function [or statement], using the head and tail methods, or slicing a row / column range.

like image 139
Haleemur Ali Avatar answered Sep 20 '22 06:09

Haleemur Ali


You can re-order columns by taking a slice of the data frame:

table3 = table2[['Gross Sales', 'Gross Profit', 'Profit Margin']].copy()

Note that I have a set of brackets for the slice, and another set of brackets to enclose the list of column names. If you do table2['Gross Sales', 'Gross Profit', 'Profit Margin'], it will throw an error. Also, since this is taking a slice, omitting .copy() will result in a shallow copy.

I don't know of any benefits of using reindex_axis if you aren't using the optional parameters, so anyone who knows of such, feel free to mention in the comments.

And if you're using Spyder, you can view the dataframe by going to the variable explorer and clicking on its name.

like image 40
Acccumulation Avatar answered Sep 19 '22 06:09

Acccumulation