我有以下問題,我想使用 numpy 陣列元素來解決。問題是:
Matrix = np.zeros((4*4), dtype = bool) 給出了這個二維矩陣。
Matrix = [[False, False, False, False],
[False, False, False, False],
[False, False, False, False],
[False, False, False, False]]
讓我們假設我們有另一個陣列 a = np.array([0,1], [2,1], [3,3])
a = [[0, 1],
[2, 1],
[3, 3]]
我的問題是:如何使用 a 陣列的元素作為索引來用 True 填充我的矩陣。輸出應該是這樣的
Matrix = [[False, True, False, False], # [0, 1]
[False, False, False, False],
[False, True, False, False], # [2, 1]
[False, False, False, True]] # [3, 3]
uj5u.com熱心網友回復:
import numpy as np
Matrix = np.zeros((4*4), dtype = bool).reshape(4,4)
a = [[0, 1],
[2, 1],
[3, 3]]
將它們展開為二維陣列的正確索引陣列對
a = ([x[0] for x in a], [x[1] for x in a])
Matrix[a] = True
>>> Matrix
array([[False, True, False, False],
[False, False, False, False],
[False, True, False, False],
[False, False, False, True]])
uj5u.com熱心網友回復:
制作 (4,4) bool 陣列的簡單方法:
In [390]: arr = np.zeros((4,4), dtype = bool)
In [391]: arr
Out[391]:
array([[False, False, False, False],
[False, False, False, False],
[False, False, False, False],
[False, False, False, False]])
制作的正確語法a:
In [392]: a = np.array([[0,1], [2,1], [3,3]])
In [393]: a
Out[393]:
array([[0, 1],
[2, 1],
[3, 3]])
使用 的 2 列a作為 2 維的索引arr:
In [394]: arr[a[:,0],a[:,1]]=True
In [395]: arr
Out[395]:
array([[False, True, False, False],
[False, False, False, False],
[False, True, False, False],
[False, False, False, True]])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/410466.html
標籤:
