Python pandas dataframe sort_值不

2024-05-14 19:42:18 发布

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

我有下面的pandas数据框,我想按“test_type”排序

  test_type         tps          mtt        mem        cpu       90th
0  sso_1000  205.263559  4139.031090  24.175933  34.817701  4897.4766
1  sso_1500  201.127133  5740.741266  24.599400  34.634209  6864.9820
2  sso_2000  203.204082  6610.437558  24.466267  34.831947  8005.9054
3   sso_500  189.566836  2431.867002  23.559557  35.787484  2869.7670

我的代码加载数据帧并对其进行排序,第一行打印上面的数据帧。

        df = pd.read_csv(file) #reads from a csv file
        print df
        df = df.sort_values(by=['test_type'], ascending=True)
        print '\nAfter sort...'
        print df

在进行排序并打印数据帧内容之后,数据帧仍然如下所示。

程序输出:

After sort...
  test_type         tps          mtt        mem        cpu       90th
0  sso_1000  205.263559  4139.031090  24.175933  34.817701  4897.4766
1  sso_1500  201.127133  5740.741266  24.599400  34.634209  6864.9820
2  sso_2000  203.204082  6610.437558  24.466267  34.831947  8005.9054
3   sso_500  189.566836  2431.867002  23.559557  35.787484  2869.7670

我希望第3行(测试类型:sso_500row)在排序后位于顶部。有人能帮我弄清楚为什么它不能正常工作吗?


Tags: csv数据testpandasdf排序typecpu
2条回答

假设,您要做的是按sso_之后的数值排序。您可以执行以下操作:

import numpy as np

df.ix[np.argsort(df.test_type.str.split('_').str[-1].astype(int).values)

这个

  1. _处拆分字符串

  2. 将此字符后面的内容转换为数值

  3. 查找根据数值排序的索引

  4. 根据这些索引重新排序数据帧

示例

In [15]: df = pd.DataFrame({'test_type': ['sso_1000', 'sso_500']})

In [16]: df.sort_values(by=['test_type'], ascending=True)
Out[16]: 
  test_type
0  sso_1000
1   sso_500

In [17]: df.ix[np.argsort(df.test_type.str.split('_').str[-1].astype(int).values)]
Out[17]: 
  test_type
1   sso_500
0  sso_1000

或者,也可以从test_type中提取数字并对其进行排序。然后根据这些指标重新编制DF索引。

df.reindex(df['test_type'].str.extract('(\d+)', expand=False)    \
                          .astype(int).sort_values().index).reset_index(drop=True)

Image

相关问题 更多 >

    热门问题