运行环境:

python 3.6.6
pandas 1.1.2
window10


问题描述:

使用pandas的astype()方法的时候报错
TypeError: int() argument must be a string, a bytes-like object or a number, not ‘NoneType’

df['store_rank'] = df['store_rank'].astype(int)

原因分析:

'store_rank’这一列里面有空数据(NaN),导致转为int类型的时候报错


解决方案:

使用pandas.to_numeric()方法,改方法里面有个errors 参数,可以选择处理数据发生异常时候的处理方法
以下是errors参数的三个选择,默认为’raise’
errors : {‘ignore’, ‘raise’, ‘coerce’}, default ‘raise’
- If ‘raise’, then invalid parsing will raise an exception.
- If ‘coerce’, then invalid parsing will be set as NaN.
- If ‘ignore’, then invalid parsing will return the input.
‘raise’:无效解析将引发异常
‘coerce’: 无效解析将转为类型
‘ignore’:无效解析返回原来的输入

df['store_rank'] = pandas.to_numeric(df['store_rank'], errors='coerce')
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐