numpy -将列舍入为最接近的十进制值

zfycwa2u  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(95)

我有一个形状为(N,3)的浮点数数组。我想四舍五入的两个第一列的最接近的十进制值变化从1到0这是从一个参数。
我已经有了一个解决方案,但我想知道是否有一个更有效或“麻木”的方法来实现它。
例如:

import numpy as np

def round_to(arr, round_to):
  col_1_rounded = np.round(arr[:,0] / round_to) * round_to
  col_2_rounded = np.round(arr[:,1] / round_to) * round_to
  return np.vstack((col_1_rounded, col_2_rounded, arr[:,2])).transpose()

arr = np.array((
        (0.24, 1.26, 45.0),
        (0.76, 1.43, 23.0),
        (2.923, 2.22, 29.0),
        (33.1202, 2.1, 5.0),
        (2.01, 2.55, 41.0)
       ))

print(round_to(arr, 0.1))
>>>[[ 0.2  1.2 45. ]
   [ 0.8  1.4 23. ]
   [ 2.9  2.2 29. ]
   [33.1  2.1  5. ]
   [ 2.   2.5 41. ]]

print(round_to(arr, 0.5))
>>>[[ 0.   1.  45. ]
   [ 1.   1.5 23. ]
   [ 3.   2.  29. ]
   [33.   2.   5. ]
   [ 2.   2.5 41. ]]

注:

我在SO上发现了其他类似的舍入函数,使用的是round(value * round_to) / round_to,但是用我的演示数据反转/*运算符并没有返回正确的结果。为什么?

def round_to(arr, round_to):
  col_1_rounded = np.round(arr[:,0] * round_to) / round_to
  col_2_rounded = np.round(arr[:,1] * round_to) / round_to
  return np.vstack((col_1_rounded, col_2_rounded, arr[:,2])).transpose()

arr = np.array((
    (0.24, 1.26, 45.0),
    (0.76, 1.43, 23.0),
    (2.923, 2.22, 29.0),
    (33.1202, 2.1, 5.0),
    (2.01, 2.55, 41.0)
   ))

print(round_to(arr, 0.5))
>>>[[ 0.  2. 45.]
    [ 0.  2. 23.]
    [ 2.  2. 29.]
    [34.  2.  5.]
    [ 2.  2. 41.]]
ou6hu8tu

ou6hu8tu1#

numpy提供了around函数,允许输入小数位数进行舍入。在给出的示例中:

arr = np.array((
        (0.24, 1.26, 45.0),
        (0.76, 1.43, 23.0),
        (2.923, 2.22, 29.0),
        (33.1202, 2.1, 5.0),
        (2.01, 2.55, 41.0)
       ))
arr[:,0:2] = np.around(arr[:,0:2],1)

给出正确的输出:

array([[ 0.2,  1.3, 45. ],
       [ 0.8,  1.4, 23. ],
       [ 2.9,  2.2, 29. ],
       [33.1,  2.1,  5. ],
       [ 2. ,  2.6, 41. ]])

相关问题