我使用以下方法创建了一个数据透视表:
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})
这给了我:
in: table2.info
out: Salesperson Gross Profit Gross Sales Profit Margin
((((values as row data))))
作为列。但是 - 毛销售额应显示在毛利润之前。如何更改非索引列的顺序?在我旋转之前,数据框有 1000 行。我到处寻找解决方案。这看起来很基本(或者应该是...)
最佳答案
您可以按照您想要的顺序重新索引轴。适当的方法称为 reindex_axis
。
_注意:自版本 0.21.0 起不推荐使用 reindex_axis:改用 reindex。_
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)
info
方法不是用来显示 DataFrame 的,也没有被正确调用。要调用 info
,请尝试键入 table2.info()
。只需键入变量名、调用打印函数 [或语句]、使用 head
和 tail
方法,或对行/列进行切片,就可以检查 DataFrame范围。
关于python - Pandas 数据透视表 - 改变非索引列的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36346071/