关键错误:从索引列“日期”绘制一条线时为“日期”

时间:2018-12-07 11:02:36

标签: pandas plot line timeline

我正在尝试使用我的第一列“日期”作为x轴在熊猫中绘制一个相当简单的图形,但是我偶然发现了一个“关键错误”,而我不知所措。我正在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()

这是我的数据帧的屏幕截图

住宅贷款数据:

enter image description here

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

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'

1 个答案:

答案 0 :(得分:1)

来自pandas docs on plot()

  

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

由此您可以推断出数据框索引是x轴的默认值。因此,您无需将索引名作为plot()传递到plot(x=...)中;您只需删除该参数并使用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'来完成。