根据python中的cut来排序pandas数据帧?

时间:2013-10-08 12:51:27

标签: python sorting pandas

如果我使用pandas.cut生成像[0.3, 0.5), ...这样的二进制文件标签,我如何按升序对这些二进制数据框进行排序?例如。 [-0.4, -0.2)应该在[-0.2, 0.0)等之前出现。例如:

df = pandas.DataFrame({"a": np.random.randn(10)})
# bin according to cut
df["bins"] = pandas.cut(df.a, np.linspace(-2,2,6))

现在,您如何根据cutdf["bins"]列)生成的标签对df进行排序?

2 个答案:

答案 0 :(得分:7)

如果您先按“a”列排序df,那么您无需对“bins”列进行排序

import pandas as pd
import numpy as np
df = pd.DataFrame({"a": np.random.randn(10)})
# for versions older than 0.17.0
df.sort(by=['a'],inplace=True)
# if running a newer version 0.17.0 or newer then you need
df.sort_values(by=['a'],inplace=True)
# bin according to cut
df["bins"] = pd.cut(df.a, np.linspace(-2,2,6))
df

Out[37]:
          a          bins
6 -1.273335    (-2, -1.2]
7 -0.604780  (-1.2, -0.4]
1 -0.467994  (-1.2, -0.4]
8  0.028114   (-0.4, 0.4]
9  0.032250   (-0.4, 0.4]
3  0.138368   (-0.4, 0.4]
0  0.541577    (0.4, 1.2]
5  0.838290    (0.4, 1.2]
2  1.171387    (0.4, 1.2]
4  1.770752      (1.2, 2]

答案 1 :(得分:1)

自pandas .17以来,排序的新方法是使用sort_values。优选的解决方案变为:

javascript