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?
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'))