首页 > 解决方案 > pd.series 会对字典键进行排序吗?

问题描述

我正在使用 Jake Vaderplas 提供的 Jupyter notebook,“Python 数据科学手册”,它说:数据可以是一个字典,其中索引默认为排序的字典键

但是当我运行代码时,输​​出没有按字典键排序。我在这里想念什么?

在 :

pd.Series({2:'a', 1:'b', 3:'c'})

出去 :

2    a
1    b
3    c
dtype :object

虽然预期的输出应该是

在 :

pd.Series({2:'a', 1:'b', 3:'c'})

出去 :

1    b
2    a
3    c
dtype :object

标签: pandasseries

解决方案


首先要说明一下,pandas 系列sorted默认是没有的。但是如果你想制作一个应该sorted按索引的系列,

sr = pd.Series({2:'a', 1:'b', 3:'c'}).sort_index()
sr

输出:

1    b
2    a
3    c

这将为您提供所需的结果。


推荐阅读