pandas.to_numeric(arg,?errors='raise',?downcast=None) ? ? ? ??[source]
將參數轉換為數字類型。
默認返回dtype為float64或int64,?具體取決于提供的數據。使用downcast參數獲取其他dtype。
請注意,如果傳入非常大的數字,則可能會導致精度損失。由于ndarray的內部限制,如果數字小于-9223372036854775808(np.iinfo(np.int64).min)或大于18446744073709551615(np.iinfo(np.uint64).max)傳入,很有可能會將它們轉換為float以便將其存儲在ndarray中。這些警告類似地適用于?Series,因為它在內部利用ndarray。
參數:arg?:?scalar(標量),list(列表),
(tuple)元組,一維數組(1-d array)或Series
errors?:?{'ignore','raise','coerce'},
默認為'raise'
如果為‘raise’,
則無效的解析將引發異常
如果為?‘coerce’,
則將無效解析設置為NaN
如果為?‘ignore’,
則無效的解析將返回輸入
downcast?:
{'integer','signed','unsigned','float'},
默認為None
如果不是None(無),并且數據已成功轉換為數字dtype
(或者數據是從數字開始的),
則根據以下規則將結果數據轉換為可能的最小數字dtype:
'integer'或'signed':
最小的有符號int dtype(最小值:np.int8)
'unsigned':
最小的無符號int dtype(最小值:np.uint8)
'float':
最小的float dtype(最小值:np.float32)
由于此行為與從核心轉換為數值的行為是分開的,
因此無論?‘errors’輸入的值如何,
向下轉換期間引發的任何錯誤都會浮出水面。
此外,僅當結果數據的dtype的大小,
嚴格大于要強制轉換為dtype的dtype時,
才會發生向下轉換,因此,
如果檢查的所有dtype都不滿足該規范,
則不會對該數據執行向下轉換。
0.19.0版中的新功能。
返回值:ret:?解析成功時為numeric(數字)。
返回類型取決于輸入。
如果為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