I have a numpy array and I want to copy parts of the array at certain indices to a different array.
我有一个numpy数组,我想将某些索引的部分数组复制到不同的数组。
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?
有没有好办法呢?
1 个解决方案
#1
1
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.
P.S。:高级索引(如此处)实际上返回数组的副本。因此,使用np.copy()是可选的。
#1
1
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.
P.S。:高级索引(如此处)实际上返回数组的副本。因此,使用np.copy()是可选的。