0

I am trying to create a new variable called "region" based on the names of countries in Africa in another variable. I have a list of all the African countries (two shown here as an example) but I have am having encountering errors.



def africa(x):
  if africalist in x:
    return 'African region'
  else:
    return 'Not African region'


df['region'] = ''

df.region= df.countries.apply(africa)

I'm getting :

'in ' requires string as left operand, not list

Sanch
  • 367
  • 2
  • 11

2 Answers2

2

I recommend you see When should I want to use apply.

You could use:

df['region'] = df['countries'].isin(africalist).map({True:'African region',
                                                     False:'Not African region'})

or

df['region'] = np.where(df['countries'].isin(africalist),
                        'African region',
                        'Not African region')
ansev
  • 30,322
  • 5
  • 17
  • 31
0

Your condition is wrong.

The correct manner is

if element in list_of_elements:

So, changing the function africa results in:

def africa(x):
  if x in africalist:
    return 'African region'
  else:
    return 'Not African region'