Home > Mobile >  Rounding off to the nearest 50's pandas dataframe
Rounding off to the nearest 50's pandas dataframe

Time:05-17

I have a pandas dataframe , screenshot shown below:

ID     Price  

100     1040.0
101     1025.0
102     750.0
103     891.0
104     924.0

Expected output shown below

ID     Price   Price_new

100     1040.0   1050
101     1025.0  1050
102     750.0   750
103     891.0   900
104     920.0    900    

This is what I have done but it's not what I want. I want to round off to the nearest fifty in such a way that at 1025 it should round to 1050.

df['Price_new'] = (df['Price'] / 50).round().astype(int) * 50

CodePudding user response:

This is due to the issue : round with python 3

s = (df['Price'] % 50)
df['new'] = df['Price']    np.where(s>=25,50-s,-s)
df
Out[33]: 
    ID  Price   new
0  100   1040  1050
1  101   1025  1050
2  102    750   750
3  103    891   900
4  104    924   900

CodePudding user response:

Follow my suggestion:

    import pandas as pd

    dt = pd.DataFrame({'ID':[100,101,102,103,104], 'Price': 
                      [1040,1025,750,891,924]})

    #VERSION1
    dt['Price_new'] = round((dt['Price'] 1)/50).astype(int)*50
    #VERSION2
    dt['Price_new_v2'] = dt['Price']-(dt['Price'].map(lambda x: xP))   
     (dt['Price'].map(lambda x: round((((xP) 1)/50))))*50

         ID Price   Price_new   Price_new_V2
    0   100 1040    1050        1050
    1   101 1025    1050        1050
    2   102 750     750         750
    3   103 891     900         900
    4   104 924     900         900

Just plus 1 in your math you will be able to find your correct answer. But there is another way to do it, my opnião is more understandable than the second version even though I used the modulo operator.

  • Related