[英]In a dataframe with both positive & negative numbers, how to round positive numbers up and round negative numbers down (both to multiples of 5)?
With a dataframe as such:对于 dataframe 这样的:
data={'A1':[-7.22,-9.432,-0.00111,0.233,17,23,34],
'A2':[-23,-7.2455,-0.00222,0.54,1.345,19,21]}
kk=pd.DataFrame(data)
A1 A2
0 -7.22000 -23.00000
1 -9.43200 -7.24550
2 -0.00111 -0.00222
3 0.23300 0.54000
4 17.00000 1.34500
5 23.00000 19.00000
6 34.00000 21.00000
I want to round positive numbers up but negative numbers down (in multiples of 5), for example:我想向上舍入正数但向下舍入负数(5 的倍数),例如:
Tried using this method only to receive an error尝试使用此方法仅收到错误
def roundupdown5(x):
if x>=0:
return np.ceil(x/5)*5
else:
return np.floor(x/5)*5
kk[['A1','A2']].apply(lambda x: roundupdown5(x))
Thank you:)谢谢:)
You can use applymap()
instead of apply()
您可以使用
applymap()
而不是apply()
kk.applymap(roundupdown5)
results in结果是
A1 A2
0 -10.0 -25.0
1 -10.0 -10.0
2 -5.0 -5.0
3 5.0 5.0
4 20.0 5.0
5 25.0 20.0
6 35.0 25.0
You can use dict and list comprehension to apply the roundupdown5()
function to all the values of data
before building the DataFrame
:在构建
DataFrame
之前,您可以使用字典和列表理解将roundupdown5()
function 应用于data
的所有值:
import pandas as pd
import numpy as np
data={'A1':[-7.22,-9.432,-0.00111,0.233,17,23,34],'A2':[-23,-7.2455,-0.00222,0.54,1.345,19,21]}
kk=pd.DataFrame(data)
def roundupdown5(x):
if x>=0:
return np.ceil(x/5)*5
else:
return np.floor(x/5)*5
data = {k:[roundupdown5(i) for i in v] for k, v in data.items()}
kk=pd.DataFrame(data)
print(data, kk)
Output: Output:
{'A1': [-10.0, -10.0, -5.0, 5.0, 20.0, 25.0, 35.0], 'A2': [-25.0, -10.0, -5.0, 5.0, 5.0, 20.0, 25.0]} A1 A2
0 -10.0 -25.0
1 -10.0 -10.0
2 -5.0 -5.0
3 5.0 5.0
4 20.0 5.0
5 25.0 20.0
6 35.0 25.0
You can usenumpy.ceil
on the absolute values and bring back the sign withnumpy.sign
, then you benefit from vectorial speed:您可以在绝对值上使用
numpy.ceil
并使用numpy.sign
带回符号,然后您将受益于矢量速度:
np.ceil(abs(kk)/5)*5*np.sign(kk)
output: output:
A1 A2
0 -10.0 -25.0
1 -10.0 -10.0
2 -5.0 -5.0
3 5.0 5.0
4 20.0 5.0
5 25.0 20.0
6 35.0 25.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.