Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reorder indexed rows based on a list in Pandas data frame

Tags:

python

pandas

I have a data frame that looks like this:

company  Amazon  Apple  Yahoo name A             0    130      0 C           173      0      0 Z             0      0    150 

It was created using this code:

import pandas as pd df = pd.DataFrame({'name' : ['A', 'Z','C'],                    'company' : ['Apple', 'Yahoo','Amazon'],                    'height' : [130, 150,173]})  df = df.pivot(index="name", columns="company", values="height").fillna(0) 

What I want to do is to sort the row (with index name) according to a predefined list ["Z", "C", "A"]. Resulting in this :

company  Amazon  Apple  Yahoo name Z             0      0    150 C           173      0      0 A             0    130      0 

How can I achieve that?

like image 912
neversaint Avatar asked May 03 '15 03:05

neversaint


People also ask

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.

How do I order rows in pandas?

You can sort by column values in pandas DataFrame using sort_values() method. To specify the order, you have to use ascending boolean property; False for descending and True for ascending. By default, it is set to True.

How do you select rows based on index list?

index[]] to Select Rows From List Index. Alternatively, you can select rows from the list index by using df. loc[df. index[]] method.


1 Answers

You could set index on predefined order using reindex like

In [14]: df.reindex(["Z", "C", "A"]) Out[14]: company  Amazon  Apple  Yahoo Z             0      0    150 C           173      0      0 A             0    130      0 

However, if it's alphabetical order, you could use sort_index(ascending=False)

In [12]: df.sort_index(ascending=False) Out[12]: company  Amazon  Apple  Yahoo name Z             0      0    150 C           173      0      0 A             0    130      0 

Like pointed below, you need to assign it to some variable

In [13]: df = df.sort_index(ascending=False) 
like image 127
Zero Avatar answered Oct 20 '22 20:10

Zero