python - 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 列)根据某些帖子按字母顺序排序。谁能告诉我如何实现它?我们来自数据库的基础数据是按特定顺序排列的,用户希望以旋转的形式查看类似的顺序。
谢谢你。
解决方案
DataFrame.sort_index
与axis=1
和一起使用ascending=False
:
table = table.sort_index(axis=1, ascending=False)
或者
table = table.loc[:, ['small', 'large']]
或者
table = table.reindex(columns = ['small', 'large'])
但我认为使用 sort_index 你不需要写轴的名称
推荐阅读
- html - 如何使用 Django 作为后端的选择选项标签作为 html 中的输入
- c# - 启动 Windows 服务后出现错误 1053
- python-3.x - 如何使用 Python 拆分大文档?
- c# - 获取设备友好名称 - 结果不正确
- model-view-controller - 从 MVC 中的不同控制器调用 Post Action
- events - Service Worker 在发送 controllerchange 事件之前延迟了几分钟
- r - 如何将 quasiquation 与 pmap 一起使用?
- java - Java 泛型:关于具有泛型返回类型(但没有泛型参数)的方法的问题
- java - 添加 Hook 来操作 JUnit 输出
- android - Android - 带有 LiveData 组件和 Repository 中的 Retrofit 调用的 MVVM