实际错误 - 你看 - 被提出,因为你试图使用系列作为字典的键。为了避免它 - 你必须从这个系列中获得一个元素。
您的代码中还有很多其他问题。
你可以这样解决:
import pandas as pd
data = {
'Threshold Level':[0, 0, 0, 0, 0],
'Country':['Itally', 'Singapore', 'Ukraine', 'USA', 'England'],
'LocalCurrency': [100, 2000, 392, 3,23 ]
}
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
def convertsgp(x):
if x <= 99:
y = 'Nominal'
elif x <= 349:
y = 'Threshold 1'
elif x <= 1399:
y = 'Threshold 2'
elif x > 1400:
y = 'Threshold 3'
return y
mydict = {'Singapore': convertsgp }
for i in list(mydict.keys()):
local_currency = df.loc[df['Country']== i]['LocalCurrency']
df.loc[df['Country']== i, 'Threshold Level'] = mydict[i](local_currency[1])
另外 - 如果您没有在 dict 中包含所有国家/地区 - 更好的方法是使用 apply,像这样,它对于大 DataFrame 的工作速度会更快,而且 - 它看起来更好:
import pandas as pd
data = {
'ThresholdLevel':[0, 0, 0, 0, 0],
'Country':['Itally', 'Singapore', 'Ukraine', 'USA', 'England'],
'LocalCurrency': [100, 2000, 392, 3,23 ]
}
# Convert the dictionary into DataFrame
df = pd.DataFrame(data)
def convertsgp(x):
if x <= 99:
y = 'Nominal'
elif x <= 349:
y = 'Threshold 1'
elif x <= 1399:
y = 'Threshold 2'
elif x > 1400:
y = 'Threshold 3'
return y
mydict = {'Singapore': convertsgp}
def apply_corresponding_function(country, value_to_apply_on):
try: # lets try to get function we need to apply
function_to_apply = mydict[country] # if there's no such key in dictionaries it'll raise an error
return function_to_apply(value_to_apply_on)
except: # this will be executed, if operations after 'try' raised any errors:
return False
df['ThresholdLevel'] = df.apply(lambda x: apply_corresponding_function(x['Country'], x['LocalCurrency']), axis =1)
另外,如果您的所有国家/地区都在 dict 中,您可以使用:
df['Threshold Level'] = mydict[df['Country'].any()](df['LocalCurrency'])
以下是如何重写函数及其用法[添加以更详细地解释应用函数的行为]:
def function_to_be_applied(dataframe_row):
country = dataframe_row['Country']
value_to_apply_on = dataframe_row['LocalCurrency']
try: # lets try to get function we need to apply
function_to_apply = mydict[country] # if there's no such key in dictionaries it'll raise an error
return function_to_apply(value_to_apply_on)
except: # this will be executed, if operations after 'try' raised any errors:
return False
df['ThresholdLevel'] = df.apply(function_to_be_applied, axis = 1)