Я пытаюсь построить довольно простой график в пандах, используя мой первый столбец под названием «Дата» в качестве оси x, но я наткнулся на ключевую ошибку, и я в растерянности, где проблема.Я использую Python 2 в дистрибутиве Anaconda.
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'