最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
pandas round方法保留两位小数设置实现方法
时间:2022-08-16 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下pandas round方法保留两位小数设置实现方法,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
pandas中可以使用round(n)方法返回 x 的小数点四舍五入到n个数字。简洁的说就是,四舍五入的保留小数点后的几个数字。round()不添加任何参数的时候,等同于round(0)就是取整。直接看例子:
import pandas as pd import numpy as np df_round = pd.DataFrame(np.random.random([3, 3]), columns=['A', 'B', 'C'], index=['one', 'two', 'three']) df_round = df_round*10 print(df_round) print(df_round.round(2))
我们经常需要对有浮点数的列需要保持精度,那么在pandas中该如何实现呢?这里提供一种方法,round方法
round常用用法有两种方式:
1、传入int,对所有列保持统一精度
>>> import numpy as np >>> import pandas as pd >>> df = pd.DataFrame([(.21, .32), (.01, .6), (.66, .03), (.21, .183)],columns=['dogs', 'cats']) >>> df dogs cats 0 0.21 0.320 1 0.01 0.600 2 0.66 0.030 3 0.21 0.183 # 统一保持2位小数 >>> df.round(2) dogs cats 0 0.21 0.32 1 0.01 0.60 2 0.66 0.03 3 0.21 0.18 # 统一保持一位小数 >>> df.round(1) dogs cats 0 0.2 0.3 1 0.0 0.6 2 0.7 0.0 3 0.2 0.2 >>>
2、传入dict,对指定列设置精度,key为列名,value为精度
# 指定列名设置精度,未指定的则保持原样 >>> df.round({'dogs': 2}) dogs cats 0 0.21 0.320 1 0.01 0.600 2 0.66 0.030 3 0.21 0.183 # 两列分别设置不同的精度 >>> df.round({'dogs':2, 'cats':1}) dogs cats 0 0.21 0.3 1 0.01 0.6 2 0.66 0.0 3 0.21 0.2
相关文章
- Golang ProtoBuf的基本语法详解 10-20
- Python识别MySQL中的冗余索引解析 10-20
- Python+Pygame绘制小球代码展示 10-18
- Python中的数据精度问题介绍 10-18
- Python随机值生成的常用方法介绍 10-18
- python3解压缩.gz文件分析 09-27