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...)
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.
Order will always be preserved. When you use the list function, you provide it an iterator, and construct a list by iterating over it.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With