I wish to take the sum of each row and round this value to the closest even number.
Data
JavaScript
x
5
1
id type Q1 22 Q2 22 Q3 22 Q4 22
2
AA hi 0.2 0.8 0.3 2.1
3
AA hello 0.2 0.7 0.3 1.7
4
AA ok 2 0.1 0 0.1
5
Desired
JavaScript
1
5
1
id type Q1 22 Q2 22 Q3 22 Q4 22 rounded_nearest_sum
2
AA hi 0.2 0.8 0.3 2.1 4
3
AA hello 0.2 0.7 0.3 1.7 2
4
AA ok 2 0.1 0 0.1 2
5
Doing
JavaScript
1
2
1
df.loc[:,'rounded_nearest_sum'] = df.sum(axis=1)
2
I realize I have to incorporate i+i.mod(2) into this script, however I am not sure how to incorporate. Any suggestion is helpful.
Advertisement
Answer
here is one way to do it
JavaScript
1
10
10
1
# filter columns that has 'Q' in their name and sum along the rows (across columns)
2
df['rounded_sum']=df.filter(like='Q').sum(axis=1)
3
4
# using np.where, check if integer part is even or odd
5
# if odd, add 1 else, keep the integer as is
6
df['rounded_sum']=np.where(df['rounded_sum'].astype(int)%2==1,
7
df['rounded_sum'].astype(int) +1,
8
df['rounded_sum'].astype(int))
9
df
10
JavaScript
1
5
1
id type Q1 22 Q2 22 Q3 22 Q4 22 rounded_sum
2
0 AA hi 0.2 0.8 0.3 2.1 4
3
1 AA hello 0.2 0.7 0.3 1.7 2
4
2 AA ok 2.0 0.1 0.0 0.1 2
5