2015-05-29 9 views
3

,我有以下數據:如何行索引不區分大小寫的方式大熊貓數據幀排序

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 

用下面的代碼:

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) 

我得到如下:

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 

我想要做的是以不區分大小寫的方式排列行 產生此:

  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

大廈在@Marius case_insensitive_order,單內襯使用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 
+0

感謝您的回答,Zero。我已經將它擴展到多列工作https://stackoverflow.com/a/46358081/1072869 – Aralox

2

您可以通過使用新的CategoricalIndex(新在0.16.1,我覺得)這個力量,但我不知道這是否是一個好主意,因爲它可能有難以預料的影響:

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 
1

我認爲這是一個有效的答案太:

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 

我與熊貓0.20.3和python2這裏測試上有500行和50列的表。