Reputation: 56823
I have a numpy array and I want to copy parts of the array at certain indices to a different array.
arr = np.arange(10)
np.random.shuffle(arr)
print arr
[0 3 4 2 5 6 8 7 9 1]
I want to copy the value at the indices
copy_indices = [3, 7, 8]
Is there any good way to do this?
Upvotes: 1
Views: 6906
Reputation: 61325
How about using this approach?
In [16]: arr
Out[16]: array([2, 9, 5, 6, 1, 4, 7, 8, 3, 0])
In [17]: copy_indices
Out[17]: [3, 7, 8]
In [18]: sliced_arr = np.copy(arr[copy_indices, ])
# alternatively
# In [18]: sliced_arr = arr[copy_indices, ]
In [19]: sliced_arr
Out[19]: array([6, 8, 3])
P.S.: Advanced indexing (as here) actually returns copy of the array. So, the use of np.copy()
is optional.
Upvotes: 1