Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding down numbers to the nearest even number

Tags:

python

pandas

I have a dataframe with a column of numbers that look like this:

data = [291.79, 499.31, 810.93, 1164.25]
df = pd.DataFrame(data, columns=['Onset'])

Is there an elegant way to round down the odd numbers to the nearest even number? The even numbers should be rounded to the nearest even integer. This should be the output:

data = [290, 498, 810, 1164]
df = pd.DataFrame(data, columns=['Onset'])

Thank you!

like image 829
jo_ Avatar asked Feb 03 '26 04:02

jo_


2 Answers

I'd use modulo operator:

df['Onset_new'] = (i:=df['Onset'].astype(int)) - i % 2
print(df)

Prints:

     Onset  Onset_new
0   291.79        290
1   499.31        498
2   810.93        810
3  1164.25       1164
like image 145
Andrej Kesely Avatar answered Feb 05 '26 16:02

Andrej Kesely


df.apply(lambda x:np.floor(x)-np.floor(x)%2)
like image 44
Himanshu Panwar Avatar answered Feb 05 '26 16:02

Himanshu Panwar



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!