恕我直言,您可以使用qcut、KBinsDiscretizer 或cut。
一些例子,
>>> df = pd.DataFrame(np.random.randn(10), columns=['a'])
>>> df
a
0 0.060278
1 -0.618677
2 -0.472467
3 1.539958
4 -0.181974
5 1.563588
6 -1.693140
7 1.868881
8 1.072179
9 0.575978
对于qcut,
>>> df['cluster'] = pd.qcut(df.a, 5, labels=range(1, 6))
>>> df
a cluster
0 0.060278 3
1 -0.618677 1
2 -0.472467 2
3 1.539958 4
4 -0.181974 2
5 1.563588 5
6 -1.693140 1
7 1.868881 5
8 1.072179 4
9 0.575978 3
对于KBinsDiscretizer,
>>> (df['cluster'] =
KBinsDiscretizer(n_bins=3, encode='ordinal', strategy='quantile')
.fit_transform(df.a.values.reshape(-1, 1)))
>>> df
a cluster
0 0.060278 1.0
1 -0.618677 0.0
2 -0.472467 0.0
3 1.539958 2.0
4 -0.181974 1.0
5 1.563588 2.0
6 -1.693140 0.0
7 1.868881 2.0
8 1.072179 2.0
9 0.575978 1.0
对于cut,
>>> df['cluster'] = pd.cut(df.a, 5, labels=range(1, 6))
>>> df
a cluster
0 0.060278 3
1 -0.618677 2
2 -0.472467 2
3 1.539958 5
4 -0.181974 3
5 1.563588 5
6 -1.693140 1
7 1.868881 5
8 1.072179 4
9 0.575978 4
最后,看看可能有用:What is the difference between pandas.qcut and pandas.cut?