Search code examples
pythonstringpandasintjupyter

Python How to convert Series type : object to int


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


Solution

  • Try

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