Issue
I have 2 numpy arrays:
a
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4]])
and
aa
array([[11, 11, 11],
[22, 22, 22],
[33, 33, 33],
[44, 44, 44],
[55, 55, 55],
[66, 66, 66]])
I want to insert fragments of aa
into a
such that a
would look like:
a
array([[1, 1, 1],
[22, 22, 22],
[33, 33, 33],
[2, 2, 2],
[55, 55, 55],
[66, 66, 66]
[3, 3, 3],
[4, 4, 4]]).
I tried:
np.insert(a,[1,3],[aa[1:3], aa[4:]], axis=0)
np.insert(a,[1,3],[[aa[1],aa[2]], [aa[4],aa[5]]], axis=0),
but got: ValueError: shape mismatch: value array of shape (2,2,3) could not be broadcast to indexing result of shape (2,3).
However for a single index it worked:
np.insert(a,1,[aa[1],aa[2]], axis=0)
array([[ 1, 1, 1],
[22, 22, 22],
[33, 33, 33],
[ 2, 2, 2],
[ 3, 3, 3],
[ 4, 4, 4]])
but did not work for for slice:
np.insert(a,1,[aa[1:3]], axis=0)
Why np.insert()
does not accept slices as values and is there a way to insert fragments of aa
into a
in one liner?
Solution
Suppose we have this:
idx_list = [1,2]
slices = aa[np.r_[1:3,4:6]]
np.insert(a,idx_list,slices, 0)
We get a ValueError
:
ValueError: shape mismatch: value array of shape (4,3) could not be broadcast to indexing result of shape (2,3)
So, here np.insert
is expecting to insert one row at each index in idx_list
, but we are supplying only 2 index values, while we have 4 rows to insert. Solution is just to double the index values:
idx_list = [1,2]
idx_list_ext = []
for i in idx_list:
idx_list_ext.extend([i, i])
# [1, 1, 2, 2]
slices = aa[np.r_[1:3,4:6]]
out = np.insert(a,idx_list_ext,slices, 0)
out
array([[ 1, 1, 1],
[22, 22, 22],
[33, 33, 33],
[ 2, 2, 2],
[55, 55, 55],
[66, 66, 66],
[ 3, 3, 3],
[ 4, 4, 4]])
Answered By - ouroboros1
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.