Skip to content
Advertisement

Python – Applying condition on after decimal point (in dataframe column)

I have a dataframe which contains a column like below,

total_hours

8.31,
5.15,
10.53,
8.69,
10.57,
10.53
14.25,
10.55,
0.0,
10.73,
8.54,
10.55,
0.0,
10.53,
10.52,
10.54

I have to apply condition after decimal point, Those conditions are, ( (<50)it will replace .0), and (>50) it will replace .5)). How can i do it properly??? Thanks in advance,….

Advertisement

Answer

Just implement your own rounding criteria in a function, and apply the function on required column:

def customRound(val):
    fraction = val-int(val)
    return int(val)+0.5 if fraction>=0.5 else int(val)

df['total_hours']=df['total_hours'].apply(customRound)

OUTPUT:

    total_hours
0           8.0
1           5.0
2          10.5
3           8.5
4          10.5
5          10.5
6          14.0
7          10.5
8           0.0
9          10.5
10          8.5
11         10.5
12          0.0
13         10.5
14         10.5
15         10.5
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement