pandas pivot table - changing order of non-index columns

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.


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.

Tags:

Python

Pandas