I have the following data frame in pandas
in 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?
We use DataFrame. reindex() function to reorder the rows using the index list.
To move the third row to the first, you can create an index moving the target row to the first element. I use a conditional list comprehension to join by lists. Then, just use iloc to select the desired index rows. if desired, you can also reset your index.
Suppose we want to change the order of the index of series, then we have to use the Series. reindex() Method of pandas module for performing this task. Series, which is a 1-D labeled array capable of holding any data.
Per SSC in the comments:
Try using .reindex
:
.reindex(['11-', 'Just 12', 'Some College', 'Bachelor+'])
The reindex
doc has more detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With