Home > Mobile >  Round to nearest even integer with condition applied using Python
Round to nearest even integer with condition applied using Python

Time:10-13

I wish to round the values to the nearest even number - however if value is 0.5 ; round this to the number 2.

Data

ID  Q121 Q221 Q321 Q421 Q122 
AA  0.5  0.5  6.6  11.4 6.8
BB  8.5  6.5  3.1  5.3  7.2 

Desired

ID  Q121 Q221 Q321 Q421 Q122 
AA  2.0  2.0  6.0  12   6.0  
BB  8.0  6.0  4.0  6.0  8.0  

Doing

df.iloc[:,1:].astype(float).div(2).round()
    

However, this only rounds the numbers to nearest even without the condition applied. I am still researching, any suggestion is appreciated.

CodePudding user response:

here is one way to do it

# 0.5 being a special case, where it need to be made into 2
# check if value is zero when made into int, if so, make it 1

df.iloc[:,1:]=np.where(df.iloc[:,1:].astype(int)==0,
                       1, 
                       df.iloc[:,1:])

# if int value is odd, add 1 to it, else leave it as is
df.iloc[:,1:]=np.where(df.iloc[:,1:].astype(int)%2==1,
                       df.iloc[:,1:].astype(int)  1, 
                       df.iloc[:,1:].astype(int))
 
df
    ID  Q121    Q221    Q321    Q421    Q122
0   AA     2       2       6      12       6
1   BB     8       6       4       6       8

if 0.5 should be made to zero then

df.iloc[:,1:]=np.where(df.iloc[:,1:].astype(int)%2==1,
                       df.iloc[:,1:].astype(int)  1, 
                       df.iloc[:,1:].astype(int))
    ID  Q121    Q221    Q321    Q421    Q122
0   AA     0       0       6      12       6
1   BB     8       6       4       6       8

CodePudding user response:

edited:

# round as the expected result shows
df.iloc[:,1:] = df.iloc[:,1:].applymap(lambda   x:  int(x) if x > .5 else 1)
# making it even
df.iloc[:,1:] = df.iloc[:,1:].applymap(lambda x: x if x%2==0 else x 1)
ID Q121 Q221 Q321 Q421 Q122
0 AA 2 2 6 12 6
1 BB 8 6 4 6 8
  • Related