Search code examples
pythonpandascut

Pandas cut with user-defined bins


I am working in Python and using the cut functionality in Pandas. I would like to have the bins in my pd.cut to be based on user-defined comma separated integers, with predefined top and bottom bounds. In other words, I would like to predefine bins as [0, 100000] and then append user defined integers to this set of numbers. If the user entered 5, 100, 5000 then bins would become [0, 5, 100, 5000, 100000] and would then work with pd.cut(df['Quantity'], bins.

I have tried a number of solutions with no avail up to this point - any input would be greatly appreciated!


Solution

  • Something like this?

    bin_range = [0, 100000]
    bin_input = raw_input("Enter bins as comma seperated list")
    bin_input_parsed = [int(x.strip()) for x in bin_input.split(',')]
    
    bins = [bin_range[0]] + bin_input_parsed + [bin_range[1]]
    pd.cut(df['Quantity'], bins)