当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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