python 浮点数 round 舍一法 向零取整 df 数组 Series 三种数据类型实现
介绍:python的round函数,默认进行四舍五入,我需要将3.45 保留一位小数,3.4
一、一般格式
使用 Python 的内置函数 math.floor()
来向下取整到指定的小数位数。例如,如果你想保留小数点后一位并向下取整,可以这样做:
import math num = 3.45 rounded_num = math.floor(num * 10) / 10 print(rounded_num)
二、数组
使用列表推导式来对数组中的所有元素进行 math.floor()
操作
1 2 3 4 5 | import math nums = [ 3.45 , 2.67 , 5.89 , 4.12 ] rounded_nums = [math.floor(num * 10 ) / 10 for num in nums] print (rounded_nums) |
三、DataFrame(df格式)
使用 applymap()
方法来对其中的所有元素进行操作
1 2 3 4 5 6 7 8 | import pandas as pd import math data = { 'A' : [ 3.45 , 2.67 , 5.89 , 4.12 ], 'B' : [ 1.23 , 4.56 , 7.89 , 3.21 ]} df = pd.DataFrame(data) rounded_df = df.applymap( lambda x: math.floor(x * 10 ) / 10 ) print (rounded_df) |
四、Series
使用 apply()
方法来对其中的所有元素进行操作。
1 2 3 4 5 6 7 8 9 | import pandas as pd import math data = { 'A' : [ 3.45 , 2.67 , 5.89 , 4.12 ]} df = pd.DataFrame(data) num = df[ 'A' ] rounded_series = num. apply ( lambda x: math.floor(x * 10 ) / 10 ) print (rounded_series) |
完!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)