如何在Pandas DataFrame中按不区分大小写的方式对行索引进行排序

5
我有以下数据:
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

我应该如何达成这个目标?
3个回答

7

在 @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

谢谢你的回答,Zero。我已经扩展了它以适用于多列 https://dev59.com/bF0a5IYBdhLWcg3w07ot#46358081 - Aralox

3

您可以通过使用新的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

2

我认为这也是一个有效的答案:

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

我在一个有500行和大约50列的表格上,使用pandas 0.20.3和python2进行了测试。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接