pandas.DataFrame.round#

DataFrame.round(decimals=0, *args, **kwargs)[源代码]#

将 DataFrame 中的数值列四舍五入到可变的小数位数。

参数:
decimalsint, dict, Series

要将每列四舍五入到的小数位数。如果给定一个整数,则将每列四舍五入到相同的小数位数。否则,dict 和 Series 将四舍五入到可变数量的小数位数。如果 decimals 是类似 dict 的对象,则列名应作为键;如果 decimals 是 Series,则列名应作为索引。未包含在 decimals 中的任何列将保持不变。 decimals 中不是输入列的元素将被忽略。

*args

附加关键字没有效果,但可能会为与 numpy 兼容而接受。

**kwargs

附加关键字没有效果,但可能会为与 numpy 兼容而接受。

返回:
DataFrame

一个 DataFrame,其中受影响的列四舍五入到指定的小数位数。

另请参阅

numpy.around

将 numpy 数组四舍五入到指定的小数位数。

Series.round

将 Series 四舍五入到指定的小数位数。

注意

对于正好在两个四舍五入的十进制值之间的值,pandas 会四舍五入到最接近的偶数(例如,-0.5 和 0.5 四舍五入到 0.0,1.5 和 2.5 四舍五入到 2.0,依此类推)。

示例

>>> df = pd.DataFrame(
...     [(0.21, 0.32), (0.01, 0.67), (0.66, 0.03), (0.21, 0.18)],
...     columns=["dogs", "cats"],
... )
>>> df
    dogs  cats
0  0.21  0.32
1  0.01  0.67
2  0.66  0.03
3  0.21  0.18

通过提供一个整数,每列都将被四舍五入到相同的小数位数。

>>> df.round(1)
    dogs  cats
0   0.2   0.3
1   0.0   0.7
2   0.7   0.0
3   0.2   0.2

使用 dict 时,可以通过将列名作为键,将小数位数作为值来指定特定列的小数位数。

>>> df.round({"dogs": 1, "cats": 0})
    dogs  cats
0   0.2   0.0
1   0.0   1.0
2   0.7   0.0
3   0.2   0.0

使用 Series 时,可以通过将列名作为索引,将小数位数作为值来指定特定列的小数位数。

>>> decimals = pd.Series([0, 1], index=["cats", "dogs"])
>>> df.round(decimals)
    dogs  cats
0   0.2   0.0
1   0.0   1.0
2   0.7   0.0
3   0.2   0.0