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
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容