首页 > 解决方案 > Python如何将Series类型:对象转换为int

问题描述

我正在尝试将 Series 对象转换为整数。但我很难做到这一点。每次我尝试某些东西时,我都会遇到一个新错误。

  1. 我尝试pd.to_numeric在解析字符串时使用,错误进行转换None
  2. 然后我尝试将None值替换为NaN:问题替换

#1.1)

pd.to_numeric(df['Var1'], downcast = 'integer')

ValueError: Unable to parse string "None" at position 44816

#1.2)

df.astype({'Var1':'int64'}).dtypes

TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

#2)

df['Var1'].astype(str).astype(int)

ValueError: invalid literal for int() with base 10: 'None'

实际结果:dtype:object
预期结果:dtype:int64

标签: pythonstringpandasintjupyter

解决方案


您似乎"None"在一个(或多个)单元格中有一个字符串。尝试先将其替换为np.nan然后转换为数字:

import numpy as np
df = df.replace("None", np.nan).astype({'Var1': float})

请注意,在熊猫版本 <0.24 中,整数列中不能有缺失值(NaN),这就是我建议将其转换为浮点数的原因。


推荐阅读