python - 如何对分类列进行分组,然后是数值列,并基于该组对数值进行分箱
问题描述
我有一个数据集,其中“类型”列基本上是形状,与此相对应,“体积”列由该形状的体积组成
现在我需要执行以下任务:
- 按形状分组
- 对于每个形状,按体积分组
- 对于每个形状和体积,定义一个范围并形成箱
输入:
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)
解决方案
我想你可以试试下面的代码。
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
推荐阅读
- c# - 将自定义 x 轴类别添加到 c# 以编程方式创建的 excel 折线图
- sql - 如何最有效地过滤基于另一个表的 SQL 查询?
- ssis - 执行 SSIS 包时检索 COM 类工厂错误
- mongodb - 从另一个集合中获取不同的 id 列表,其中数组字段包含来自 MongoDB 中当前集合中的项目的 id
- snowflake-cloud-data-platform - 雪花:有没有不使用创建仓库的方法?
- reactive-programming - 如何使用 Rx.Net 根据观察者的执行时间来节流
- jquery - 使用动态验证模式验证“必填”字段
- css - 使用溢出时图像从黑暗中淡出:隐藏?
- architecture - 如何设计算法交易平台的系统架构?
- android - 不要在 ImageView 中显示 ClipDrawable