当我在进行绘图测试时,每次绘制数据档案中的图形都会遇到相同的错误。我的一位同事在她的电脑上运行了相同的程序,而且运行正常,因此我不确定是否需要导入额外的库或进行更新。以下是导致错误的那行代码:
def sub_plot_weekday(df):
fechas = []
for i in range(len(df.index)):
date = str(df.index[i])[0:7]
if date not in fechas:
fechas.append(date)
#print(fechas)
n_subplots = len(fechas)
n_col = 2
n_rows = math.ceil(n_subplots/n_col)
fig = plt.figure(figsize = (20, 12))
for d in range(len(fechas)):
#Guardamos en una var el df filtrado x fecha
filter_df = df[fechas[d]].copy()
#Guardamos en una lista el nombre de cada día para cada "Fecha" y la ponemos en una columna
#print(filter_df)
dates = filter_df.index
name_m = dates[0].strftime("%B")
list_weekdays = [dates[i].date().strftime("%A") for i in range(len(dates))]
filter_df['weekday'] = list_weekdays
# Creamos un df agrupando por día de semana contando eventos
grouped_by_weekday = pd.DataFrame(filter_df[['EVENT', 'weekday']][filter_df['EVENT'] != 0].groupby('weekday').count())
days_index = grouped_by_weekday.index.tolist()
days_values = grouped_by_weekday.EVENT.tolist()
order_day, order_val = reorder_lists(days_index, days_values)
#Añadimos subplot
plt.subplot(n_rows, n_col, d+1)
plt.title('Number of Operations per Weekday (' + name_m + ' ' +fechas[d][:4] + ')',fontsize= 17)
plt.bar(order_day, order_val, color = 'purple') #(0.5,0.1,0.5,0.6)
#plt.xticks(order_day, rotation=45)
for i, val in enumerate(order_val):
plt.text(i, val, int(val), horizontalalignment='center', verticalalignment='bottom', fontdict={'fontweight':500, 'size':12})
plt.ylim(0,26)
plt.xticks(order_day, rotation=0)
fig.tight_layout(pad=2.0)
plt.show()
sub_plot_weekday(dt1)
</code></pre>
<pre><code>KeyError Traceback (most recent call last)
File ~\AppData\Local\anaconda3\envs\myenv\lib\site-packages\pandas\core\indexes\base.py:3790, in Index.get_loc(self, key)
3789 try:
-> 3790 return self._engine.get_loc(casted_key)
3791 except KeyError as err:
File index.pyx:152, in pandas._libs.index.IndexEngine.get_loc()
File index.pyx:181, in pandas._libs.index.IndexEngine.get_loc()
File pandas\_libs\hashtable_class_helper.pxi:7080, in pandas._libs.hashtable.PyObjectHashTable.get_item()
File pandas\_libs\hashtable_class_helper.pxi:7088, in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: '2019-10'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
Cell In[11], line 1
----> 1 sub_plot_weekday(dt1)
Cell In[10], line 25, in sub_plot_weekday(df)
21 #Recoremos cada "fecha" recogida
23 for d in range(len(fechas)):
24 #Guardamos en una var el df filtrado x fecha
---> 25 filter_df = df[fechas[d]].copy()
26 #Guardamos en una lista el nombre de cada día para cada "Fecha" y la ponemos en una columna
27 #print(filter_df)
28 dates = filter_df.index
File ~\AppData\Local\anaconda3\envs\myenv\lib\site-packages\pandas\core\frame.py:3896, in DataFrame.__getitem__(self, key)
3894 if self.columns.nlevels > 1:
3895 return self._getitem_multilevel(key)
-> 3896 indexer = self.columns.get_loc(key)
3897 if is_integer(indexer):
3898 indexer = [indexer]
File ~\AppData\Local\anaconda3\envs\myenv\lib\site-packages\pandas\core\indexes\base.py:3797, in Index.get_loc(self, key)
3792 if isinstance(casted_key, slice) or (
3793 isinstance(casted_key, abc.Iterable)
3794 and any(isinstance(x, slice) for x in casted_key)
3795 ):
3796 raise InvalidIndexError(key)
-> 3797 raise KeyError(key) from err
3798 except TypeError:
3799 # If we have a listlike key, _check_indexing_error will raise
3800 # InvalidIndexError. Otherwise we fall through and re-raise
3801 # the TypeError.
3802 self._check_indexing_error(key)
KeyError: '2019-10'
<Figure size 2000x1200 with 0 Axes>