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

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

相关推荐
啦啦啦_99992 天前
Pandas之Series对象
pandas
xiaotao1313 天前
01-编程基础与数学基石:概率与统计
人工智能·python·numpy·pandas
人工干智能6 天前
科普:python的pandas包中的DataFrame就是二维表
开发语言·python·pandas
橙露6 天前
Polars 极速数据框架:比 Pandas 更快的大数据处理
pandas
Yu_Lijing7 天前
Python数据分析和数据处理库Pandas(Series篇)
人工智能·python·数据分析·pandas
AI效率工坊7 天前
【Python实战】10万行数据自动清洗:pandas+AI智能识别+异常检测完整方案
人工智能·python·pandas
人工干智能7 天前
科普:pandas 中的类 SQL语句:transaction.groupby(“card_id“)[‘purchase_day‘].diff()
数据库·sql·pandas
神秘剑客_CN7 天前
python安装requests及pandas
开发语言·python·pandas
zzwq.8 天前
Pandas读取数据:csv、excel、sql全攻略
python·pandas
zfan5208 天前
python对Excel数据处理(1)
python·excel·pandas