Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - how to convert 1/0 to yes/no (in pandas.DataFrame)? [duplicate]

Tags:

In R, if I want to create a new column with YES/NO based on another column with 1 and 0, the following code serves my purpose.

df <- data.frame(alpha = c(50, 51, 52), beta = c(1,0,1))
df$gamma <- factor(df$beta, label = c('no','yes'))

  alpha beta gamma
1    50    1   yes
2    51    0    no
3    52    1   yes

But I am not sure how to do the same in Python. Can anyone finish the following code or suggest different methods?

import pandas as pd
df = pd.DataFrame({'alpha': [50, 51, 52], 'beta': [1,0,1]})
df['gamma'] = ??????

Thanks in advance. (The simpler, the better)

like image 959
T_T Avatar asked Apr 29 '18 09:04

T_T


People also ask

How do you replace yes with 1 and no with 0 in Python?

To change a column of yes or no to 1 or 0, for this purpose, we will use the map() function. The map() method will help us to traverse each value of DataFrame so that we can check the value at the same time.


1 Answers

You can use pd.Series.map, which accepts a dictionary input:

import pandas as pd

df = pd.DataFrame({'alpha': [50, 51, 52], 'beta': [1,0,1]})

df['gamma'] = df['beta'].map({True: 'yes', False: 'no'})
like image 55
jpp Avatar answered Sep 28 '22 19:09

jpp