Home > Enterprise >  Conditional Rounding using Python
Conditional Rounding using Python

Time:10-13

I wish to round the values to the nearest even number w conditions:

if value is less than 0.6 ; round to 0
if value is greater than 0.6; round to 2

Data

ID  Q121 Q221 Q321 Q421 Q122 Q222 Q322
AA  0.1  0.5  6.6  11.4 6.8  1.9  1
BB  0.2  0.6  3.1  5.3  7.2  1.8  0.9

Desired

ID  Q121 Q221 Q321 Q421 Q122 Q222 Q322
AA  0    0    6.0  12   6.0  2    2
BB  0    2    4.0  6.0  8.0  2    2

Doing

# round as the expected result shows
df.iloc[:,1:] = df.iloc[:,1:].applymap(lambda   x:  int(x) if x < 0.6 else 0)


df.iloc[:,1:] = df.iloc[:,1:].applymap(lambda x: x if x%2==0 else x 1)

    

A SO member provided a suggestion which worked, however I wish to tweak. I am still researching, any suggestion is appreciated.

CodePudding user response:

You can use:

i = df.iloc[:, 1:].astype(int)
df2 = (i i.mod(2) # round to nearest 2
       # add 2 for values between 0.6-1
        2*(df.iloc[:, 1:].ge(0.6)
           &df.iloc[:, 1:].lt(1))
       )

df.update(df2)

Output:

   Q121  Q221  Q321  Q421  Q122  Q222  Q322
0     0     0     6    12     6     2     2
1     0     2     4     6     8     2     2
  • Related