0

I have a column in my dataset which have the following values (single, married) some of the cell are empty and I want to convert single to 0 and married to 1 and convert it from string to int

df.X4[df.X4 == 'single'] = 1
df.X4[df.X4 == 'married'] = 2
df['X4'] = df['X4'].astype(str).astype(int)

the cells that has no value give this error

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

I have tried fillna like this : df.X4.fillna(0)

but still give same error

desertnaut
  • 52,940
  • 19
  • 125
  • 157
Amira Elsayed Ismail
  • 8,822
  • 30
  • 81
  • 160

1 Answers1

1

Let us try

df.X4[df.X4 == 'single'] = 1
df.X4[df.X4 == 'married'] = 2
df['X4'] = pd.to_numeric(df['X4'], errors='coerce').fillna(0).astype(int)
BENY
  • 296,997
  • 19
  • 147
  • 204