Conditionally binning

瘦欲@ 提交于 2019-12-12 21:08:50

问题


Is it possible to create a new column in a dataframe where the bins for 'X' are based on a value of another column(s). Example below.

The bins for AR1, PO1 and RU1 are different from one another.

Until now I can only get bins for all values in '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())

The output I would like to have:

EDIT;

On my real data I get a ValueError: edges being not unique. Can I solve this with i.e. rank? How would I add this to the solution proposed?


回答1:


Simple use pd.qcut within a groupby on 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

Leave of the labels parameter if you want them to have their own unique edges

df['bins_X'] = df.groupby('S').X.apply(pd.qcut, q=10)


来源:https://stackoverflow.com/questions/41303633/conditionally-binning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!