我有一个国家/地区名称的数据框,我想添加一个列,表明它是否属于穆斯林禁令的一部分。所以,理想情况下,我希望如此:
Country Name Ban
Indonesia non_muslim_ban
Iran, Islamic Rep. muslim_ban
Iraq non_muslim_ban
Ireland non_muslim_ban
Libya muslim_ban
Liechtenstein non_muslim_ban
Somalia muslim_ban
South Africa non_muslim_ban
Sudan muslim_ban
Syrian Arab Republic muslim_ban
West Bank and Gaza non_muslim_ban
Yemen, Rep. muslim_ban
Zambia non_muslim_ban
Zimbabwe non_muslim_ban
我尝试了这个功能并收到错误:
def muslim_ban(Country_Name):
if df['Country Name'] in ['Iran', 'Libya', 'Somalia', 'Sudan', 'Syria', 'Yemen']:
return 'muslim_ban'
elif df['Country Name'] not in ['Iran', 'Libya', 'Somalia', 'Sudan', 'Syria', 'Yemen']:
return 'non_muslim_ban'
`df['muslim_ban'] = df['Country Name'].apply(muslim_ban)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
有人可以协助吗?
更新以包含修订后的代码
答案 0 :(得分:1)
您的代码存在一些问题。
首先,在muslim_ban的函数定义中有空格分隔变量名。因此,将"国家/地区名称" 替换为" Country_Name"
其次,您可以在列表中添加多条字符串if条件,然后使用in
和not in
运算符检查是否存在。
def muslim_ban(Country_Name):
if Country_Name in ['Iran', 'Libya', 'Somalia', 'Sudan', 'Syria', 'Yemen']:
return 'muslim_ban'
elif Country_Name not in ['Iran', 'Libya', 'Somalia', 'Sudan', 'Syria', 'Yemen']:
return 'non_muslim_ban'
df['muslim_ban'] = df['Country_Name'].apply(muslim_ban)
答案 1 :(得分:1)
这里有一些可能会有帮助的事情。
希望这有帮助!
答案 2 :(得分:0)
您确定可以将功能参数拆分为:
Country Name
?也许这是你的语法错误。顺便说一下,语法错误应该显示遇到错误的行。
答案 3 :(得分:0)
ban_muslim = ["Yemen" ,"Syrian Arab Republic" , "Sudan" , "Somalia", "Libya" , "Iran" ]
ban_non_muslim = ["Indonesia","Iraq","Ireland","Liechtenstein","South Africa","Gaza" ,"Zambia","Zimbabwe"]
country_name = str(input("please enter your country name: "))
if country_name in ban_muslim :
print ("you entered banned muslim country ",country_name)
elif country_name in ban_non_muslim:
print("you entered banned muslim country " ,country_name)
else:
print (" you enterd unavailable name")