【问题标题】:Key Error: 'Date' when plotting a line from index column 'Date'关键错误:从索引列“日期”绘制一条线时出现“日期”
【发布时间】:2018-12-07 21:24:00
【问题描述】:

我正在尝试使用我的第一列“日期”作为 x 轴在 pandas 中绘制一个相当简单的图表,但我偶然发现了一个关键错误,我不知道问题出在哪里。我在 Anaconda 发行版下使用 Python 2。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

#read file
df=pd.read_csv("C:\Users\sophi\Desktop\ResidentialLoans.csv",index_col='Date')

#extracting the individual components
index=df.index
columns=df.columns
values=df.values

# plot the graph
ax=plt.gca()
df.plot(x='Date', y='LTV < = 75%', kind="line", ax=ax)
df.plot(x='Date', y='LTV Over 75 < = 90%', kind="line", ax=ax, color="red")
plt.show()

这是我的数据框截图ю

住宅贷款数据:

我收到以下错误消息,但没有绘制任何内容:

KeyErrorTraceback (most recent call last)
<ipython-input-125-52b0be68296d> in <module>()
      1 # plot the graph
      2 ax=plt.gca()
----> 3 df.plot(x='Date', y='LTV < = 75%', kind="line", ax=ax)
      4 df.plot(x='Date', y='LTV Over 75 < = 90%', kind="line", ax=ax, color="red")
      5 plt.show()

C:\Users\sophi\Anaconda2\lib\site-packages\pandas\plotting\_core.pyc in __call__(self, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds)
   2939                           fontsize=fontsize, colormap=colormap, table=table,
   2940                           yerr=yerr, xerr=xerr, secondary_y=secondary_y,
-> 2941                           sort_columns=sort_columns, **kwds)
   2942     __call__.__doc__ = plot_frame.__doc__
   2943 

C:\Users\sophi\Anaconda2\lib\site-packages\pandas\plotting\_core.pyc in plot_frame(data, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwds)
   1975                  yerr=yerr, xerr=xerr,
   1976                  secondary_y=secondary_y, sort_columns=sort_columns,
-> 1977                  **kwds)
   1978 
   1979 

C:\Users\sophi\Anaconda2\lib\site-packages\pandas\plotting\_core.pyc in _plot(data, x, y, subplots, ax, kind, **kwds)
   1764                 if is_integer(x) and not data.columns.holds_integer():
   1765                     x = data_cols[x]
-> 1766                 elif not isinstance(data[x], ABCSeries):
   1767                     raise ValueError("x must be a label or position")
   1768                 data = data.set_index(x)

C:\Users\sophi\Anaconda2\lib\site-packages\pandas\core\frame.pyc in __getitem__(self, key)
   2683             return self._getitem_multilevel(key)
   2684         else:
-> 2685             return self._getitem_column(key)
   2686 
   2687     def _getitem_column(self, key):

C:\Users\sophi\Anaconda2\lib\site-packages\pandas\core\frame.pyc in _getitem_column(self, key)
   2690         # get column
   2691         if self.columns.is_unique:
-> 2692             return self._get_item_cache(key)
   2693 
   2694         # duplicate columns & possible reduce dimensionality

C:\Users\sophi\Anaconda2\lib\site-packages\pandas\core\generic.pyc in _get_item_cache(self, item)
   2484         res = cache.get(item)
   2485         if res is None:
-> 2486             values = self._data.get(item)
   2487             res = self._box_item_values(item, values)
   2488             cache[item] = res

C:\Users\sophi\Anaconda2\lib\site-packages\pandas\core\internals.pyc in get(self, item, fastpath)
   4113 
   4114             if not isna(item):
-> 4115                 loc = self.items.get_loc(item)
   4116             else:
   4117                 indexer = np.arange(len(self.items))[isna(self.items)]

C:\Users\sophi\Anaconda2\lib\site-packages\pandas\core\indexes\base.pyc in get_loc(self, key, method, tolerance)
   3063                 return self._engine.get_loc(key)
   3064             except KeyError:
-> 3065                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   3066 
   3067         indexer = self.get_indexer([key], method=method, tolerance=tolerance)

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

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

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

KeyError: 'Date'

【问题讨论】:

  • 一旦将索引设置为Date,它就不再是一个命名列并且不能作为x 的参数传递。我相信如果你想要的值作为x 已经是索引,你可以省略它。

标签: pandas plot line timeline


【解决方案1】:

来自pandas docs on plot()

x :标签或位置,默认无
...
use_index :布尔值,默认为 True
使用索引作为 x 轴的刻度

由此您可以推断数据框索引是 x 轴的默认值。所以你不需要将索引名称作为plot(x=...) 传递给plot();您可以删除该参数并使用 plot(y='column name', ...) 调用它,因为您要使用的列是索引。

您收到错误的原因是,一旦您将一列设置为索引,它就不再是您的数据框中可以按名称访问的列。

具体来说,这意味着您根本无法使用df.__getitem__(index_name)df[index_name]——如果您尝试访问df['Date'],您将看到相同的错误。如果您查看df.columns,您会发现Date 不在其中,如果您使用df.iloc[] 按位置访问列,您会注意到索引0 映射到'Single: less than 2.50' 列。

请注意,要将索引“恢复”为普通列,您可以随时使用df.reset_index()。这只会按当前顺序对您的索引进行编号,并将索引设置为常规列,您可以再次按名称引用它。这是df.set_index() 函数的逆运算,您的导入通过设置index_col='Date' 来执行此操作。

【讨论】:

  • 亚历山大,非常感谢!我删除了索引名称作为 x 轴名称的显式传递,这解决了问题。也许我错误地遵循了关于索引问题的另一个帖子建议。
  • 我自己也必须努力学习这一点!不用担心!我不得不去寻找它在文档中明确说明这一点的地方——它没有,只需从参数的描述中推断出来:/
猜你喜欢
  • 2019-02-11
  • 2020-08-04
  • 1970-01-01
  • 1970-01-01
  • 2018-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-15
相关资源
最近更新 更多