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)
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.
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'})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With