Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting 'no' and 'yes' into 0 and 1 in pandas dataframe [duplicate]

I want to convert data of 'edjefe' column which contains int as well as 'yes' and 'no' values. My problem is I just want to map 'yes' and 'no' to 1 and 0 and keep the int values as it is So I wrote this code

def foo(x):
    if x == 'no':
        return 0
    elif x == 'yes':
        return 1
    else:
        return x

and df1.edjefe.map(lambda x : foo(x))

But I am getting an error as,

RecursionError: maximum recursion depth exceeded while calling a Python object
like image 517
Aptha Gowda Avatar asked Nov 28 '22 06:11

Aptha Gowda


2 Answers

You can also just use replace:

df.edjefe.replace(to_replace=['no', 'yes'], value=[0, 1])

like image 116
ksbg Avatar answered Dec 05 '22 03:12

ksbg


Just use dict-like to_replace:

df['edjefe'].replace({'no': 0, 'yes': 1})
like image 39
Lev Zakharov Avatar answered Dec 05 '22 03:12

Lev Zakharov