Pandas 的 to_numeric(~)
方法將輸入轉換為數字類型。默認情況下,將使用int64
或float64
。
參數
1. arg
| array-like
輸入數組,可以是標量、列表、NumPy 數組或係列。
2. errors
| string
| optional
如何處理無法解析為數字的值:
值 |
說明 |
---|---|
|
提出錯誤。 |
|
轉換為 |
|
保留該值不變。 |
默認情況下,errors="raise"
。
3. downcast
| string
| optional
是否執行將數字轉換為最小數字類型(例如 int64
到 int8
):
值 |
說明 |
---|---|
|
將類型轉換為 |
|
將類型轉換為 |
|
將類型轉換為 |
|
將類型轉換為 |
|
不要進行任何貶低。 |
請注意,向下轉換是在主數字轉換之後執行的,因此如果向下轉換期間存在解析問題,則無論您為 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
。
貶低
默認情況下,數字將轉換為 int64
或 float64
:
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
相關用法
- Python Pandas to_timedelta方法用法及代碼示例
- Python Pandas to_datetime方法用法及代碼示例
- Python torch.distributed.rpc.rpc_async用法及代碼示例
- Python torch.nn.InstanceNorm3d用法及代碼示例
- Python torchaudio.transforms.Fade用法及代碼示例
- Python torch.special.gammaincc用法及代碼示例
- Python torch.optim.lr_scheduler.ConstantLR用法及代碼示例
- Python torch.normal用法及代碼示例
- Python torchdata.datapipes.iter.Multiplexer用法及代碼示例
- Python torch.nn.quantized.dynamic.LSTM用法及代碼示例
- Python torch.nn.EmbeddingBag用法及代碼示例
- Python torch.nn.Module.register_forward_hook用法及代碼示例
- Python torch.nn.AvgPool2d用法及代碼示例
- Python torch.nn.PixelShuffle用法及代碼示例
- Python torch.Generator.initial_seed用法及代碼示例
- Python torch.resolve_neg用法及代碼示例
- Python torchtext.vocab.Vectors.get_vecs_by_tokens用法及代碼示例
- Python torch.nn.CELU用法及代碼示例
- Python torch.reciprocal用法及代碼示例
- Python torch.nn.Hardsigmoid用法及代碼示例
- Python torch.fft.fft用法及代碼示例
- Python torch.distributed.TCPStore用法及代碼示例
- Python torch.distributed.pipeline.sync.skip.skippable.stash用法及代碼示例
- Python torch.nn.GLU用法及代碼示例
- Python torch.nn.functional.conv1d用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Pandas | to_numeric method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。