Reputation: 711
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?
Upvotes: 2
Views: 87
Reputation: 260640
Using a different example for clarity:
# X
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
# to_insert
array([[ -1, -2, -3, -4, -5],
[ -6, -7, -8, -9, -10]])
You can tile
a destination array and use indexing to "insert" the rows of X:
Y = np.tile(np.r_[to_insert, np.zeros((1, X.shape[1]))], (X.shape[0], 1))
Y[to_insert.shape[0]::to_insert.shape[0]+1] = X
output Y
:
array([[ -1., -2., -3., -4., -5.], # to_insert
[ -6., -7., -8., -9., -10.], #
[ 0., 1., 2., 3., 4.], # X row 0
[ -1., -2., -3., -4., -5.], # to_insert
[ -6., -7., -8., -9., -10.], #
[ 5., 6., 7., 8., 9.], # X row 1
[ -1., -2., -3., -4., -5.], # to_insert
[ -6., -7., -8., -9., -10.], #
[ 10., 11., 12., 13., 14.]]) # X row 2
Upvotes: 1