Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change rows order pandas data frame

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?

like image 895
redeemefy Avatar asked Mar 14 '17 01:03

redeemefy


People also ask

How do I change the order of rows in pandas?

We use DataFrame. reindex() function to reorder the rows using the index list.

How do I move rows in pandas DataFrame?

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.

How do I change the order of index in pandas DataFrame?

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.


1 Answers

Per SSC in the comments:


Try using .reindex:

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

The reindex doc has more detail.

like image 157
divibisan Avatar answered Oct 08 '22 12:10

divibisan