首页 > 解决方案 > 如何对分类列进行分组,然后是数值列,并基于该组对数值进行分箱

问题描述

我有一个数据集,其中“类型”列基本上是形状,与此相对应,“体积”列由该形状的体积组成

现在我需要执行以下任务:

  1. 按形状分组
  2. 对于每个形状,按体积分组
  3. 对于每个形状和体积,定义一个范围并形成箱

输入:

 Type             Volume

 Cylinder          100
 Square            300
 Cylinder          200
 Oval              100
 Square            320
 Cylinder          150
 Oval              600
 Round             1000
 Square            900
 Round             1500

输出:

 Type              Volume       Bin

 Cylinder          100            1
 Cylinder          150            1
 Cylinder          200            2
 Oval              100            1
 Oval              600            3
 Round             1000           1
 Round             1500           2
 Square            300            1
 Square            320            1
 Square            900            3

垃圾箱如下:

1.Cylinder -> Bin1(100-200), Bin2(201-300) ....

2.椭圆 -> Bin1(100-200), ..... Bin3(500-600).... ...

代码:

  grouped=df_dim.groupby('Type', as_index=False)
  def test(group):
     return group.reset_index()
  def group_vol(group):
     groupedVol = 
         group.groupby(pd.cut(group["Target_BrimVol"],
         np.arange(0,5000,200)),as_index=False)

     return groupedVol.apply(test)

  gr = grouped.apply(group_vol)
  print(gr)

标签: pythonpython-3.xdataframepandas-groupbysklearn-pandas

解决方案


我想你可以试试下面的代码。

testdf = df.groupby('Type',as_index=False).apply(lambda x: x.groupby(pd.cut(x["Vol"],np.arange(x["Volume"].min(),x["Volume"].max(),200)),as_index=False).apply(test))

这里发生的是,首先groupby基本上将 Dataframe 分组为“类型”类别,然后您希望根据范围对其进行分组。为此,您可以使用 lambda 函数再次对其进行分组,使用pd.cut函数根据您的范围对间隔进行小幅削减。在这种情况下,我只是取最大值和最小值并将其以 200 的间隔切割。在此之后,如果您想将输出重新合并在一起形成一个 Dataframe,请再使用一个 apply 将它们合并回来。像这样,

def test(group):
   #Write your function here. Whatever you want to perform.
   return group.merge(group)

我在as_index=False这里重置索引,以便根据新索引重新排列数据框。

希望这可以帮助。

编辑:- 对于垃圾箱,您不必担心,因为每个垃圾箱都会groupby创建一个新索引,您可以将其用于您的目的。如中,

Index1  Index2  Type  Volume
0 0 Cylinder  100
0 0 Cylinder  140
0 1 Cylinder  250
1 0 Oval  154
1 4 Oval 999
2 1 Circle  328

推荐阅读