[英]Reference to ndarray rows in ndarray
是否可以在另一個numpy數組中存儲numpy數組的特定行的引用?
我有一個二維節點數組,例如
nodes = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]])
現在,我只想選擇其中一些並將引用存儲在另一個numpy數組中:
nn = np.array([nodes[0], nodes[3]])
如果我在nn
修改條目,則數組nodes
保持不變。 有沒有一種方法可以存儲對ndarray nn
nodes
的引用?
您可以將索引存儲到numpy數組中所需的行:
ref = np.array([0, 3])
您可以在索引表達式中使用引用來訪問所需的節點:
>>> nn = nodes[ref]
>>> nn
array([[1, 2],
[4, 5]])
在這種情況下, nn
將是一個深副本,與原始副本沒有任何關系。 盡管nn[foo] = bar
不會影響原始數組,但是您可以直接使用ref
:
>>> nodes[ref, 1] = [17, 18]
>>> nodes
array([[ 1, 17],
[ 2, 3],
[ 3, 4],
[ 4, 18],
[ 5, 6]])
另外,您也可以將遮罩用於ref
:
>>> ref2 = np.zeros(nodes.shape[0], dtype=np.bool)
>>> ref2[ref] = True
>>> ref2
array([ True, False, False, True, False], dtype=bool)
您幾乎可以執行所有相同的操作:
>>> nn2 = nodes[ref2]
>>> nn2
array([[1, 2],
[4, 5]])
修改也可以:
>>> nodes[ref2, 1] = [19, 23]
>>> nodes
array([[ 1, 19],
[ 2, 3],
[ 3, 4],
[ 4, 23],
[ 5, 6]])
使用索引數組唯一更方便的是從選擇中選擇特定節點:
>>> nodes[ref[0], 0]
1
方法1
首先,使用dtype = object初始化一個None的Numpy數組。 (它不一定非要是None。我猜想您只是不能在初始化時放置引用,因為Numpy會以某種方式創建它的深層副本。)
然后,將引用放入數組中。
nodes = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]])
# nn = np.array([nodes[0], nodes[1]],dtype=object) would not work
nn = np.array([None, None], dtype=object)
nn[0] = nodes[0]
nn[1] = nodes[3]
# Now do some modification.
nn[0][1] = 100
Output of nodes:
array([[ 1, 100],
[ 2, 3],
[ 3, 4],
[ 4, 5],
[ 5, 6]])
# make it a function
def make_ref(old_array, indeces):
ret = np.array([None for _ in range(len(indeces))])
for i in range(len(indeces)):
ret[i] = old_array[indeces[i]]
return ret
nn = make_ref(nodes, [0, 3])
方法二
如果不需要將其放在Numpy數組中,只需使用列表來托管引用。
nn = [nodes[0], nodes[1]]
在Numpy中,您可以查看可以編輯的數組的視圖。 在您的示例中,您可以執行以下操作:
import numpy as np
nodes = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]])
node_idx = np.array([0, 3])
nodes[node_idx] = np.array([[1, 5], [2, 5]])
nodes
輸出:
array([[1, 5],
[2, 3],
[3, 4],
[2, 5],
[5, 6]])
您也可以將其替換為布爾數組:
import numpy as np
nodes = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]])
node_mask = np.array([True, False, False, True, False])
nodes[node_mask] = np.array([[1, 5], [2, 5]])
nodes
產生相同的結果。 當然,這意味着您可以像這樣做魔術:
import numpy as np
nodes = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]])
nodes[nodes[:, 0] == 3] = [1, 5]
nodes
用[1, 5]
替換第一個等於3
的第一個元素的所有行。 輸出:
array([[1, 2],
[2, 3],
[1, 5],
[4, 5],
[5, 6]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.