python - 将元素插入到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 ]
解决方案
这是一个一次性解决方案
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 ])
推荐阅读
- qt - 更新独立的应用程序
- javascript - 可以使用 Webpack 一次导入一个模块并让方法可用于多个模块
- python - 使用 HDF5 格式将 pandas 数据帧写入 S3
- c - 打印文件中的字符但省略括号中的字符
- angular - 为什么在传递方法参数时未定义 Ionic ionRefresher 事件?
- azure - 是否有可能使用 Azure 数据工厂将数据从 Azure 数据湖 gen2 传输到 Azure 事件中心?
- ios - 如何使用 Swift Code 检索快照计数
- apache-kafka - 如何备份 Kafka 的主题配置?
- python - 如何在 Redis 中将订阅者注册为 Python 中的回调侦听器
- apache-kafka - Kafka JDBC 连接器在使用 TimestampConverter 时抛出 NullPointerException