Skip to content
Advertisement

In Pandas, how do I convert a number column to discrete values quickly?

I have a dataframe with an Integer column, which I need to convert to discrete value bands, I am currently doing this using apply with my own function, as seen bellow, however this is rather slow, is there any way to quickly do this?

JavaScript

Caller function here:

JavaScript

My data look like this:

JavaScript

Advertisement

Answer

IIUC and given the mix of types of conditions I’d recommend np.select:

JavaScript

By comparing against pct_change instead of diff the conditions can be simplified:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement