有条件地装箱

时间:2016-12-23 14:58:17

标签: python pandas binning

是否可以在数据框中创建新列,其中“X”的区间基于另一列的值。以下示例。

AR1,PO1和RU1的箱子彼此不同。

到目前为止,我只能获得“X”中所有值的分档。

import pandas as pd
import numpy as np
import string
import random

N = 100
J = [2012,2013,2014]
K = ['A','B','C','D','E','F','G','H']
L = ['h','d','a']
S = ['AR1','PO1','RU1']

np.random.seed(0)

df = pd.DataFrame(
    {'X': np.random.uniform(1,10,N),
     'Y': np.random.uniform(1,10,N),
     'J':np.random.choice(J, N),
     'R':np.random.choice(L, N),
     'S':np.random.choice(S,N)
    })

df['bins_X'] = pd.qcut(df['X'], 10)

print(df.head())

enter image description here

我想要的输出:

enter image description here

EDIT;

在我的真实数据上,我得到一个ValueError:边缘不是唯一的。我可以用等级来解决这个问题吗?我如何将其添加到提议的解决方案中?

1 个答案:

答案 0 :(得分:3)

pd.qcut

上的groupby内简单使用S
df['bins_X'] = df.groupby('S').X.apply(pd.qcut, q=10, labels=np.arange(10))

df.groupby(['bins_X', 'S']).size().unstack()

S       AR1  PO1  RU1
bins_X               
0         3    4    4
1         3    3    4
2         3    3    4
3         2    3    4
4         3    4    4
5         3    3    3
6         2    3    4
7         3    3    4
8         3    3    4
9         3    4    4

如果希望labels参数具有自己的唯一边

,请将其保留
df['bins_X'] = df.groupby('S').X.apply(pd.qcut, q=10)