[英]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 'in ' 需要字符串作为左操作数,而不是列表
I recommend you see When should I want to use apply
.我建议您查看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:因此,更改功能africa
导致:
def africa(x):
if x in africalist:
return 'African region'
else:
return 'Not African region'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.