pd.to_numeric

作用

作用:将参数转换为数字类型。

默认返回dtype为float64或int64, 具体取决于提供的数据。使用downcast参数获取其他dtype。

参数描述

参数 描述
args 接受scalar, list, tuple, 1-d array, or Series类型
errors 有3种类型{‘ignore’, ‘raise’, ‘coerce’}, 默认为‘raise’
downcast {‘integer’, ‘signed’, ‘unsigned’, ‘float’} , default None,默认返回float64或int64
注意downcast的意思是向下转换

errors中参数的解释

'raise’参数:无效的解析将引发异常

'corece’参数:将无效解析设置为NaN

‘ignore’参数:**无效的解析将返回输入

downcast中参数的意义

默认的None就是不进行处理

‘integer’’signed’:最小的有符号整数dtype(最小值np.int8)

‘unsigned’:最小的unsigned int dtype(np.uint8)

‘float’:最小的float dtype(np.float32)

返回值:如果解析成功,则为数字。其中返回类型取决于输入。如果为Series,则为Series,否则为ndarray。

实例

import pandas as pd
import numpy as np
s = pd.Series(['apple', '1.0', '2','2019-01-02',1, False,None,pd.Timestamp('2018-01-05')])

# to_numeric是在object,时间格式中间做转换,然后再使用astype做numeric类型的内部转换
pd.to_numeric(s, errors='raise') # 遇到非数字字符串类型报错,bool类型报错,时间类型转换为int
pd.to_numeric(s, errors='ignore') # 只对数字字符串转换,其他类型一律不转换,包含时间类型
pd.to_numeric(s, errors='coerce')  # 将时间字符串和bool类型转换为数字,其他均转换为NaN

# downcast 可以进一步转化为int或者float
pd.to_numeric(s) # 默认float64类型
pd.to_numeric(s, downcast='signed') # 转换为整型

# astype中的error没有`coerce`选项,所以只适合`numeric`内部类型的转换,比如将int32转换为int64,int32转换为float32
# 而不适合在object,时间格式之间做转换,
s.astype('int32',errors='raise')
s.astype('int32',errors='ignore')  # 对object无效,astype只能对numeric类型生效

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hyk今天写算法了吗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值