问题
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 !
回答1:
Use np.where
Ex:
import numpy as np
df['sex'] = np.where(df['sex'] == 'female', 0, 1)
回答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)
来源:https://stackoverflow.com/questions/53040174/cannot-convert-non-finite-values-na-or-inf-to-integer