如果首先按列“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]