Converting yes/no to integer type 1/0 (not just replacing) in Pandas data frame

Viewed 548

After looking at several posts here, every post explains how to replace yes/no in a column with 1/0, but the datatype of those numbers remain 'object' and is not float or int (even after I use astype(int)), so I can't do further operation with them. My code is below. Anyone knows how to convert datatype now from object to float or int?

df['Inter Plan'].replace({'no': 0, 'yes': 1}).astype(int)

print(df['Inter Plan'].dtypes)
3 Answers

astype returns a pandas series, it is not done in place. Use:

df["Inter Plan"] = df['Inter Plan'].replace({'no': 0, 'yes': 1}).astype(int)

There is a copy option for astype which will allow you to do the operation in place, but because you are using replace as well, I don't think you'll be able to do it all in one line, so it is probably best to just use the above piece of code. In addition, the in-place option (which is setting copy to False) comes with a warning:

be very careful setting copy=False as changes to values then may propagate to other pandas objects.

Try casting to str before replacing:

df['Inter Plan'] = df['Inter Plan'].str.replace({'no': 0, 'yes': 1}).astype(int)

One way to do this:

df['Inter Plan'].replace({'no': 0, 'yes': 1}, inplace=True).astype('int', copy=False)
Related