如何对Pandas数据帧中的行子集进行排序

2024-06-16 17:15:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数据帧:

import pandas as pd
df = pd.DataFrame({'FavCol' : ['Fixy','Macky', 'querk', 'alber'],
                   'sample1' : [20.3, 25.3,3.1,3],
                   'sample2' : [130, 150,173,4],        
                   'sample3' : [1.0, 2.0,12.0,4],         
                   })

看起来像这样:

^{pr2}$

我要做的是基于FavCol对数据帧进行排序(不区分大小写),但保持第一行Fixy不变。结果是:

  FavCol  sample1  sample2  sample3
    Fixy     20.3      130        1
   alber      3.0        4        4
   Macky     25.3      150        2
   querk      3.1      173       12

我怎么才能做到呢?在

更新

我的复制有问题[用户:John Galt]. 有了这些数据:

Group No.   Abbr. of test substance Route   Time (hrs)  Dose (/body)    Conc.   Volume of dosage (/body)    # of mouse
1   PBS DMSO5%  i.d.    6   0 mg    0 mg/ mL    0.1 mL  3
2   MPLA    i.d.    6   0.01 mg 0.1 mg/ mL  0.1 mL  3
3   MALP2s  i.d.    6   0.01 mg 0.1 mg/ mL  0.1 mL  3
4   R848    i.d.    6   0.1 mg  1 mg/ mL    0.1 mL  3
5   DMXAA   i.d.    6   0.1 mg  1 mg/ mL    0.1 mL  3

这个代码:

import pandas as pd
df = pd.read_table("http://dpaste.com/0JPC984.txt")
colnames = df.columns.values.tolist()
print colnames
fixed_rown = colnames[1]
df['lower'] = df[fixed_rown].str.lower()
df.loc[1:] = df[1:].sort('lower')
df

它会产生这样的结果:

Out[35]:
   Group No. Abbr. of test substance Route  Time (hrs) Dose (/body)  \
0          1              PBS DMSO5%  i.d.           6         0 mg
1          2                    MPLA  i.d.           6      0.01 mg
2          3                  MALP2s  i.d.           6      0.01 mg
3          4                    R848  i.d.           6       0.1 mg
4          5                   DMXAA  i.d.           6       0.1 mg

        Conc. Volume of dosage (/body)  # of mouse       lower
0    0 mg/ mL                   0.1 mL           3  pbs dmso5%
1  0.1 mg/ mL                   0.1 mL           3        mpla
2  0.1 mg/ mL                   0.1 mL           3      malp2s
3    1 mg/ mL                   0.1 mL           3        r848
4    1 mg/ mL                   0.1 mL           3       dmxaa

In [45]: pd.__version__
Out[45]: '0.16.1'

修正后dmxaa没有出来。在


Tags: of数据importpandasdfasbodylower