vendredi 26 mars 2021

How can I make multiple if statement in the same line? Python

In the following DataFrame of pandas there is a column called "grupo_edad", the values of the column are:

De 0 a 4 años, De 5 a 9 años, De 10 a 14 años, De 15 a 19 años, De 20 a 24 años,...,De 85 a 89 años, 90 y más años.

I want to create a new column with a condition, where the two values: "De 0 a 4 años" and "De 5 a 9 años" take the same value, for example: 0-9. Analogously for the rest.

The problems come when trying to make the if statement in the same code line. I have done this:

df['nueva_columna']=df['grupo_edad'].apply(lambda x: 
                                 "0-9" if (x=="De 0 a 4 años" or x=="De 5 a 9 años") else 
                                 "10-19" if (x=="De 10 a 14 años" or x=="De 15 a 19 años") else
                                 "20-29" if (x=="De 20 a 24 años" or x=="De 25 a 29 años") else
                                 "30-39" if (x=="De 30 a 34 años" or x=="De 35 a 39 años") else                              
                                 "40-49" if (x=="De 40 a 44 años" or x=="De 45 a 49 años") else                              
                                 "50-59" if (x=="De 50 a 54 años" or x=="De 55 a 59 años") else
                                 "60-69" if (x=="De 60 a 64 años" or x=="De 65 a 69 años") else
                                 "70-79" if (x=="De 70 a 74 años" or x=="De 75 a 79 años") else "80+")

But it is not working properly (see image), all of them are working but there are problems with: "10-19", "70-79" and "80+". So... how am I understanding wrongly the if statement ? Is weird there are some that work perfectly

Thank you in advance for the help!

Aucun commentaire:

Enregistrer un commentaire