Why am I getting the error "ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()" on my plot?

Why am I getting the error "ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()" on my plot?

我已经在这个问题上停留了很长一段时间,我不确定如何解决它 - 这是代码和它附带的错误:

data = data.sort_values(by=['Happiness Rank'])

plt.figure(figsize=(20,13))
sns.scatterplot(data=data, x='Happiness Score',y='Economy (GDP per Capita)', hue = 'Year')
plt.title('Life Satisfication vs GDP per Capita',fontsize=20)
plt.xlabel('Life Satisfication',fontsize=16)
plt.ylabel('GDP per Capita',fontsize=16)
for i in range(len(data)):
    plt.text(s=data.loc[i,'Country'], x=data.loc[i,'Happiness Score']+0.01,
             y=data.loc[i,'Economy (GDP per Capita)']+0.01, fontsize=10)
plt.show()

此代码打印出带点的散点图,但点旁边没有国家/地区名称,这就是错误所在:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-35-c451b5b6b763> in <module>
      5 plt.ylabel('GDP per Capita',fontsize=16)
      6 for i in range(len(data)):
----> 7     plt.text(s=(data.loc[i,'Country']), x=(data.loc[i,'Happiness Score']+0.01),
      8              y=(data.loc[i,'Economy (GDP per Capita)']+0.01), fontsize=10)
      9 plt.show()

~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/pyplot.py in text(x, y, s, fontdict, **kwargs)
   3007 @_copy_docstring_and_deprecators(Axes.text)
   3008 def text(x, y, s, fontdict=None, **kwargs):
-> 3009     return gca().text(x, y, s, fontdict=fontdict, **kwargs)
   3010 
   3011 

~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/axes/_axes.py in text(self, x, y, s, fontdict, **kwargs)
    763             **kwargs,
    764         }
--> 765         t = mtext.Text(x, y, text=s, **effective_kwargs)
    766         t.set_clip_path(self.patch)
    767         self._add_text(t)

~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/text.py in __init__(self, x, y, text, color, verticalalignment, horizontalalignment, multialignment, fontproperties, rotation, linespacing, rotation_mode, usetex, wrap, **kwargs)
    149         self._x, self._y = x, y
    150         self._text = ''
--> 151         self.set_text(text)
    152         self.set_color(color if color is not None else rcParams["text.color"])
    153         self.set_fontproperties(fontproperties)

~/opt/anaconda3/lib/python3.8/site-packages/matplotlib/text.py in set_text(self, s)
   1163         if s is None:
   1164             s = ''
-> 1165         if s != self._text:
   1166             self._text = str(s)
   1167             self.stale = True

~/opt/anaconda3/lib/python3.8/site-packages/pandas/core/generic.py in __nonzero__(self)
   1440     @final
   1441     def __nonzero__(self):
-> 1442         raise ValueError(
   1443             f"The truth value of a {type(self).__name__} is ambiguous. "
   1444             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

如果有人知道如何解决,我将不胜感激this/can解释为什么会发生这种情况,这样我以后就可以避免类似的事情发生。提前致谢!

你在“loc”遇到的麻烦。你为它使用循环,但在这种情况下你不能这样做。 Google“密谋”。在 Plotly 中绘图更容易。

您的代码看起来像您期望索引具有连续值,从 0.

开始

但很可能您的 DataFrame 的索引具有 重复 值。 在这种情况下,loc[i,…] 检索索引为 iall 行 并从他们 returns 特定列。 这种返回值的类型是 Series 而不是“单个”值。

避免这个问题的方法之一是遍历行, 例如使用 iterrows。那么你实际上可以忽略索引值 并仅检索当前行中感兴趣的列。

所以将循环更改为:

for _, row in data.iterrows():
    plt.text(s=row['Country'], x=row['Happiness Score']+0.01,
        y=row['Economy (GDP per Capita)']+0.01, fontsize=10)

需要上面代码中的“_”作为占位符来捕获索引 当前行的 row 实际上是一个 Series 持有 当前行。

然后行[…]从 当前行。