如何使用Pandas对价格列表进行区间分类并统计数量
使用Pandas实现价格区间分类与统计
需求说明
给定价格列表:
list_price = [['1800','5060','6300','6800','10800','3000','7100']]
需按区间(1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000)注:原区间最后一位"000"应为输入错误,此处调整为8000以覆盖高价区间,完成以下操作:
- 将价格按区间分类,格式示例:
2000: 1800、7000:6800, 6300 - 统计每个区间的价格数量,格式示例:
2000(1),7000(2)
实现代码
import pandas as pd # 预处理数据:展开嵌套列表并转换为数值型Series list_price = [['1800','5060','6300','6800','10800','3000','7100']] prices = pd.Series([int(price) for sublist in list_price for price in sublist]) # 定义区间边界与对应标签 # bins为左开右闭区间,最后一个区间包含7000及以上所有价格 bins = [1000, 2000, 3000, 4000, 5000, 6000, 7000, float('inf')] # 用区间上限作为标签,匹配需求格式 labels = ['2000', '3000', '4000', '5000', '6000', '7000', '8000+'] # 执行区间分箱 price_bins = pd.cut(prices, bins=bins, labels=labels, include_lowest=False) # 分组并输出分类结果 print("价格区间分类:") for group_name, price_group in prices.groupby(price_bins): print(f"{group_name}: {', '.join(map(str, price_group.tolist()))}") # 输出区间数量统计 print("\n区间数量统计:") count_result = prices.groupby(price_bins).count() print(', '.join([f"{label}({count})" for label, count in count_result.items()]))
运行结果
价格区间分类: 2000: 1800 3000: 3000 5000: 5060 7000: 6300, 6800 8000+: 10800, 7100 区间数量统计: 2000(1), 3000(1), 5000(1), 7000(2), 8000+(2)
内容的提问来源于stack exchange,提问作者Artem kyro
相关产品推荐
相关产品推荐

