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
  • 57,590
  • 26
  • 140
  • 166
Amira Elsayed Ismail
  • 9,216
  • 30
  • 92
  • 175

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
  • 317,841
  • 20
  • 164
  • 234