python - 有条件分箱

标签 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

编辑;

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

最佳答案

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

如果您希望标签拥有自己独特的边缘,请保留 labels 参数

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

关于python - 有条件分箱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41303633/

相关文章:

python - 无法更新嵌套列表中的值

python - 没有名为 flask.ext.restful 的模块

python - 追加 CSV 文件,匹配无序列

python - Pandas:将多个变量转换为一组虚拟变量

python - numpy 中的高效 bin 分配

python - 通过 DecisionTreeClassifier sklearn 合并数据?

python - 返回一行中的单词列表但忽略某些空格

python - AWS 弹性 beanstalk 上的 Django 版本

python - 使用 python pandas 或任何其他更好的库在工作表中添加一列并在整列中应用此 excel 公式

r - 将数据放入不相等的 bin 大小