在为 DataFrame 系列创建类别时如何从 QCUT 中获取整数

alp*_*ric 6 python dataframe pandas

有两个 ndarray:

import pandas as pd
import numpy as np

a = np.arange(0,100, 10)
b = np.random.random_integers(low=9000, high=10000, size=(1000,)) 
Run Code Online (Sandbox Code Playgroud)

我继续创建 DataFrame:

numbers =  np.concatenate((a, b), axis=0)
df = pd.DataFrame({'a':numbers})
Run Code Online (Sandbox Code Playgroud)

由于大多数数字值(1000 个数字)都在 9,000 到 10,000 之间,只有 10 个数字在 1 到 100 之间,所以我使用方法来qcut()获取按数字百分比逻辑间隔的类别每个范围:

df['cats'] = pd.qcut(df.a, 10)
print pd.value_counts(df['cats'])
Run Code Online (Sandbox Code Playgroud)

打印出:

[0, 9103]           102
(9630.4, 9717]      102
(9407, 9519]        102
(9307.4, 9407]      102
(9895.3, 10000]     101
(9717, 9810]        101
(9203.6, 9307.4]    101
(9810, 9895.3]      100
(9103, 9203.6]      100
(9519, 9630.4]       99
Name: cats, dtype: int64
Run Code Online (Sandbox Code Playgroud)

而不是生成“(9103, 9203.6]”、“(9519, 9630.4]”标签,qcut我希望我能得到整数,如 1、2、3、4、5 、6 、7 、8 、9 等?

piR*_*red 1

使用labels=np.arange(10) + 1

df['cats'] = pd.qcut(df.a, 10, labels=np.arange(10) + 1)
print pd.value_counts(df['cats'])

1     103
3     102
10    101
9     101
8     101
7     101
6     101
4     101
5     100
2      99
Name: cats, dtype: int64
Run Code Online (Sandbox Code Playgroud)