gpt4 book ai didi

python - 如何对分类列和数值列进行分组,并基于该组对数值进行分箱

转载 作者:行者123 更新时间:2023-12-01 07:49:52 26 4
gpt4 key购买 nike

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

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

  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.气缸 -> 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)

最佳答案

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

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 重置此处的索引,以便根据新索引重新排列数据帧。

希望这有帮助。

编辑:-对于 bin,您不必担心,因为每个 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

关于python - 如何对分类列和数值列进行分组,并基于该组对数值进行分箱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56292807/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com