Question

[Solved] Cannot convert non-finite values (NA or inf) to integer [duplicate]

I have a dataframe looks like this

   survived pclass  sex age sibsp   parch   fare    embarked
    0   1   1   female  29.0000 0   0   211.3375    S
    1   1   1   male    0.9167  1   2   151.5500    S
    2   0   1   female  2.0000  1   2   151.5500    S
    3   0   1   male    30.0000 1   2   151.5500    S
    4   0   1   female  25.0000 1   2   151.5500    S

I want to convert ‘sex’ to 0, 1 coding and used isnull checked that there is no NA in the column

However, on this line I received ValueError: Cannot convert non-finite values (NA or inf) to integer

df['sex'] = df['sex'].map({'female':0, 'male':1}).astype(int)

Any suggestions ? thank you !

Enquirer: Osca

||

Solution #1:

Use np.where

Ex:

import numpy as np

df['sex'] = np.where(df['sex'] == 'female', 0, 1)
Respondent: Rakesh

Solution #2:

I think the proper way to do it is by using the replace function

df.replace({'sex':{'female':0, 'male':1}}, inplace=True)

If your df has nans, then you could fill them by some value, e.g. -1, using fillna and then replace the rest

df.fillna({'sex':-1}, inplace=True)
df.replace({'sex':{'female':0, 'male':1}}, inplace=True)
Respondent: Andreas K.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy