當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python pandas.to_numeric用法及代碼示例

用法:

pandas.to_numeric(arg, errors='raise', downcast=None)

將參數轉換為數值類型。

默認返回 dtype 是 float64int64,具體取決於提供的數據。使用downcast 參數獲取其他數據類型。

請注意,如果傳入的數字非常大,可能會出現精度損失。由於 ndarray 的內部限製,如果數字小於 -9223372036854775808 (np.iinfo(np.int64).min) 或大於 18446744073709551615 (np.iinfo(np.uint64).max) 被傳入,它們很可能會被轉換為浮點數,以便它們可以存儲在 ndarray 中。這些警告同樣適用於 Series,因為它在內部利用了 ndarray

參數

arg標量、列表、元組、一維數組或係列

要轉換的參數。

errors{‘ignore’, ‘raise’, ‘coerce’},默認 ‘raise’
  • 如果‘raise’,則無效解析將引發異常。

  • 如果‘coerce’,則無效解析將設置為NaN。

  • 如果‘ignore’,則無效解析將返回輸入。

downcaststr,默認無

可以是‘integer’, ‘signed’, ‘unsigned’, or ‘float’。如果不是 None,並且如果數據已成功轉換為數字 dtype(或者如果數據以數字開頭),則根據以下規則將該結果數據向下轉換為可能的最小數字 dtype:

  • ‘integer’ or ‘signed’:最小有符號 int dtype (min.:np.int8)

  • ‘unsigned’:最小的無符號整數 dtype (min.:np.uint8)

  • ‘float’:最小浮點數據類型(最小:np.float32)

由於此行為與核心轉換為數值是分開的,因此無論‘errors’ 輸入的值如何,在向下轉換期間引發的任何錯誤都將浮出水麵。

此外,僅當結果數據的 dtype 的大小嚴格大於要轉換為的 dtype 時才會發生向下轉換,因此如果檢查的 dtype 都不滿足該規範,則不會對數據執行向下轉換。

返回

ret

解析成功時的數值。返回類型取決於輸入。如果是 Series,則為 Series,否則為 ndarray。

例子

采取單獨的係列並轉換為數字,當被告知時強製

>>> s = pd.Series(['1.0', '2', -3])
>>> pd.to_numeric(s)
0    1.0
1    2.0
2   -3.0
dtype:float64
>>> pd.to_numeric(s, downcast='float')
0    1.0
1    2.0
2   -3.0
dtype:float32
>>> pd.to_numeric(s, downcast='signed')
0    1
1    2
2   -3
dtype:int8
>>> s = pd.Series(['apple', '1.0', '2', -3])
>>> pd.to_numeric(s, errors='ignore')
0    apple
1      1.0
2        2
3       -3
dtype:object
>>> pd.to_numeric(s, errors='coerce')
0    NaN
1    1.0
2    2.0
3   -3.0
dtype:float64

支持可空整數和浮點 dtype 的向下轉換:

>>> s = pd.Series([1, 2, 3], dtype="Int64")
>>> pd.to_numeric(s, downcast="integer")
0    1
1    2
2    3
dtype:Int8
>>> s = pd.Series([1.0, 2.1, 3.0], dtype="Float64")
>>> pd.to_numeric(s, downcast="float")
0    1.0
1    2.1
2    3.0
dtype:Float32

相關用法


注:本文由純淨天空篩選整理自pandas.pydata.org大神的英文原創作品 pandas.to_numeric。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。