Home > Back-end >  In a dataframe with both positive & negative numbers, how to round positive numbers up and round neg
In a dataframe with both positive & negative numbers, how to round positive numbers up and round neg

Time:06-22

With a dataframe as such:

data={'A1':[-7.22,-9.432,-0.00111,0.233,17,23,34],
      'A2':[-23,-7.2455,-0.00222,0.54,1.345,19,21]}
kk=pd.DataFrame(data)
         A1        A2
0  -7.22000 -23.00000
1  -9.43200  -7.24550
2  -0.00111  -0.00222
3   0.23300   0.54000
4  17.00000   1.34500
5  23.00000  19.00000
6  34.00000  21.00000

I want to round positive numbers up but negative numbers down (in multiples of 5), for example:

  • 21 will become 25 instead of 20
  • -7 will become -10 instead of -5

Tried using this method only to receive an error

def roundupdown5(x):
   if x>=0:
       return np.ceil(x/5)*5
   else:
       return np.floor(x/5)*5

kk[['A1','A2']].apply(lambda x: roundupdown5(x))

Thank you :)

CodePudding user response:

You can use applymap() instead of apply()

kk.applymap(roundupdown5)

results in

      A1    A2
0   -10.0   -25.0
1   -10.0   -10.0
2   -5.0    -5.0
3   5.0 5.0
4   20.0    5.0
5   25.0    20.0
6   35.0    25.0

CodePudding user response:

You can use dict and list comprehension to apply the roundupdown5() function to all the values of data before building the DataFrame:

import pandas as pd
import numpy as np

data={'A1':[-7.22,-9.432,-0.00111,0.233,17,23,34],'A2':[-23,-7.2455,-0.00222,0.54,1.345,19,21]}
kk=pd.DataFrame(data)


def roundupdown5(x):
    if x>=0:
        return np.ceil(x/5)*5
    else:
        return np.floor(x/5)*5

data = {k:[roundupdown5(i) for i in v] for k, v in data.items()}
kk=pd.DataFrame(data)
print(data, kk)

Output:

{'A1': [-10.0, -10.0, -5.0, 5.0, 20.0, 25.0, 35.0], 'A2': [-25.0, -10.0, -5.0, 5.0, 5.0, 20.0, 25.0]}      A1    A2
0 -10.0 -25.0
1 -10.0 -10.0
2  -5.0  -5.0
3   5.0   5.0
4  20.0   5.0
5  25.0  20.0
6  35.0  25.0

CodePudding user response:

You can use numpy.ceil on the absolute values and bring back the sign with numpy.sign, then you benefit from vectorial speed:

np.ceil(abs(kk)/5)*5*np.sign(kk)

output:

     A1    A2
0 -10.0 -25.0
1 -10.0 -10.0
2  -5.0  -5.0
3   5.0   5.0
4  20.0   5.0
5  25.0  20.0
6  35.0  25.0
  • Related