pandas round保留两位小数

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

pandas round保留两位小数

data_amateur   2022-09-28 我要评论

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们