How to sort case insensitive strings in Pandas DataFrame

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 sort the string by case insensitive giving 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 this?

+3
source share
3 answers

Based on @Marius case_insensitive_order, one liner withreindex

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
+4
source

You can force this to use a new one CategoricalIndex(new in 0.16.1, I think), but I'm not sure if this is a great idea, as this can have unpredictable effects:

case_insenstive_order = sorted(df.index, key=lambda x: x.lower())
case_insenstive_order
Out[4]: ['cdiGMP', 'Pam3CSK4', 'Poly_IC']

df.index = pd.CategoricalIndex(df.index, 
                               categories=case_insenstive_order, 
                               ordered=True)
df.sort_index()
Out[7]: 
          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
+2
source

, :

df = df.iloc[df.index.str.lower().argsort()]

reindex, , :

%timeit df.reindex(sorted(df.index, key=lambda x: x.lower()), copy=True)
1000 loops, best of 3: 794 ยตs per loop

%timeit df.iloc[df.index.str.lower().argsort()]
1000 loops, best of 3: 850 ยตs per loop

pandas 0.20.3 python2 500 50 .

+1

Source: https://habr.com/ru/post/1584915/


All Articles