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

Question:

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?

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

Asked By: DatBigD

||

Answers:

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'))
Answered By: I'mahdi

When I encounter problems like this, I break up my code into smaller pieces. In this case, I recommend creating a function instead of using a lambda:

def get_category(x):
    if x == endswith('Rural')
        return 'Rural'
    if x == endswith('Urban')
        return urban
    return 'other'

This is much easier to read than trying to do everything in a single line. Also, python can more easily point out where any problems are because the code is broken across multiple lines.

Now you will find that endswith() isn’t defined. Most likely you want to call it on the string x:

def get_category(x):
    if x.endswith('Rural')
        return 'Rural'
    if x.endswith('Urban')
        return urban
    return 'other'

Now you can apply this function to your dataframe:

data['lga_code'] = data.loc[:,'lga'].apply(get_category)
Answered By: Code-Apprentice
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.