Click here to Skip to main content
15,845,589 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a function that divides the values of a numeric column into the specified number of bins/categories, based on the ranges they fall into. These categories are numbered from 0 to the limit specified. And the column values are replaced with their category number. I implemented the binning function which worked fine. I now want to display the ranges the column values get divided into. Following is what I tried:

What I have tried:

Binning function code:

def binning_fun_cut(df, binning_inputs):
    col_name = binning_inputs[0]
    num_of_bins = binning_inputs[1]
    range_table = pd.value_counts(df[col_name], bins=num_of_bins, sort=False)
    belief = range_table.to_dict()
    df[col_name] = pd.cut(df[col_name], bins=num_of_bins, labels=range(num_of_bins)).astype(str)
    result_dict = df.to_dict(orient='records')         
    for record in result_dict:                         
        for key, value in record.items():              
            if isinstance(value, float):               
                record[key] = str(value) 
    return {'Range of binned': belief, 'dataf': result_dict}   

ValueError: [TypeError("'pandas._libs.interval.Interval' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]

Expected output (for the variable 'belief'):

(1.004, 1.01]      7
(1.01, 1.015]    159
(1.015, 1.02]    106
(1.02, 1.025]     81

How do I get the expected output?
Updated 11-Mar-23 7:38am

1 solution

I don't do Python, but the error seems to be telling you that you're trying to iterate (for...) over something that is not a collection, but is a single object.
Share this answer
Apoorva 2022 11-Mar-23 14:23pm    
I did debugging & the code works when I print the result. I'm trying to return the result as a dictionary using Fast API & that is when I get the specified error.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900