Salih
Salih

Reputation: 719

Pandas Rounding Columns for Exact Value

My input dataframe;

     A          B       C 
0    0          1       1.3
1    1.2        2       2.25
2    1.5        3       4.42
3    2.7        4       5.12
4    3.9        5       6.24
5    4.55       6       7.25

I want to round the C columns according to a threshold in dataframe. But i couldn' t get the desired results.

Code is;

threshold=0.25
df['C']=round(df['C'] - threshold+0.5)

Output is;

     A          B       C 
0    0          1       2
1    1.2        2       2
2    1.5        3       5
3    2.7        4       5
4    3.9        5       6
5    4.55       6       7

Desired output is;

     A          B       C 
0    0          1       2
1    1.2        2       3
2    1.5        3       5
3    2.7        4       5
4    3.9        5       6
5    4.55       6       8

I got a trouble with .25 value. I want to round up this values too. Could ypu please help me about this?

Upvotes: 3

Views: 221

Answers (2)

Chris Adams
Chris Adams

Reputation: 18647

You could use use numpy.floor and add the boolean (1 if mod(1) is >= threshold and 0 if its <):

threshold = 0.25
df['C'] = np.floor(df['C']) + df['C'].mod(1).ge(threshold)

[out]

      A  B    C
0  0.00  1  2.0
1  1.20  2  3.0
2  1.50  3  5.0
3  2.70  4  5.0
4  3.90  5  6.0
5  4.55  6  8.0

Upvotes: 2

jezrael
jezrael

Reputation: 862471

Use numpy.isclose with numpy.modf for test .5 for condition and round by numpy.ceil and numpy.round by numpy.where:

threshold=0.25

s = df['C'] - threshold+0.5
print (s)
0    1.55
1    2.50
2    4.67
3    5.37
4    6.49
5    7.50
Name: C, dtype: float64

m = np.isclose(np.modf(s)[0], 0.5)

df['C']=np.where(m, np.ceil(s), np.round(s))
print (df)
      A  B    C
0  0.00  1  2.0
1  1.20  2  3.0
2  1.50  3  5.0
3  2.70  4  5.0
4  3.90  5  6.0
5  4.55  6  8.0

Upvotes: 2

Related Questions