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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。