Tie_24
Tie_24

Reputation: 647

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 nearest 5 in a new B column, using numpy if possible.

Output should be:

        A        B
0  503.36   505.00
1  509.80   510.00
2  612.31   610.00
3  614.29   615.00

Upvotes: 7

Views: 6218

Answers (3)

BENY
BENY

Reputation: 323386

Since you mention numpy

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

Upvotes: 10

piRSquared
piRSquared

Reputation: 294536

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

Upvotes: 3

Scott Boston
Scott Boston

Reputation: 153550

You can use:

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

Or as @piRSquared states:

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

Output:

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

Upvotes: 4

Related Questions