Pandas 中的 round()
方法用于将值四舍五入到指定的小数位数。
示例
import pandas as pd
# create a DataFrame
data = {'Value1': [1.1234, 2.3456, 3.5678],
'Value2': [4.2345, 5.6789, 6.9123]}
df = pd.DataFrame(data)
# round the entire DataFrame to 2 decimal places
df_rounded = df.round(2)
print(df_rounded)
'''
Output
Value1 Value2
0 1.12 4.23
1 2.35 5.68
2 3.57 6.91
'''
round() 语法
Pandas 中 round()
方法的语法是
df.round(decimals=0, *args, **kwargs)
round() 参数
round()
方法接受以下参数
decimal
(可选) - 四舍五入到的小数位数*args
和**kwargs
(可选) - 可以传递给函数的其他参数和关键字参数
round() 返回值
round()
方法返回一个新 DataFrame,其中数据已四舍五入到给定的十进制位数。
示例 1:将 DataFrame 元素四舍五入到最近的整数
import pandas as pd
# create a DataFrame
data = {'Value1': [1.1234, 2.3456, 3.5678],
'Value2': [4.2345, 5.6789, 6.9123]}
df = pd.DataFrame(data)
# round the entire DataFrame elements to nearest integer
df_rounded = df.round()
print(df_rounded)
输出
Value1 Value2 0 1.0 4.0 1 2.0 6.0 2 4.0 7.0
在此示例中,round()
方法将 df DataFrame 的元素四舍五入到最近的整数。
示例 2:将元素四舍五入到指定的小数位数
import pandas as pd
# sample data
data = {
'A': [1.12345, 2.98765],
'B': [3.10234, 4.76543]
}
# create a DataFrame
df = pd.DataFrame(data)
# round to 3 decimal places
df_rounded = df.round(3)
print(df_rounded)
输出
A B 0 1.123 3.102 1 2.988 4.765
在上面的示例中,round()
方法用于四舍五入 df DataFrame 的元素。
参数 3 表示我们希望将 df 中的所有数值四舍五入到三位小数。
示例 3:四舍五入特定列
import pandas as pd
# create a DataFrame
data = {'Value1': [1.1234, 2.3456, 3.5678],
'Value2': [4.2345, 5.6789, 6.9123]}
df = pd.DataFrame(data)
# round specific columns to given number of decimal places
df_rounded = df.round({'Value1': 1, 'Value2': 2})
print(df_rounded)
输出
Value1 Value2 0 1.1 4.23 1 2.3 5.68 2 3.6 6.91
在这里,我们向 round()
方法传递了一个字典,其中
'Value1': 1
- 指定标签为Value1
的列应四舍五入到1位小数。'Value2': 2
- 指定标签为Value2
的列应四舍五入到2位小数。