pandas.to_numeric#
- pandas.to_numeric(arg, errors='raise', downcast=None, dtype_backend=<no_default>)[原始碼]#
將引數轉換為數值型別。
如果輸入已為數字 dtype,則將保留該 dtype。對於非數字輸入,預設返回 dtype 是 float64 或 int64,具體取決於提供的資料。使用 downcast 引數獲取其他 dtype。
請注意,如果傳入非常大的數字,可能會發生精度損失。由於 ndarray 的內部限制,如果傳入小於 -9223372036854775808 (np.iinfo(np.int64).min) 或大於 18446744073709551615 (np.iinfo(np.uint64).max) 的數字,它們很可能會被轉換為 float,以便儲存在 ndarray 中。這些警告同樣適用於 Series,因為 Series 在內部利用了 ndarray。
- 引數:
- arg標量、列表、元組、一維陣列或 Series
要轉換的引數。
- errors{‘raise’, ‘coerce’}, default ‘raise’
如果為“raise”,則無效解析將引發異常。
如果為“coerce”,則無效解析將設定為 NaN。
- downcaststr,預設 None
可以是“integer”、“signed”、“unsigned”或“float”。如果不是 None,並且資料已成功轉換為數字 dtype(或資料本身就是數字),則根據以下規則將結果資料向下轉換為最小的數字 dtype。
“integer”或“signed”:最小的有符號整數 dtype(最小:np.int8)。
“unsigned”:最小的無符號整數 dtype(最小:np.uint8)。
“float”:最小的浮點數 dtype(最小:np.float32)。
由於此行為與核心轉換為數字值是分開的,因此在向下轉換過程中引發的任何錯誤都將顯示出來,而不管“errors”輸入的值如何。
此外,僅當結果資料的 dtype 大於要轉換為的 dtype 時,才會執行向下轉換。因此,如果檢查的 dtype 都不滿足此規範,則不會對資料執行向下轉換。
- dtype_backend{‘numpy_nullable’, ‘pyarrow’}
應用於結果
DataFrame的後端資料型別(仍處於實驗階段)。如果未指定,則預設行為是不使用可為空的資料型別。如果指定,行為如下:"numpy_nullable":返回可空 dtype 支援的物件。"pyarrow":返回帶有 pyarrow 支援的可空物件。
版本 2.0 中已新增。
- 返回:
- ret
如果解析成功,則為數字。返回型別取決於輸入。如果是 Series,則返回 Series;否則返回 ndarray。
- 引發:
- ValueError
如果輸入包含非數字值且 errors='raise'。
- TypeError
如果輸入不是列表狀、一維或可轉換為數字的標量,例如巢狀列表或不受支援的輸入型別(例如,dict)。
另請參閱
DataFrame.astype將引數強制轉換為指定的資料型別。
to_datetime將引數轉換為 datetime。
to_timedelta將引數轉換為 timedelta。
numpy.ndarray.astype將 numpy 陣列轉換為指定型別。
DataFrame.convert_dtypes轉換資料型別。
示例
接受單獨的 Series 並轉換為數字,根據指示進行強制轉換。
>>> 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="coerce") 0 NaN 1 1.0 2 2.0 3 -3.0 dtype: float64
支援可空整數和浮點數的向下轉換。
>>> 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