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
到此这篇关于pandas round方法保留两位小数的设置实现的文章就介绍到这了,更多相关pandas round方法保留两位小数内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!