python - “系列的真实值(value)不明确”是什么意思?

标签 python ambiguous

我已经开始 Python 编程大约 2 周了。尝试在论坛上搜索我的标题中所述的错误,但我仍然不明白我的代码有什么问题。

ValueError:系列的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。

我正在尝试做的事情:

  • 将定义的函数插入我的字典中,以确定 基于 DataFrame ['LocalCurrency'] 值的阈值级别。

  • 如果我的 DataFrame ['Country'] 由字典中的键组成(例如 新加坡),运行该函数并将返回值放入新列中 称为“阈值水平”。

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()):
    df.loc[(df['Country']== i, 'Threshold Level'] = mydict [i](df['LocalCurrency'])

非常感谢您的意见,谢谢!

最佳答案

实际错误 - 你看 - 被提出,因为你试图使用系列作为字典的键。为了避免它 - 你必须从这个系列中获取一个元素。 您的代码中还存在很多其他问题。 你可以这样解决:

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)

此外,如果您在字典中包含所有国家/地区,您可以使用:

df['Threshold Level'] = mydict[df['Country'].any()](df['LocalCurrency'])

以下是重写函数及其用法的方法[添加以更详细地解释 apply 函数的行为]:

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)

关于python - “系列的真实值(value)不明确”是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59486763/

相关文章:

python - 按值对字典进行排序并仅打印键

python - 加载模块时出错./exp.so undefined symbol

python - 根据每个主索引的最后一个二级索引选择所有行

c++ - 对重载函数的模糊调用 - log 与 ptrdiff_t

reference - swift3 中的模糊引用

swift - 模糊地使用backgroundColor swift

c++11 - 确定 std::bind() 结果的数量和其他特征的标准方法?

python - 在 python 中显示输入提示

python - Matplotlib x 轴标签对齐关闭

C++ typedef继承二义性问题