我正在做一个简单的定义,以根据一些间隔返回颜色列表。不幸的是,我一直收到以下错误:
ValueError:系列的真值不明确。使用a.empty,a.bool(),a.item(),a.any()或a.all()。
我看过以下有关stackoverflow的讨论,但只有失败的尝试才能使它起作用。
Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()
这是我的代码:
y = 5
std = pd.Series([1,1,1,1])
values = pd.Series([2, 4, 6, 8])
colors = []
def colorbybar():
for i in values:
if y < (values - (2*std)):
colors[i] = 'darkblue'
elif y < (values - std):
colors[i] = 'blue'
elif y < values:
colors[i] = 'white'
elif y < (values + std):
colors[i] = 'red'
elif y < (values + (2*std)):
colors[i] = 'darkred'
return colors
colorbybar()
[执行y < (values - std)
时将返回pd.Series
>>> y < (values - std)
0 False
1 False
2 False
3 True
dtype: bool
但是这里您需要标量bool
作为条件,如错误使用中所述
ValueError:系列的真值不明确。使用a.empty,a.bool(),a.item(),a.any()或a.all()。
like
>>> (y < (values - std)).all()
False
>>> # or
>>> (y < (values - std)).any()
True
因此您的职能将是
def colorbybar():
for i in values:
if (y < (values - (2*std))).all():
colors[i] = 'darkblue'
elif (y < (values - std)).all():
colors[i] = 'blue'
elif (y < values).all():
colors[i] = 'white'
elif (y < (values + std)).all():
colors[i] = 'red'
elif (y < (values + (2*std))).all():
colors[i] = 'darkred'
return colors
我想您还没有完全了解Python的for
的工作原理。
[在循环中,您试图对values
,即整个系列,进行Dishin notes算术运算。您可能想对values
的items进行操作。即i
:
for i in values:
if y < (i - (2*std)):
# and so on
此外,您正在尝试将i
用作列表colors
的索引(键)。这不可能。您可以使用字典以这种方式设置键,但这可能不是您想要的(请参见archived version of the original question:
我正在尝试创建一个基于值是否介于某个间隔之间来返回颜色列表的定义。因此,如果y为-1,则应返回列表[深蓝色,深蓝色,深蓝色,深蓝色],但是如果y为11,则应返回列表[深红色,深红色,深红色,深红色]。
代替错误的语法colors[i]
,您可以使用colors.append('darkblue')
等。>