Python 四舍五入到5的更高倍数
我试图将值四舍五入到5的更高倍数 例如:Python 四舍五入到5的更高倍数,python,pandas,rounding,Python,Pandas,Rounding,我试图将值四舍五入到5的更高倍数 例如: df values rounded_values (expected column) 10 10 11 15 13 15 22 25 21 25 34 35 35 35 尝试: 尝
df
values rounded_values (expected column)
10 10
11 15
13 15
22 25
21 25
34 35
35 35
尝试:
尝试:
使用mod:
def round_to5(x):
if x%5 == 0:
return x
else:
return x + (5 - x%5)
df['round_values'] = df['values'].apply(lambda x: round_to5(x))
输出为:
values round_values
0 10 10
1 12 15
2 24 25
3 27 30
使用mod:
def round_to5(x):
if x%5 == 0:
return x
else:
return x + (5 - x%5)
df['round_values'] = df['values'].apply(lambda x: round_to5(x))
输出为:
values round_values
0 10 10
1 12 15
2 24 25
3 27 30
Pandas列的底层容器是numpy数组,因此您可以在此处使用numpy:
import numpy as np
df['rounded_values'] = np.round_((np.ceil(df['values']/5)*5)).astype(int)
Pandas列的底层容器是numpy数组,因此您可以在此处使用numpy:
import numpy as np
df['rounded_values'] = np.round_((np.ceil(df['values']/5)*5)).astype(int)
这可以简单地完成,首先除以5,然后调用
math.ceil
,然后乘以5:
>>>import math
>>>round5 = lambda n: math.ceil(n / 5) * 5
>>> round5(22)
25
>>> round5(21)
25
>>> round5(35)
35
>>> round5(10)
10
>>> round5(11)
15
>>> round5(15)
15
这可以简单地完成,首先除以5,然后调用
math.ceil
,然后乘以5:
>>>import math
>>>round5 = lambda n: math.ceil(n / 5) * 5
>>> round5(22)
25
>>> round5(21)
25
>>> round5(35)
35
>>> round5(10)
10
>>> round5(11)
15
>>> round5(15)
15
如果x%5==0或者x+(5-x%5)如果x%5==0或者x+(5-x%5)你不能只使用一个简单的函数
lambda x:x如果x%5==0或者x+(5-x%5)