pandas round方法保留两位小数的设置实现

Owen
Owen
发布时间:2026-10-15 | 5人浏览过
原创

本文介绍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方法的常用使用方式主要有两种:

第一种方式是传入整数参数,对所有数据列应用统一的精度标准。

>>> 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
>>> 

第二种方式是传入字典参数,针对特定列单独设置精度。其中,字典的键(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方法实现保留两位小数及相关精度设置的说明已完成。如需了解更多相关技巧,可查阅本站过往文章或继续浏览后续内容。感谢大家的支持!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表