Python在数组重排序中的怪异行为

2024-09-25 12:34:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试重新排列一些数组,但它似乎并不总是正常工作:

# Works fine
arr = np.array([2,3,1])    
idx1 = np.array([1,0,2])
arr[idx1]
>> array([3, 2, 1])

# Doesn't work
arr = np.array([2,3,1])
idx2 = np.array([2,0,1])
arr[idx2]
>> array([1, 2, 3]) # Should have been [3,1,2]

我做错什么了吗?你知道吗


Tags: havenp数组arrayworkworksarrbeen
1条回答
网友
1楼 · 发布于 2024-09-25 12:34:40

索引使用索引数组重建数组。索引数组包含原始数组中元素的位置(索引)列表。你知道吗

Numpy arrays may be indexed with other arrays (or any other sequence- like object that can be converted to an array, such as lists, with the exception of tuples; see the end of this document for why this is). The use of index arrays ranges from simple, straightforward cases to complex, hard-to-understand cases. For all cases of index arrays, what is returned is a copy of the original data, not a view as one gets for slices.

Index arrays must be of integer type. Each value in the array indicates which value in the array to use in place of the index.

就你而言:

arr = np.array([2,3,1])
idx2 = np.array([2,0,1])

索引[2, 0, 1]表示[third element, first element, second element]

arr[idx2]你得到[1, 2, 3]。是的。你知道吗

示例:带有第二和第三个元素的索引

>>> arr[np.array([1,2])]
array([3, 1])

相关问题 更多 >