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

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

相关推荐
laocooon5238578861 天前
对传入的 x , y 两个数组做折线图, x 对应 x 轴, y 对应 y 轴。并保存到 Task1/image1/T2.png
python·numpy·pandas·matplotlib
Maxwell_li12 天前
新冠检测例子学习查准率和召回率
学习·机器学习·数据分析·回归·numpy·pandas
渡我白衣2 天前
Python 与数据科学工具链入门:NumPy、Pandas、Matplotlib 快速上手
人工智能·python·机器学习·自然语言处理·numpy·pandas·matplotlib
IT北辰3 天前
用 Python 自动解析药品规格并计算包装总容量 —— pandas + 正则实战
开发语言·python·pandas
lbb 小魔仙3 天前
Python 读取 Excel 文件:openpyxl 与 pandas 实战对比
python·excel·pandas
Amber_373 天前
数据分析之(MySQL+普通程序) VS (Python的NumPy/Pandas)
python·mysql·数据分析·numpy·pandas
Lucky高4 天前
Pandas库实践3_索引
开发语言·python·pandas
墨上烟雨4 天前
Pandas读写CSV、Excel、JSON文件
pandas
Serendipity_Carl5 天前
京东手机销售数据分析: 从数据清洗到可视化仪表盘
python·数据分析·pandas·pyecharts
一位代码6 天前
pandas | 查看数据特征的常见属性及方法
pandas