pandas.DataFrame.round#
- DataFrame.round(decimals=0, *args, **kwargs)[源代码]#
将 DataFrame 四舍五入到可变小数位数。
- Parameters:
- decimalsint, dict, Series
要将每列舍入的小数位数. 如果给出整数,则将每列舍入到相同的小数位数. 否则,字典和 Series 会舍入到可变小数位数. 如果 decimals 是类似字典的,则列名应包含在键中,如果 decimals 是 Series,则包含在索引中. decimals 中未包含的任何列将保持不变. decimals 中不是输入列的元素将被忽略.
- *args
其他关键字没有影响,但可能为了与 numpy 兼容而接受。
- **kwargs
其他关键字没有影响,但可能为了与 numpy 兼容而接受。
- Returns:
- DataFrame
一个 DataFrame,其中受影响的列会舍入到指定的小数位数.
参见
numpy.around将 numpy 数组舍入到给定的小数位数.
Series.round将 Series 舍入到给定的小数位数.
Examples
>>> df = pd.DataFrame([(.21, .32), (.01, .67), (.66, .03), (.21, .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