gpt4 book ai didi

python - Pandas pivot_table 保留顺序

转载 作者:行者123 更新时间:2023-12-03 12:13:10 24 4
gpt4 key购买 nike

>>> df
A B C D
0 foo one small 1
1 foo one large 2
2 foo one large 2
3 foo two small 3
4 foo two small 3
5 bar one large 4
6 bar one small 5
7 bar two small 6
8 bar two large 7
>>> table = pivot_table(df, values='D', index=['A', 'B'],
... columns=['C'], aggfunc=np.sum)
>>> table
small large
foo one 1 4
two 6 NaN
bar one 5 4
two 6 7

我希望输出如上所示,但我得到一个排序的输出。
bar 高于 foo 等等。

最佳答案

在创建时 pivot_table ,索引自动按字母顺序排序。不仅foobar ,您可能还会注意到 smalllarge排序。如果你想要 foo最重要的是,您可能需要sort他们再次使用 sortlevel .如果您期望输出如 example here ,然后按 A 排序和 C两者都可能需要。

table.sortlevel(["A","B"], ascending= [False,True], sort_remaining=False, inplace=True)
table.sortlevel(["C"], axis=1, ascending=False, sort_remaining=False, inplace=True)
print(table)

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

更新:

删除索引名称 A , BC :
table.columns.name = None
table.index.names = (None, None)

关于python - Pandas pivot_table 保留顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44988213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com