python - Pandas 数据透视表 - 改变非索引列的顺序

标签 python pandas

我使用以下方法创建了一个数据透视表:

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()。只需键入变量名、调用打印函数 [或语句]、使用 headtail 方法,或对行/列进行切片,就可以检查 DataFrame范围。

关于python - Pandas 数据透视表 - 改变非索引列的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36346071/

相关文章:

python - 根据同一行中的值填充 NaN 单元格

python - Pandas groupby 函数中的 secondary_y 范围

python - 使用 Pandas 计算特定列中具有相同值的行

python - 如何在 PyQt/PySide 中将 QComboBox 设置为项目文本中的项目

python - 使用 Scapy 构建 Probe Request 请求

python - 关于python3.4.1客户端连接redis中的char b前缀

python - 错误 : list indices must be integers not float

python - Pandas 类别 : keep only most common ones and replace rest with NaN

python - 在多索引数据帧上突出显示最大/最小值 - Pandas

python - Pandas :创建新的数据框,平均来自另一个数据框的重复项