Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round and apply min and max to all values in Pandas Dataframe

I'm struggling on how to clean-up a dataframe. What I would like to do is truncate all items (i.e. floor()), and for any items below or over a min/max, replace with the min or max as applicable. E.g. for this dataframe:

enter image description here

If my min and max are 1 and 5 respectively, 1.2 would truncate to 1, 9.6 would map to 5, -1.2 would map to 1, and 3.5 would truncate to 3:

enter image description here

Other than brute-force iteration using iterrows(), I haven't been able to get this to work. Lots of stuff on finding the min and max, but not on applying a min and max.

May I please ask if anyone has some suggestions? Thank you.

like image 461
tendim Avatar asked Oct 23 '25 04:10

tendim


1 Answers

You can use applymap, such as:

from numpy import floor

MAX, MIN = 5, 1

df = df.applymap(lambda val: MAX if val > MAX else int(floor(val)) if val > MIN else MIN)
like image 162
Ralubrusto Avatar answered Oct 25 '25 18:10

Ralubrusto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!