7

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
jpp
  • 159,742
  • 34
  • 281
  • 339
Aptha Gowda
  • 968
  • 2
  • 10
  • 20

5 Answers5

17

You can also just use replace:

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

ksbg
  • 3,214
  • 1
  • 22
  • 35
  • `TypeError: Cannot compare types 'ndarray(dtype=int64)' and 'str'` – Aptha Gowda Aug 03 '18 at 12:40
  • String replace requires a string as an input and an output. Replace yes and no with `value=['0', '1']`, then cast the result with `int()`. – addohm Aug 03 '18 at 12:47
  • Note also that `replace` has a flag `inplace=True` for replacing the values in the dataframe in-place, rather than returning the modified values. – Anton Schwaighofer Nov 21 '22 at 11:27
8

Just use dict-like to_replace:

df['edjefe'].replace({'no': 0, 'yes': 1})
Lev Zakharov
  • 2,409
  • 1
  • 10
  • 24
4

You can use pd.Series.map with a dictionary mapping followed by pd.Series.fillna:

d = {'no': 0, 'yes': 1}
df1['edjefe'] = df1['edjefe'].map(d).fillna(df1['edjefe'])

You will likely find this more efficient than pd.Series.replace.

See Replace values in a pandas series via dictionary efficiently for more details.

If you have mutable objects in your series, this will fail, since dictionary keys must be hashable. You can convert to strings in this case:

df1['edjefe'] = df1['edjefe'].astype(str).map(d).fillna(df1['edjefe'])
jpp
  • 159,742
  • 34
  • 281
  • 339
1

You can also try:

df1['edjefe'] = (df1['edjefe']=="yes")*1 
0

You can use pandas.Categorical as well.

df1["edjefe"] = pd.Categorical(df1["edjefe"]).codes

Visit here for more information.

Maryam Bahrami
  • 1,056
  • 9
  • 18