4

如果我pandas.cut用来生成 bin 标签[0.3, 0.5), ...,如何根据这些 bin 升序对数据帧进行排序?例如[-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 进行排序?

4

2 回答 2

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]
于 2013-10-08T13:09:03.207 回答
1

从 pandas .17 开始,新的排序方式是使用 sort_values。首选解决方案变为:

import pandas as pd
import numpy as np
df = pd.DataFrame({"a": np.random.randn(10)})
df.sort_values('a',inplace=True)
# bin according to cut
df["bins"] = pd.cut(df.a, np.linspace(-2,2,6))
df
于 2016-03-30T20:42:59.340 回答