Round to Nearest 5 with numpy

df
        A
0  503.36
1  509.80
2  612.31
3  614.29

I want to round to the nearest 5 in a new column B using numpy if possible.

The conclusion should be:

        A        B
0  503.36   505.00
1  509.80   510.00
2  612.31   610.00
3  614.29   615.00
+4
source share
3 answers

Since you mention numpy

np.around(df.A.values/5, decimals=0)*5
Out[31]: array([505., 510., 610., 615.])
+6
source

You can use:

df['B'] = df.div(5).round(0) * 5

Or as @piRSquared state:

df['B'] = df['A'].mul(2).round(-1).div(2)

Conclusion:

        A      B
0  503.36  505.0
1  509.80  510.0
2  612.31  610.0
3  614.29  615.0
+4
source
df.assign(B=df.mul(2).round(-1).div(2))

        A      B
0  503.36  505.0
1  509.80  510.0
2  612.31  610.0
3  614.29  615.0
+3
source

Source: https://habr.com/ru/post/1694867/


All Articles