首页 > 解决方案 > Python pandas pivot_table 类别列位置

问题描述

我正在尝试旋转一个 Python pandas 数据框,它可以工作,但问题是列的顺序被扭曲了。假设我的数据框如下

 --------
>>> df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
...                          "bar", "bar", "bar", "bar"],
...                    "B": ["one", "one", "one", "two", "two",
...                          "one", "one", "two", "two"],
...                    "C": ["small", "large", "large", "small",
...                          "small", "large", "small", "small",
...                          "large"],
...                    "D": [1, 2, 2, 3, 3, 4, 5, 6, 7],
...                    "E": [2, 4, 5, 5, 6, 6, 8, 9, 9]})
>>> df
     A    B      C  D  E
0  foo  one  small  1  2
1  foo  one  large  2  4
2  foo  one  large  2  5
3  foo  two  small  3  5
4  foo  two  small  3  6
5  bar  one  large  4  6
6  bar  one  small  5  8
7  bar  two  small  6  9
8  bar  two  large  7  9

在旋转它之后

 >>> table = pd.pivot_table(df, values='D', index=['A', 'B'],
...                     columns=['C'], aggfunc=np.sum)
>>> table
C        large  small
A   B
bar one    4.0    5.0
    two    7.0    6.0
foo one    4.0    1.0
    two    NaN    6.0

在上面的旋转输出中,我希望先看到“小”,然后再看到“大”

C        small  large
A   B
bar one    5.0    5.0
    two    6.0    7.0
foo one    1.0    4.0
    two    6.0    NaN

到目前为止,我无法在网上找到任何选项。类别列值(上面示例 df 中的 C 列)根据某些帖子按字母顺序排序。谁能告诉我如何实现它?我们来自数据库的基础数据是按特定顺序排列的,用户希望以旋转的形式查看类似的顺序。

谢谢你。

标签: pythonpandas

解决方案


DataFrame.sort_indexaxis=1和一起使用ascending=False

 table = table.sort_index(axis=1, ascending=False)

或者

table = table.loc[:, ['small', 'large']]

或者

table = table.reindex(columns = ['small', 'large'])

但我认为使用 sort_index 你不需要写轴的名称


推荐阅读