介绍: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()
操作
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()
方法来对其中的所有元素进行操作
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()
方法来对其中的所有元素进行操作。
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)
完!