Python How to convert Series type : object to int

谁都会走 提交于 2020-07-23 10:37:07

问题


I'm trying to convert a Series object to integer. But I'm having trouble doing it. Every time I try something I have a new Error.

  1. I tried to convert using pd.to_numeric, error while parsing string None
  2. Then I tried to replace None values with NaN : problem replacing

#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'

actual result: dtype: object
expected result: dtype: int64


回答1:


Try

import numpy as np
df = df.fillna(np.nan)



回答2:


You seem to have a string "None" in one (or more) of the cells. Try to first replace it with np.nan and then cast to numeric:

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

Note that in pandas version <0.24 you can't have missing values (NaNs) in an integer column, that's why I suggested casting it to float.



来源:https://stackoverflow.com/questions/57161836/python-how-to-convert-series-type-object-to-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!