Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a Pandas DataFrame by index?

Tags:

python

pandas

When there is an DataFrame like the following:

import pandas as pd df = pd.DataFrame([1, 1, 1, 1, 1], index=[100, 29, 234, 1, 150], columns=['A']) 

How can I sort this dataframe by index with each combination of index and column value intact?

like image 897
midtownguru Avatar asked Mar 05 '14 23:03

midtownguru


People also ask

How do I sort pandas by index?

Pandas Series: sort_index() functionThe sort_index() function is used to sort Series by index labels. Returns a new Series sorted by label if inplace argument is False, otherwise updates the original series and returns None. Axis to direct sorting. This can only be 0 for Series.

How do I sort pandas DataFrame?

In order to sort the data frame in pandas, function sort_values() is used. Pandas sort_values() can sort the data frame in Ascending or Descending order.

Which method should I apply to a series or DataFrame to sort the entries by index?

To sort by index / columns (row/column names), use the sort_index() method.

How do I sort a pandas DataFrame by a specific column?

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.


2 Answers

Dataframes have a sort_index method which returns a copy by default. Pass inplace=True to operate in place.

import pandas as pd df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A']) df.sort_index(inplace=True) print(df.to_string()) 

Gives me:

     A 1    4 29   2 100  1 150  5 234  3 
like image 178
Paul H Avatar answered Oct 19 '22 07:10

Paul H


Slightly more compact:

df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A']) df = df.sort_index() print(df) 

Note:

  • sort has been deprecated, replaced by sort_index for this scenario
  • preferable not to use inplace as it is usually harder to read and prevents chaining. See explanation in answer here: Pandas: peculiar performance drop for inplace rename after dropna
like image 26
fantabolous Avatar answered Oct 19 '22 06:10

fantabolous