简体   繁体   English

有条件的装箱

[英]Conditionally binning

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). 是否可以在其中“ X”的仓基于另一列的值的数据框中创建新列。 Example below. 下面的例子。

The bins for AR1, PO1 and RU1 are different from one another. AR1,PO1和RU1的容器彼此不同。

Until now I can only get bins for all values in 'X'. 到现在为止,我只能获取“ 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. 在我的真实数据上,我得到一个ValueError:边缘不是唯一的。 Can I solve this with ie rank? 我可以用等级来解决这个问题吗? How would I add this to the solution proposed? 我如何将其添加到建议的解决方案中?

Simple use pd.qcut within a groupby on S S上的groupby简单使用pd.qcut

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 如果希望它们具有自己的独特边缘,则不使用labels参数

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM