KeyError:将标签添加到重新绘制时为6

时间:2019-06-28 10:24:26

标签: pandas matplotlib seaborn

我有一个包含以下列的数据框:“项目”,“小时”,“收入”,“费率”

我尝试用X轴上的“费率”和Y轴上的“收入”构建一个重新绘制图,并在我的重新绘制图上的点上添加项目名称标签。这是我的代码:

ax=sns.regplot(x = 'Revenue', y = 'Rate',data= df_hours_revenue, ci = None)
sns.set(rc={'figure.figsize':(20,10)})
# ax.set_xlabel('')
# ax.set_ylabel('Rate (£/hour)')
sns.set_context('poster')
plt.title("Rate vs. project revenue 2018-2019")

for line in range(0,df_hours_revenue.shape[0]):
     ax.text(df_hours_revenue.Revenue[line], df_hours_revenue.Rate[line], 
     df_hours_revenue.Project[line], horizontalalignment='left', 
     size='small', color='Black', weight='normal')

结果是添加了一些标签的图形,并且出现了我不理解的输出错误:

KeyError                                  Traceback (most recent call last)
<ipython-input-55-fdcfd6157523> in <module>
      9 
     10 for line in range(0,df_hours_revenue.shape[0]):
---> 11      ax.text(df_hours_revenue.Revenue[line], df_hours_revenue.Rate[line], 
     12      df_hours_revenue.Project[line], horizontalalignment='left',
     13      size='small', color='Black', weight='normal')

~/anaconda3/lib/python3.7/site-packages/pandas/core/series.py in __getitem__(self, key)
    866         key = com.apply_if_callable(key, self)
    867         try:
--> 868             result = self.index.get_value(self, key)
    869 
    870             if not is_scalar(result):

~/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_value(self, series, key)
   4373         try:
   4374             return self._engine.get_value(s, k,
-> 4375                                           tz=getattr(series.dtype, 'tz', None))
   4376         except KeyError as e1:
   4377             if len(self) > 0 and (self.holds_integer() or self.is_boolean()):

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 6

1 个答案:

答案 0 :(得分:0)

如果要按位置访问“系列”项目,则应使用.iloc,例如:

df_hours_revenue.Revenue.iloc[line]

了解更多here