I know that there are some answers for this question, but unfortunately I couldn't make any of them work. I have a loop that plots certain time intervals as subplots, but some time intervals due the cleaning of the data get deleted. Now I would like to skip that time interval and just continue normally.
I tried to do that with:
except ValueError:
continue
But I get invalid syntax error.
Original code:
dimenzion = math.ceil(np.sqrt(len(lista_start)))
fig, axes = plt.subplots(nrows=dimenzion,ncols=dimenzion, figsize=(25, 21), sharex=False)
sns.despine(left= True)
fig.suptitle('Clean data', y =1.01, fontsize = 21)
date = 0
i = 0
j = 0
while date <= len(lista_end)-1:
df_date = df_clean[(df_clean['Time'] > pd.Timestamp(lista_start.loc[date][0])) &
(df_clean['Time'] < pd.Timestamp(lista_end.loc[date][0]))]
df_date = df_date.reset_index(drop = True)
start = datetime.datetime.strftime(lista_start.loc[date][0], '%d.%m.%y')
end = datetime.datetime.strftime(lista_end.loc[date][0], '%d.%m.%y')
df_date.plot('Time', 'Mids Ply Fines B', figsize = (25,7), ax = axes[i,j], subplots = True)
axes[i,j].set_title('{} - {}'.format(start, end))
axes[i,j].get_xaxis().set_visible(False)
j = j+1
date = date + 1
if j > dimenzion - 1:
j = 0
i = i+1
except ValueError:
continue
plt.setp(axes, yticks=[])
plt.tight_layout()
In Python, the except needs a starting try - you need to tell it which code 'section' might generate the error you want to capture :
I don't know what line is generating the ValueError - but this should be sufficient:
try :
df_date = df_clean[(df_clean['Time'] > pd.Timestamp(lista_start.loc[date][0])) &
(df_clean['Time'] < pd.Timestamp(lista_end.loc[date][0]))]
df_date = df_date.reset_index(drop = True)
start = datetime.datetime.strftime(lista_start.loc[date][0], '%d.%m.%y')
end = datetime.datetime.strftime(lista_end.loc[date][0], '%d.%m.%y')
df_date.plot('Time', 'Mids Ply Fines B', figsize = (25,7), ax = axes[i,j], subplots = True)
axes[i,j].set_title('{} - {}'.format(start, end))
axes[i,j].get_xaxis().set_visible(False)
j = j+1
date = date + 1
if j > dimenzion - 1:
j = 0
i = i+1
except ValueError:
continue
Notice who the whole code 'section' between the try and the except are indented - that makes it clear that any ValueError exception generated anywhere in that section will result in the continue being created.