“系列的真值不明确”是什么意思?
What do you mean by "The truth value of a Series is ambiguous?
我已经进行了大约 2 周的 Python 编程。试图在论坛上搜索我标题中所述的错误,但我仍然不明白我的代码有什么问题。
ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
我想做什么:
Insert a defined function into my dictionary 这是确定
基于 DataFrame ['LocalCurrency'] 值的阈值级别。
如果我的 DataFrame ['Country'] 包含字典中的键(例如
Singapore), 运行 函数并将返回值放在新列中
称为 'Threshold level'.
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,就像这样,它对于大数据帧工作得更快,而且 - 它看起来更好:
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'])
这里是重写函数的方法及其用法[添加以更详细地解释应用函数的行为]:
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)
- Pandas不容易啊。我不是说你不应该使用它,如果你是
Python 才 2 周,但你会有很多关于
pandas 如果你刚刚开始。
- 不要在键上使用
i
进行迭代。通常 i
用于索引。你似乎
遍历国家列表。也许把它命名为国家。
- 您可能想要使用
applymap
或 apply
。
- 在 convertsgp 中尝试添加 else 以提高可读性。
- 你这行有问题
df.loc[(df['Country']== i, 'Threshold Level'] = mydict
[i](df['LocalCurrency'])
df.loc[
后不应该有 (
.
我已经进行了大约 2 周的 Python 编程。试图在论坛上搜索我标题中所述的错误,但我仍然不明白我的代码有什么问题。
ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
我想做什么:
Insert a defined function into my dictionary 这是确定 基于 DataFrame ['LocalCurrency'] 值的阈值级别。
如果我的 DataFrame ['Country'] 包含字典中的键(例如 Singapore), 运行 函数并将返回值放在新列中 称为 'Threshold level'.
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,就像这样,它对于大数据帧工作得更快,而且 - 它看起来更好:
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'])
这里是重写函数的方法及其用法[添加以更详细地解释应用函数的行为]:
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)
- Pandas不容易啊。我不是说你不应该使用它,如果你是 Python 才 2 周,但你会有很多关于 pandas 如果你刚刚开始。
- 不要在键上使用
i
进行迭代。通常i
用于索引。你似乎 遍历国家列表。也许把它命名为国家。 - 您可能想要使用
applymap
或apply
。 - 在 convertsgp 中尝试添加 else 以提高可读性。
- 你这行有问题
df.loc[(df['Country']== i, 'Threshold Level'] = mydict [i](df['LocalCurrency'])
df.loc[
后不应该有(
.