Python 在“装箱”中同时输出“箱子”和“标签”列

Python 在“装箱”中同时输出“箱子”和“标签”列,python,pandas,dataframe,binning,Python,Pandas,Dataframe,Binning,我有一个dataframe列,我想对其执行装箱,例如: df.head X 4.6 2.5 3.1 1.7 我希望一列用于bin范围,一列用于标签,如下所示: df.head X bin label 4.6 (4,5] 5 2.5 (2,3] 3 3.1 (3,4] 4 1.7 (1,2] 2 显然,如下设置label参数只会产生一列bin标签,而不再是范围 df['bin'] = df.X.apply(pd.cut, labels=np.arange(5)) 有没有更优雅的解决方案,而不

我有一个dataframe列,我想对其执行装箱,例如:

df.head
X
4.6
2.5
3.1
1.7
我希望一列用于bin范围,一列用于标签,如下所示:

df.head
X bin label
4.6 (4,5] 5
2.5 (2,3] 3
3.1 (3,4] 4
1.7 (1,2] 2
显然,如下设置
label
参数只会产生一列bin标签,而不再是范围

df['bin'] = df.X.apply(pd.cut, labels=np.arange(5))
有没有更优雅的解决方案,而不是对两列运行
pd.cut
2次


感谢如果您允许
pd.cut
动态设置垃圾箱边缘,您可以使用
retbins
标志。从:

这将返回第二个结果:

bins: numpy.ndarray or IntervalIndex.
    The computed or specified bins. Only returned when
    retbins=True. For scalar or sequence bins, this is
    an ndarray with the computed bins. If set
    duplicates=drop, bins will drop non-unique bin. For
    an IntervalIndex bins, this is equal to bins.
可以使用此选项将箱子边缘指定给框架:

assignments,edges=pd.cut(df.X,bins=5,labels=False,retbins=True)
df['label']=赋值
df['bin_floor']=边缘[作业]
df['bin_ceil']=边[assignments+1]
您的注释表明您希望在groupby操作中使用此选项。在这种情况下,您可以将上述内容包装到函数中:

def分配动态标识和标签(
df,
价值观,
恩宾斯,
label_col='label',
本楼,
bin_ceil_col='bin_ceil',
):
指定,边=pd.cut(
df[value\u col],bin=5,labels=False,retbins=True
)
df[标签列]=赋值
df[bin\u floor\u col]=边[赋值]
df[bin_ceil_col]=边[assignments+1]
返回df
df.groupby('id').apply(分配动态标识和标签'X',5)

您能否发布一组示例数据和代码,向我们展示您的工作和尝试?下面是一些关于在提问时创建一个新问题的提示。我已经编辑了这个问题。谢谢问题是在执行
pd.cut
之前,我不知道箱子边缘是什么,所以我没有
bin\u标签这样的数组。在我的实际实现中,binning是以索引为条件执行的,因此我的代码如下:
df['bin']=df.groupby('id').X.apply(pd.cut,bins=5)
。由于有大量的
id
,我不可能事先知道每个
id
的箱子。我明白了。这是你问题中非常重要的一部分。感谢您对问题的修改!你甚至不能打电话给警察局。把你的问题写下来。你能修改这个问题以反映你的实际用例吗?@c我已经修改了我的答案以反映你的评论。
bins: numpy.ndarray or IntervalIndex.
    The computed or specified bins. Only returned when
    retbins=True. For scalar or sequence bins, this is
    an ndarray with the computed bins. If set
    duplicates=drop, bins will drop non-unique bin. For
    an IntervalIndex bins, this is equal to bins.