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

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

相关推荐
卜及中11 天前
【Python】数据处理工具:Pandas详细指南
开发语言·python·学习·pandas
NLxxxxX11 天前
爬虫获取数据:selenium的应用
开发语言·爬虫·python·selenium·测试工具·numpy·pandas
猫头虎12 天前
2025最新Python 100个常用函数在线体验项目
android·java·python·pycharm·django·pandas·pip
闯闯桑12 天前
Pyspark中的int
大数据·python·spark·pandas
蓝婷儿12 天前
Python 数据分析与可视化 Day 3 - Pandas 数据筛选与排序操作
python·数据分析·pandas
蓝婷儿14 天前
Python 数据分析与可视化 Day 1 - Pandas 数据分析基础入门
python·数据分析·pandas
慕婉030715 天前
Pandas 核心数据结构详解:Series 和 DataFrame 完全指南
数据结构·pandas