I'm trying to make a recursive try-except
function in order to deal with occasional errors. In pandas
, we can create quantiles for dataframes, however, it might happen that the borders of two or more quantiles coincide and, thus, there isn't a border actually. Sopandas
will throw an error. To circumvent this, you can just lower the number of quantiles and that's what I'm attempting to do here.
import pandas as pd
quantiled, dict_bins = recursive_lower_labels(model_quant = model_quant,
n_quantiles = n_quantiles,
reverse = reverse)
def recursive_lower_labels(model_quant,
n_quantiles,
reverse = False):
'''
Recursively lowers the number of labels until it works.
'''
if n_quantiles == 0: # base case
return 'Error: There are no Quantiles to be used.'
# Not very important...
# I'm using this to either use normal or reverse labels.
if reverse == False:
labels = range(1, n_quantiles + 1)
elif reverse == True:
labels = range(n_quantiles, 0, -1)
try:
qt, dc = pd.qcut(model_quant,
q = n_quantiles,
labels = labels,
retbins = True)
return qt, dc
except:
recursive_lower_labels(model_quant,
n_quantiles = n_quantiles - 1,
reverse = reverse)
The error I'm getting is (pointing to the function call up top):
cannot unpack non-iterable NoneType object
I suspect it's one of two mistakes I'm making:
- There is a problem with scoping somewhere. Maybe
n_quantiles
? It doesn't seem likely, from my unexperienced debugging. - There is an issue with respect to placing a return before the function recursive call inside the
except
statement. I've tried a lot of combinations here, even with an extraelse
at the end and it didn't work either.
By the way, if not recursive, this does work.
EDIT:
My question was marked as a duplicate and this edit is to address that evaluation. Firstly, it was marked as a duplicate of a question that was also marked as such, which is strange, but not that relevant. The important and useful concept that differs those questions from mine is that they both had functions that, although recursive, did not necessarily return something all the time, while mine did return something always and, thus, made it seem that the return on the recursion was not necessary — which turns out to not be true.