python - 计算熊猫中列的四分位数类别
问题描述
我有一个如下所示的数据框
东风:
product_x year total_price total_sale
A 2016 50 200
B 2016 200 100
A 2017 250 250
B 2017 1000 300
A 2018 100 50
B 2018 900 600
K 2016 20 300
D 2016 100 450
在上面的数据框中,我想添加名为 total_sale_Quartile 的新列。
计算 total_sale_Quartile 的说明。
排序 total_sale 如下所示
50, 100, 200, 250, 300, 300, 450, 600
Q1 = 50 to 100
Q2 = 101 to 250
Q3 = 251 to 300
Q4 = 301 to 600
预期输出:
product_x year total_price total_sale total_sale_Quartile
A 2016 50 200 Q2
B 2016 200 100 Q1
A 2017 250 250 Q2
B 2017 1000 300 Q3
A 2018 100 50 Q1
B 2018 900 600 Q4
K 2016 20 300 Q3
D 2016 100 450 Q4
解决方案
使用,pd.cut
带有可选参数include_lowest=True
将值从total_sale
into分类Quartiles
:
df['total_sale_Quartile'] = (
pd.cut(
df['total_sale'], bins=[50, 100, 250, 300, 600],
labels=['Q1', 'Q2', 'Q3', 'Q4'], include_lowest=True)
)
或者,pd.qcut
如果您想仅根据分位数范围对列进行分类,请使用:
df['total_sale_Quartile'] = (
pd.qcut(df['total_sale'], 4, labels=['Q1', 'Q2', 'Q3', 'Q4'])
)
结果:
# print(df)
product_x year total_price total_sale total_sale_Quartile
0 A 2016 50 200 Q2
1 B 2016 200 100 Q1
2 A 2017 250 250 Q2
3 B 2017 1000 300 Q3
4 A 2018 100 50 Q1
5 B 2018 900 600 Q4
6 K 2016 20 300 Q3
7 D 2016 100 450 Q4
推荐阅读
- python - Python 检查 listelement 是否在值中,但返回它找到的 listelement 而不是 true
- javascript - 如果用户中断,自动向下滚动取消
- python - 基于一个共同的项目运行两个烧瓶应用程序
- java - 我如何调用这些方法?
- javascript - bcrypt.compare() 或 bcrypt.compareSync()
- python - 如何使用带有 preprocessing_function 的数据生成器正确加载图像?
- python - Telethon,给定要更改的单词,更改文本实体的偏移量和长度
- kotlin - 将对象变量公开为公共使其成员无法解析
- rest - 不同 HTTP 方法的目的?
- spring-boot - 为什么数据库Hibernate jpa中的employee_id和department_id不自动更新