python - 更改行顺序 Pandas 数据框

标签 python pandas sorting jupyter-notebook

我在 python3pandas 中有以下数据框:

               +------------------------------+
               | total_sum | percent_of_total |
+--------------+------------------------------+ 
| Group        |           |                  |
+--------------+------------------------------+     
| 11-          | 99435     | 0.255880         |
+--------------+-----------+------------------+
| Bachelor+    | 64900     | 0.167010         |
+--------------+-----------+------------------+
| Just 12      | 162483    | 0.418124         |
+--------------+-----------+------------------+
| Some College | 61782     | 0.158986         |
+---------------------------------------------+

我想像这样更改包括索引在内的行的顺序...

               +------------------------------+
               | total_sum | percent_of_total |
+--------------+------------------------------+ 
| Group        |           |                  |
+--------------+------------------------------+     
| 11-          | 99435     | 0.255880         |
+--------------+-----------+------------------+
| Just 12      | 162483    | 0.418124         |
+--------------+-----------+------------------+
| Some College | 61782     | 0.158986         |
+--------------+-----------+------------------+
| Bachelor+    | 64900     | 0.167010         |
+--------------+-----------+------------------+

我尝试使用 .sort_index(['11-', 'Just 12', 'Some College', 'Bachelor+']) 并收到以下错误... TypeError:无法散列的类型:'list'。所以看起来 pandas 按字母顺序对这些索引进行排序。如何重新排序行?

最佳答案

根据 SSC在评论中:


尝试使用 .reindex:

.reindex(['11-', 'Just 12', 'Some College', 'Bachelor+'])

reindex文档有更多详细信息。

关于python - 更改行顺序 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42776511/

相关文章:

sorting - 在 SAS 中,有没有办法使用除一个之外的所有变量进行排序?

c++ - 在排序的静态数组中搜索的最快方法

python - 如何找出 Pandas 中使用的编码

python - 从分层 DataFrame 中按最大值选择行

python - 使用 Panda df.to_excel(...) 后获取 excel 文件

python - 删除列表中数字的倍数 :

java:为什么带有比较器的二进制搜索不起作用?

python - Virtualenv 和 debian 中的代码位置

python - 在 Bokeh 中创建选择列表时出错

python - 如何使用 LoginRequiredMixin 在基于类的 View 中发送 Django 错误消息?