假设我有2个numpy 2D数组,最小值和最大值,它们将始终彼此相同。我想创建第三个数组,结果,这是将linspace应用于max和min值的结果。是否有某种“numpy”/矢量化方法可以做到这一点?下面是示例非矢量化代码,以显示我想要的结果。
import numpy as np
mins = np.random.rand(2,2)
maxs = np.random.rand(2,2)
# Number of elements in the linspace
x = 3
m, n = mins.shape
results = np.zeros((m, n, x))
for i in range(m):
for j in range(n):
min = mins[i][j]
max = maxs[i][j]
results[i][j] = np.linspace(min, max, num=x)
最佳答案
这是一种基于 this post
的矢量化方法,用于处理一般的n-dim情况-
def create_ranges_nd(start, stop, N, endpoint=True):
if endpoint==1:
divisor = N-1
else:
divisor = N
steps = (1.0/divisor) * (stop - start)
return start[...,None] + steps[...,None]*np.arange(N)
sample 运行-
In [536]: mins = np.array([[3,5],[2,4]])
In [537]: maxs = np.array([[13,16],[11,12]])
In [538]: create_ranges_nd(mins, maxs, 6)
Out[538]:
array([[[ 3. , 5. , 7. , 9. , 11. , 13. ],
[ 5. , 7.2, 9.4, 11.6, 13.8, 16. ]],
[[ 2. , 3.8, 5.6, 7.4, 9.2, 11. ],
[ 4. , 5.6, 7.2, 8.8, 10.4, 12. ]]])
关于python - 跨多维数组的矢量化NumPy Linspace,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46694167/