How to change values in a dataframe Python

Viewed 106619

I've searched for an answer for the past 30 min, but the only solutions are either for a single column or in R. I have a dataset in which I want to change the ('Y/N') values to 1 and 0 respectively. I feel like copying and pasting the code below 17 times is very inefficient.

df.loc[df.infants == 'n', 'infants'] = 0
df.loc[df.infants == 'y', 'infants'] = 1
df.loc[df.infants == '?', 'infants'] = 1

My solution is the following. This doesn't cause an error, but the values in the dataframe doesn't change. I'm assuming I need to do something like df = df_new. But how to do this?

for coln in df:
for value in coln: 
        if value == 'y':
            value = '1'
        elif value == 'n':
            value = '0'
        else: 
            value = '1'

EDIT: There are 17 columns in this dataset, but there is another dataset I'm hoping to tackle which contains 56 columns.

republican  n   y   n.1 y.1 y.2 y.3 n.2 n.3 n.4 y.4 ?   y.5 y.6 y.7 n.5 y.8
0   republican  n   y   n   y   y   y   n   n   n   n   n   y   y   y   n   ?
1   democrat    ?   y   y   ?   y   y   n   n   n   n   y   n   y   y   n   n
2   democrat    n   y   y   n   ?   y   n   n   n   n   y   n   y   n   n   y
3   democrat    y   y   y   n   y   y   n   n   n   n   y   ?   y   y   y   y
4   democrat    n   y   y   n   y   y   n   n   n   n   n   n   y   y   y   y
7 Answers

All the solutions above are correct, but what you could also do is:

df["infants"] = df["infants"].replace("Y", 1).replace("N", 0).replace("?", 1) which now that I read more carefully is very similar to using replace with dict !

Related