I have an array like this, although much larger:
X = np.array([
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
]);
and I want to insert a 2d array every k positions. For example:
dim = 2
to_insert = np.zeros((dim, X.shape[1]))
I'm using this code, but it's too slow for the size of the arrays I'm using:
for k in range(X.shape[0]):
X = np.insert(X, k*(dim+1), to_insert, axis=0)
#[[0 0 0 0 0]
# [0 0 0 0 0]
# [1 2 3 4 5]
# [0 0 0 0 0]
# [0 0 0 0 0]
# [1 2 3 4 5]
# [0 0 0 0 0]
# [0 0 0 0 0]
# [1 2 3 4 5]]
I am trying to do it using np.insert:
positions = [k for k in range(X.shape[0])]
X = np.insert(X, positions, to_insert, axis=0)
But it only works with dim=1. For dim>1 I get the error:
File "./test.py", line 25, in <module>
X = np.insert(X, positions, to_insert, axis=0)
File "/usr/local/lib/python3.6/dist-packages/numpy/lib/function_base.py", line 4629, in insert
new[tuple(slobj)] = values
ValueError: shape mismatch: value array of shape (2,5) could not be broadcast to indexing result of shape (3,5)
What is the most efficient way to do it?