簡體   English   中英

從列表索引為 numpy 數組賦值

[英]Assign values to numpy array from list indices

我有一個 numpy 數組和一個列表,比如:

np_array = np.random.randint(0,3,(2,3))
np_array
array([[1, 1, 2],
       [2, 1, 2]])

indices_list:
[7,8,9]

並且想要一個 numpy 數組,它從列表的索引中獲取其值(即,如果 np_array 的值為 2,則將索引列表 [2] 設置為新數組上的值):

np_array_expected
array([[8, 8, 9],
       [9, 8, 9]])

我做了這個不成功的嘗試:

np_array[indices_list]
Traceback (most recent call last):

  File "/tmp/ipykernel_27887/728354097.py", line 1, in <module>
    np_array[indices_list]

IndexError: index 7 is out of bounds for axis 0 with size 2


indices_list[np_array]
Traceback (most recent call last):

  File "/tmp/ipykernel_27887/265649000.py", line 1, in <module>
    indices_list[np_array]

TypeError: only integer scalar arrays can be converted to a scalar index

這只是索引: b[a] ,因為第二個數組也是 numpy 數組。

輸出:

array([[8, 8, 9],
       [9, 8, 9]])

您只需要將列表也更改為一個 numpy 數組,那么它就是簡單的索引:

np.array(indices_list)[np_array]

做你想做的,我想。 或不?

這是我的迭代解決方案:

>>> arr = np.array([[1,1,2],[2,1,2]])
>>> indices_list = [7,8,9]
>>> for i in range(arr.shape[0]) :
...     for j in range(arr.shape[1]) :
...         arr[i][j] = indices_list[arr[i][j]]

>>> print(arr)

輸出 :

array([[8, 8, 9],
       [9, 8, 9]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM