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

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

相关推荐
qq_381454994 天前
Python Pandas完全指南:从核心数据结构到实战操作
pandas
TUTO_TUTO5 天前
【python-词汇指标提取工具开发】自学笔记(1)-后端程序
人工智能·python·pandas·visual studio code
葱明撅腚5 天前
shapely空间数据分析
python·pandas·gis·shapely
忘忧记6 天前
pandas基础三
pandas
叫我:松哥8 天前
基于scrapy的网易云音乐数据采集与分析设计实现
python·信息可视化·数据分析·beautifulsoup·numpy·pandas
测试摆渡媛8 天前
Excel模板填充工具(工具&脚本分享)
python·数据挖掘·pandas
_Soy_Milk8 天前
【算法工程师】—— Python 数据分析
python·数据分析·numpy·pandas·matplotlib
Data-Miner9 天前
类似Pandas AI的几个数据分析处理智能体介绍
人工智能·数据分析·pandas
智航GIS11 天前
11.18 自定义Pandas扩展开发指南:打造你的专属数据分析武器库
python·数据分析·pandas
人工干智能12 天前
你知道 Pandas 中 `pd.get_dummies()` 会生成哪些独热的新列么?
大数据·pandas