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


Python Pandas to_numeric方法用法及代碼示例

Pandas 的 to_numeric(~) 方法將輸入轉換為數字類型。默認情況下,將使用int64float64

參數

1. arg | array-like

輸入數組,可以是標量、列表、NumPy 數組或係列。

2. errors | string | optional

如何處理無法解析為數字的值:

說明

"raise"

提出錯誤。

"coerce"

轉換為 NaN

"ignore"

保留該值不變。

默認情況下,errors="raise"

3. downcast | string | optional

是否執行將數字轉換為最小數字類型(例如 int64int8 ):

說明

"integer"

將類型轉換為 np.int8

"signed"

將類型轉換為 np.int8 。與上麵相同。

"unsigned"

將類型轉換為 np.uint8

"float"

將類型轉換為 np.float32

None

不要進行任何貶低。

請注意,向下轉換是在主數字轉換之後執行的,因此如果向下轉換期間存在解析問題,則無論您為 errors 指定什麽,都會引發錯誤。

默認情況下,downcast=None

返回值

如果 arg 是一個係列,則返回一個新係列。否則,返回一個新的 Numpy 數組。

例子

基本用法

要將 Series 中所有值的類型轉換為數字類型:

s = pd.Series(["1.","2.0",3])
pd.to_numeric(s)



0    1.0
1    2.0
2    3.0
dtype: float64

請注意,源係列 s 保持不變,並在此處返回一個新係列。

錯誤處理

默認為 errors="raise" ,這意味著當轉換為數字類型時出現問題時,會拋出錯誤:

s = pd.Series(["2", "2.3.4"])
pd.to_numeric(s)



ValueError: Unable to parse string "2.3.4" at position 1

我們可以通過指定 errors="coerce" 將無效值轉換為 NaN ,而不是拋出錯誤,如下所示:

s = pd.Series(["2", "2.3.4"])
pd.to_numeric(s, errors="coerce")



0    2.0
1    NaN
dtype: float64

我們還可以使用 errors="ignore" 保留無效值:

s = pd.Series(["2", "2.3.4"])
pd.to_numeric(s, errors="ignore")



0        2
1    2.3.4
dtype: object

請注意該係列的 dtype 是 object 。這是因為即使包含一種非數字類型(在本例中為 "2.3.4")的 Series 也必須向上轉換為更通用的類型,即 object

貶低

默認情況下,數字將轉換為 int64float64

s = pd.Series(["1.", "2.0", 3])
pd.to_numeric(s)



0    1.0
1    2.0
2    3.0
dtype: float64

這裏使用float64,因為"2.0"在底層被轉換為float而不是int

我們可以通過傳入 downcast="float" 將其轉換為 float32,如下所示:

s = pd.Series(["1.", "2.0", 3])
pd.to_numeric(s, downcast="float")



0    1.0
1    2.0
2    3.0
dtype: float32

在這種情況下,由於 2.0 也可以表示為 int ,因此我們也可以傳遞 downcast="integer" 將值轉換為 int8 類型:

s = pd.Series(["1.", "2.0", 3])
pd.to_numeric(s, downcast="integer")



0    1
1    2
2    3
dtype: int8

相關用法


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