当前位置:网站首页>连续变量离散化教程
连续变量离散化教程
2022-07-31 11:43:00 【梦想画家】
为了分析连续数据,通常需要离散化或分成组。本文介绍pandas包中cut和qcut函数,对连续变量进行使用不同方式进行分组。
cut函数
假设有一组人年龄数据,现在需要分为几组,分别为[18,25],[26,35],[35,60]以及60以上。实现代码:
ages = [20, 22, 25, 27, 21, 23, 37, 31, 61, 45, 41, 32]
bins = [18, 25, 35, 60, 100]
cats = pd.cut(ages, bins)
print(cats)
pd.value_counts(cats)
# (18, 25] 5
# (35, 60] 3
# (25, 35] 3
# (60, 100] 1
与数学符合保持一致,圆括号表示不包括,中括号表示包括边界值。我们也可以通过right=False改变右侧编边界:
right参数
pd.cut(ages, [18, 26, 36, 61, 100], right=False)
标签参数
我们也可以传入分组名称作为标签:
group_names = [' Youth' , ' YoungAdult' , ' MiddleAged' , ' Senior' ]
pd.cut(ages, bins, labels=group_names)
qcut函数
如果你给cut函数传入整数表示分组数量,而不是显示指明分组边界,则会根据数据集中最大值和最小值按照等长进行计算。下面示例把均匀分布数据分为四组:
data = np.random.rand(20)
pd.cut(data, 4, precision=2)
pd.value_counts(cats)
# (0.26, 0.5] 6
# (0.74, 0.99] 5
# (0.011, 0.26] 5
# (0.5, 0.74] 4
与之类似函数是qcut,基于相同数量进行分组。
数据分布不同,使用cut不一定分组有相同元素,因此qcut可以实现每组元素相同。代码如下:
data = np.random.randn(1000) # Normally distributed
cats = pd.qcut(data, 4) # Cut into quartiles
pd.value_counts(cats)
# (0.666, 3.23] 250
# (-0.00942, 0.666] 250
# (-0.651, -0.00942] 250
# (-3.186, -0.651] 250
与cut类似,也可以传入自己的数量范围:
pd.qcut(data, [0, 0.1, 0.5, 0.9, 1.])
边栏推荐
- MySQL 的几种碎片整理方案总结(解决delete大量数据后空间不释放的问题)
- Service discovery of kubernetes
- 3.网页信息解析方法:Xpath与BeautifulSoup
- Docker build Mysql master-slave replication
- The principle of v-model
- Data Lake (19): SQL API reads Kafka data and writes it to Iceberg table in real time
- kubernetes之服务发现
- mpu9150(driverack pa简明教程)
- MySQL 行级锁(行锁、临键锁、间隙锁)
- lotus-local-net 2k v1.17.0-rc4
猜你喜欢
Experience innovation and iteration through the development of lucky draw mini-programs
[Virtualization Ecological Platform] Platform Architecture Diagram & Ideas and Implementation Details
Docker实践经验:Docker 上部署 mysql8 主从复制
多线程学习笔记-2.final关键字和不变性
MySQL 的几种碎片整理方案总结(解决delete大量数据后空间不释放的问题)
【软件工程之美 - 专栏笔记】33 | 测试工具:为什么不应该通过QQ/微信/邮件报Bug?
普林斯顿微积分读本03第二章--编程实现函数图像绘制、三角学回顾
Obsidian设置图床
Power BI----几个常用的分析方法和相适应的视觉对象
三六零与公安部三所发布报告:关基设施保护成为网络安全博弈关键
随机推荐
在 Excel 内使用 ODBC 消费 SAP ABAP CDS view
分布式id解决方案
初始JDBC 编程
Candence学习篇(11) allegro中设置规则,布局,走线,铺铜
一文吃透接口调用神器RestTemplate
订song餐系统
一文带你了解redux的工作流程——actionreducerstore
Read through the interface to call the artifact RestTemplate
[Virtualization Ecological Platform] Platform Architecture Diagram & Ideas and Implementation Details
In PLC communication error or timeout or download the prompt solution of the model
redis-enterprise use
Docker build Mysql master-slave replication
【虚拟化生态平台】树莓派安装虚拟化平台操作流程
三六零与公安部三所发布报告:关基设施保护成为网络安全博弈关键
学自动化测试哪个培训机构好 试听课程后就选了这个地方学习
St. Regis Takeaway Project: File Upload and Download
kubernetes之服务发现
mysql automatically adds creation time and update time
strings包详细文档+示例
unity computeshader的可读写buffer