Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort row index case-insensitive way in Pandas DataFrame

Tags:

python

pandas

I have the following data:

Set Coolthing Route Organ Up Down
set4 Pam3CSK4 ID LL 81 60
set4 Poly_IC ID LL 542 92
set4 Poly_IC ID MM 73 73
set4 cdiGMP ID MM 143 78
set4 Poly_IC ID BB 32 82
set4 cdiGMP ID BB 90 129

With the following code:

import pandas as pd
df = pd.io.parsers.read_table("http://dpaste.com/2PHS7R0.txt",sep=" ")
df = df.pivot(index="Coolthing",columns="Organ").fillna(0)
df.drop('Set',axis=1,inplace=True)
df.drop('Route',axis=1,inplace=True)
df.index.name = None
df.columns.names = (None,None)

I get the following:

In [75]: df
Out[75]:
          Up            Down
          BB   LL   MM    BB  LL  MM
Pam3CSK4   0   81    0     0  60   0
Poly_IC   32  542   73    82  92  73
cdiGMP    90    0  143   129   0  78

What I want to do is to sort the row with case insensitive way yielding this:

          Up            Down
          BB   LL   MM    BB  LL  MM
cdiGMP    90    0  143   129   0  78
Pam3CSK4   0   81    0     0  60   0
Poly_IC   32  542   73    82  92  73

How can I achieve that?

like image 928
pdubois Avatar asked May 29 '15 05:05

pdubois


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.

Is Pandas DataFrame case sensitive?

pandas. DataFrame. merge (similar to a SQL join) is case sensitive, as are most Python functions. Make sure you are handling your data correctly there, or just do your joins before you deduplicate.

How do you sort an index order?

The sort_index() is used to sort index in ascending and descending order. If you won't mention any parameter, then index sorts in ascending order.


1 Answers

Building on @Marius case_insensitive_order, a single liner using reindex

In [63]: df.reindex(sorted(df.index, key=lambda x: x.lower()))
Out[63]:
          Up            Down
          BB   LL   MM    BB  LL  MM
cdiGMP    90    0  143   129   0  78
Pam3CSK4   0   81    0     0  60   0
Poly_IC   32  542   73    82  92  73
like image 97
Zero Avatar answered Sep 22 '22 02:09

Zero