numpy-100
numpy-100 copied to clipboard
An alternative solution for Q.70
- Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★) hint: array[::4]
# Author: Warren Weckesser Z = np.array([1,2,3,4,5]) nz = 3 Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz)) Z0[::nz+1] = Z print(Z0)
A more readable function from numpy: numpy.insert(arr, obj, values, axis=None)
. NumPy Doc
Thus, an alternative solution will be:
Z = np.array([1, 2, 3, 4, 5])
Z0 = np.insert(a[..., np.newaxis], [1], [[0, 0, 0] for _ in range(len(a))], axis=1)
Z0 = Z0.flatten()[:-3]
print(Z0)
您好,您的邮件我已收到,我会尽快回复您。
@Jeff1999 Thansk. Did you time the two solutions ? I'm not too confident with the for loop and a big array.