Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What am I doing wrong with this syntax of multiple if – else in apply pandas?

I am trying to execute this code:

data['lga_code'] = data.loc[:,'lga'].apply(lambda x: 'Rural' if x == endswith('Rural')
                                          ('Urban' if x == endswith('Urban')
                                           else 'other'))

But I get this error: SyntaxError: invalid syntax.

What is wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The data is a dataframe that it has 125 categories. I want to group them all into three, and that’s what I tried.

How can I solve that?

Thank you.

>Solution :

You forgot else. Also str.endswith() return True or False. You need to write x.endswith.

data.loc[:,'lga'].apply(lambda x: 'Rural' if x.endswith('Rural')
                        else ('Urban' if x.endswith('Urban')
                              else 'other'))

### You can write without  "loc" ###
data['lga'].apply(lambda x: 'Rural' if x.endswith('Rural')
                        else ('Urban' if x.endswith('Urban')
                              else 'other'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading