简体   繁体   中英

How to copy numpy array values at certain indices

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?

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])

PS: Advanced indexing (as here) actually returns copy of the array . So, the use of np.copy() is optional.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM