简体   繁体   中英

Create a new column value based on another column content from a list

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

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM