Pandas DataFrame.round(~)
方法返回 DataFrame,其所有數值根據指定參數進行舍入。
參數
1.decimals
| int
或 dict
或 Series
| optional
要舍入的小數位數。舍入的列取決於 decimals
的數據類型:
類型 |
說明 |
---|---|
|
DataFrame 中的所有值都將四舍五入。 |
|
隻有指定的列才會被四舍五入。 |
|
隻有指定的列才會被四舍五入。 |
請注意, decimals=1
意味著像 1.52
這樣的值將四舍五入為 1.5
。相反,decimals=-1
會將 13
等值舍入為 10
(最接近的第 10 位)。
對於數據類型 dict
和 Series
,鍵和索引將是要舍入的列的名稱,相應的值是要舍入的小數位數。請參閱下麵的示例以進行說明。
默認情況下, decimals=0
,這意味著值將四舍五入到最接近的整數。
警告
以 5
結尾的數字將向下舍入。例如,2.5
和 3.45
等數字將分別向下舍入為 2
和 3.4
,而不是向上舍入。
返回值
DataFrame
,其值根據提供的參數進行舍入。
例子
將所有值四舍五入到最接近的整數
考慮以下 DataFrame :
df = pd.DataFrame({"A":[1.05,2.42],"B":[3.45,4.9]})
df
A B
0 1.05 3.45
1 2.42 4.90
要四舍五入到最接近的整數,隻需直接調用round()
:
df.round()
A B
0 1.0 3.0
1 2.0 5.0
將所有值四舍五入到最接近的十位
考慮以下 DataFrame :
df = pd.DataFrame({"A":[4,6],"B":[12,18]})
df
A B
0 4 12
1 6 18
要舍入到最接近的 10 位,請提供 -1
作為參數:
df.round(-1)
A B
0 0 10
1 10 20
將所有值四舍五入到小數點後第一位
考慮以下 DataFrame :
df = pd.DataFrame({"A":[1.07,2.42],"B":[3.45,4.9]})
df
A B
0 1.07 3.45
1 2.42 4.90
要四舍五入到小數點後第一位,請提供 1
作為參數:
df.round(1)
A B
0 1.1 3.4
1 2.4 4.9
請注意 3.45
如何向下舍入為 3.4
而不是向上舍入為 3.5
。
僅對某些列進行舍入
我們可以提供 dict
或 Series
來舍入某些列,而不是提供 int
。
字典傳遞
提供 dict
時,鍵必須是列名稱,而值必須是要舍入的小數位。
作為示例,請考慮以下 DataFrame:
df = pd.DataFrame({"A":[4.2,6.6],"B":[12.4,18.9]})
df
A B
0 4.2 12.4
1 6.6 18.9
僅將列 A
舍入為最接近的整數,並保持列 B
不變:
df.round({"A":0})
A B
0 4.0 12.4
1 7.0 18.9
請注意 B
列如何保持原樣。
係列賽通過
同樣,當提供 Series
時,索引必須是列名,而值必須是要舍入的小數位。
考慮以下 DataFrame :
df = pd.DataFrame({"A": [4.2,6.6], "B": [12.4,18.9]})
df
A B
0 4.2 12.4
1 6.6 18.9
僅將列 A
舍入為最接近的整數,並保持列 B
不變:
decimals = pd.Series([0], index=["A"])
df.round(decimals)
A B
0 4.0 12.4
1 7.0 18.9
請注意 B
列如何保持原樣。
相關用法
- Python Pandas DataFrame rolling方法用法及代碼示例
- Python Pandas DataFrame rank方法用法及代碼示例
- Python Pandas DataFrame rdiv方法用法及代碼示例
- Python Pandas DataFrame radd方法用法及代碼示例
- Python PySpark DataFrame repartition方法用法及代碼示例
- Python PySpark DataFrame replace方法用法及代碼示例
- Python PySpark DataFrame rdd屬性用法及代碼示例
- Python Pandas DataFrame reset_index方法用法及代碼示例
- Python Pandas DataFrame reorder_levels方法用法及代碼示例
- Python Pandas DataFrame rsub方法用法及代碼示例
- Python Pandas DataFrame resample方法用法及代碼示例
- Python Pandas DataFrame reindex方法用法及代碼示例
- Python PySpark DataFrame randomSplit方法用法及代碼示例
- Python Pandas DataFrame replace方法用法及代碼示例
- Python Pandas DataFrame rpow方法用法及代碼示例
- Python Pandas DataFrame rfloordiv方法用法及代碼示例
- Python Pandas DataFrame rtruediv方法用法及代碼示例
- Python Pandas DataFrame rename_axis方法用法及代碼示例
- Python Pandas DataFrame rmod方法用法及代碼示例
- Python Pandas DataFrame rmul方法用法及代碼示例
- Python Pandas DataFrame rename方法用法及代碼示例
- Python Pandas DataFrame empty屬性用法及代碼示例
- Python Pandas DataFrame pop方法用法及代碼示例
- Python Pandas DataFrame nsmallest方法用法及代碼示例
- Python Pandas DataFrame sample方法用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Pandas DataFrame | round method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。