Pandas实战100例 | 案例 13: 数据分类 - 使用 `cut` 对数值进行分箱

案例 13: 数据分类 - 使用 cut 对数值进行分箱

知识点讲解

在数据分析中,将连续的数值数据分类成不同的区间(或"分箱")是一种常见的做法。Pandas 提供了 cut 函数,它可以根据你指定的分箱边界将数值数据分配到不同的类别中。

  • 使用 cut 进行分箱 : 你可以指定一系列的边界来定义分箱,然后将这些边界应用于数据列。cut 还允许你为每个箱指定标签。
示例代码
python 复制代码
# 准备数据和示例代码的运行结果,用于案例 13

# 示例数据
data_categorization = {
    'Product': ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'],
    'Price': [5, 3, 9, 7, 1]
}
df_categorization = pd.DataFrame(data_categorization)

# 使用 cut 进行分箱
df_categorization['PriceRange'] = pd.cut(df_categorization['Price'], bins=[0, 2, 5, 10], labels=['Low', 'Medium', 'High'])

df_categorization

在这个示例中,我们对产品价格进行了分类。我们定义了三个价格区间:低(0-2)、中等(2-5)、高(5-10),并使用 cut 函数将每个产品的价格分配到这些区间中。

示例代码运行结果
复制代码
      Product  Price PriceRange
0       Apple      5     Medium
1      Banana      3     Medium
2      Cherry      9       High
3        Date      7       High
4  Elderberry      1        Low

这个结果展示了每个产品根据其价格被分配到的相应区间。这种方法对于分类分析和制作分组统计非常有用。

相关推荐
沉下去,苦磨练!5 小时前
python的数据分析Pandas
python·数据分析·pandas
毋语天1 天前
Pandas 数据处理进阶:缺失值、合并、分组聚合与透视表
python·数据分析·pandas·数据清洗·透视表
hef2881 天前
探索Pandas groupby的各种技巧和应用实例
pandas
Cloud_Shy6182 天前
Python 数据分析基础入门:《Excel Python:飞速搞定数据分析与处理》学习笔记系列(第十二章 用户定义函数 上篇)
python·数据分析·excel·pandas
星越华夏2 天前
pandas日期类型差值timedelta大于等于7天
pandas
Omics Pro4 天前
填补蛋白质组深度学习预处理教学空白
人工智能·python·深度学习·plotly·numpy·pandas·scikit-learn
星越华夏4 天前
Pandas获取excel表sheet名称
excel·pandas
星越华夏5 天前
PPTX判断包含图表id
python·pandas
Cloud_Shy6185 天前
Python 数据分析基础入门:《Excel Python:飞速搞定数据分析与处理》学习笔记系列(第十一章 Python 包跟踪器 上篇)
python·数据分析·excel·pandas·matplotlib
小郑加油6 天前
python学习Day14:实际应用——pandas的筛选与保存
python·学习·pandas