我在 python3
的 pandas
中有以下数据框:
+------------------------------+
| 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/