pandas 更改行顺序熊猫数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42776511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:11:02  来源:igfitidea点击:

Change rows order pandas data frame

pythonpandassortingjupyter-notebook

提问by Gilbert

I have the following data frame in pandasin python3:

我在pandasin 中有以下数据框python3

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

And I want to change the order of the rows including the indexes like so...

我想改变行的顺序,包括像这样的索引......

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

I have tried to use .sort_index(['11-', 'Just 12', 'Some College', 'Bachelor+'])and I get the following error... TypeError: unhashable type: 'list'. So looks like pandas sort these indexes by alphabetic order. How can I re-order the rows?

我试图用.sort_index(['11-', 'Just 12', 'Some College', 'Bachelor+'])我碰到下面的错误...... TypeError: unhashable type: 'list'。所以看起来Pandas按字母顺序对这些索引进行排序。如何重新排序行?

回答by divibisan

Per SSCin the comments:

根据评论中的SSC



Try using .reindex:

尝试使用.reindex

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

The reindexdoc has more detail.

reindex文档有更多详细信息。