首页 > 解决方案 > 将元素插入到numpy数组中,以便最小间距是任意的

问题描述

给定一个有序numpy的浮点数组(从最小值到最大值),我需要确保元素之间的间距小于我调用的任意浮点数step

这是我的代码,据我所知它可以工作,但我想知道是否有更优雅的方法来做到这一点:

import numpy as np

def slpitArr(arr, step=3.):
    """
    Insert extra elements into array so that the maximum spacing between
    elements is 'step'.
    """
    # Keep going until no more elements need to be added
    while True:
        flagExit = True
        for i, v in enumerate(arr):
            # Catch last element in list
            try:
                if abs(arr[i + 1] - v) > step:
                    new_v = (arr[i + 1] + v) / 2.
                    flagExit = False
                    break
            except IndexError:
                pass
        if flagExit:
            break
        # Insert new element
        arr = np.insert(arr, i + 1, new_v)

    return arr


aa = np.array([10.08, 14.23, 19.47, 21.855, 24.34, 25.02])

print(aa)
print(slpitArr(aa))

这导致:

[10.08  14.23  19.47  21.855 24.34  25.02 ]
[10.08  12.155 14.23  16.85  19.47  21.855 24.34  25.02 ]

标签: pythonnumpy

解决方案


这是一个一次性解决方案

1) 计算连续点之间的差异d

2) ceil-将d逐级除以得到m

2a) 可选地将m向上取整到最接近的 2 次幂

3) 将d除以m并将结果重复m

4) 形成累积和

这是代码。技术说明: d 的第一个元素不是差异而是“锚”,因此它等于数据的第一个元素。

def fill(data, step, force_power_of_two=True):
    d = data.copy()
    d[1:] -= data[:-1]
    if force_power_of_two:
        m = 1 << (np.frexp(np.nextafter(d / step, -1))[1]).clip(0, None)
    else:
        m = -(d // -step).astype(int)
    m[0] = 1
    d /= m
    return np.cumsum(d.repeat(m))

样品运行:

>>> inp
array([10.08 , 14.23 , 19.47 , 21.855, 24.34 , 25.02 ])
>>> fill(inp, 3)
array([10.08 , 12.155, 14.23 , 16.85 , 19.47 , 21.855, 24.34 , 25.02 ])

推荐阅读