Python小案例(五)循环判断进行分组
2023-06-13 09:17:15 时间
Python小案例(五)循环判断进行分组
需求背景:现有一列按照某规则排序后的产品,想进行打包进行组合售卖。要求按顺序进行价格累积,当价格累积超过2000后,需要从下一个产品重新开始打包。
- 构造数据
import pandas as pd
# 构造数据
df_cycle = pd.DataFrame(
{'顺序':[i for i in range(12)],
'价格':[1000,500,600,800,1000,700,400,300,200,500,200,100],})
# 查看数据情况
df_cycle
顺序 | 价格 | |
---|---|---|
0 | 0 | 1000 |
1 | 1 | 500 |
2 | 2 | 600 |
3 | 3 | 800 |
4 | 4 | 1000 |
5 | 5 | 700 |
6 | 6 | 400 |
7 | 7 | 300 |
8 | 8 | 200 |
9 | 9 | 500 |
10 | 10 | 200 |
11 | 11 | 100 |
- 利用python进行循环判断
df_cycle['cumu']=0 # 初始累积值为0
df_cycle['class']=0 # 初始类别为0
# 通过循环判断进行分组
inint_price=0
i=0
for index, row in df_cycle.iterrows():
price=row['价格']
inint_price+=price
if inint_price>=2000:
df_cycle.at[index, 'cumu']=inint_price
df_cycle.at[index, 'class']=i
i=i+1
inint_price=0
else:
df_cycle.at[index, 'cumu']=inint_price
df_cycle.at[index, 'class']=i
df_cycle
顺序 | 价格 | cumu | class | |
---|---|---|---|---|
0 | 0 | 1000 | 1000 | 0 |
1 | 1 | 500 | 1500 | 0 |
2 | 2 | 600 | 2100 | 0 |
3 | 3 | 800 | 800 | 1 |
4 | 4 | 1000 | 1800 | 1 |
5 | 5 | 700 | 2500 | 1 |
6 | 6 | 400 | 400 | 2 |
7 | 7 | 300 | 700 | 2 |
8 | 8 | 200 | 900 | 2 |
9 | 9 | 500 | 1400 | 2 |
10 | 10 | 200 | 1600 | 2 |
11 | 11 | 100 | 1700 | 2 |
共勉~
相关文章
- python win32api messagebox_如何在Python中使用Win32 API?
- 【Python】Ubuntu修改默认Python版本
- 【菜鸟学Python】案例一:汇率换算「建议收藏」
- pythondecode函数的用法_如何使用python中的decode函数?[通俗易懂]
- 迭代器Python_python进阶路线
- 【说站】python中condition条件变量的作用
- 【说站】Python特征降维如何理解
- python分析人口出生率代码_国家统计局居然也能用的上Python?人口数据Python脚本了解一下?…[通俗易懂]
- python调用通达信公式_通达信公式-主力雷达Python化[通俗易懂]
- 在python中用来安装第三方库的常用工具_什么库用于安装管理Python扩展包
- linux开机自启动python脚本_python3执行linux命令
- 下列python语句的输出结果是print_下列 Python语句的输出结果是「建议收藏」
- 廖雪峰的 Python 教程_python基础教程廖雪pdf
- Python获取手机4K壁纸,一个入门练手的案例
- Python 探索性数据分析工具(PandasGUI,Pandas Profiling,Sweetviz,dtale)以及学术论文快速作图science.mplstyle
- Python写入csv出现空白行,如何解决?
- Rust最受喜爱却少有人用,Python仅排第六,2021全球开发者调查报告出炉
- 自定义异常类 python
- python之面向对象详解编程语言
- Python的sorted函数应用详解编程语言
- Python学习案例详解编程语言
- python之event【事件】详解编程语言
- Python简易操作MySQL数据库指南(python操作mysql数据库)
- 从Python连接Oracle数据库介绍(python连接oracle)
- Python与MySQL实现数据分析的完美组合(mysql中python)
- 使用cxoracle操作Python的完美路径(cx_oracle 路径)
- python求素数示例分享
- Python中字符编码简介、方法及使用建议