[英]For numpy 2d array, how to find all pairs of adjacent elements?
請幫我。 我想問一下 numpy 矩陣(二維數組)。
我有一個二維數組x
,其中所有元素的值都是1
或0
。 x
的形狀最多為(1000, 1000)
。
讓我定義一下:如果x
兩個不同元素的索引(分別為行和列)最多相差1
,則稱它們為相鄰對; 並且都具有1
作為它們的值。
我想知道如何在A
上找到所有相鄰的對。
我需要使用 for 循環嗎?
非常感謝您提前。
我認為無需在 numpy 中進行顯式循環即可滿足要求。
import numpy as np
np.random.seed(1234) # Make random array reproduceable
arr = np.random.randint( 0, 2, size = (10,10))
leftshifted = arr[ :, 1:] # Shift arr 1 col left, shape = (10, 9)
downshifted = arr[ 1: ] # Shift arr 1 row down, shape = ( 9, 10)
hrows, hcols = np.where( arr[ :, :-1 ] & leftshifted )
# arr[ :,:-1 ] => ignore last column for the comparison
# returns rows and columns where arr and leftshifted = 1
# i.e. where two adjacent columns in a row are 1
vrows, vcols = np.where( arr[ :-1 ] & downshifted )
# arr[ :-1 ] => ignore last row for the comparison
# returns rows and columns where arr and downshifted = 1
# i.e. where two adjacent rows in a column are 1
print(arr, '\n')
# [[1 1 0 1 0 0 0 1 1 1]
# [1 1 0 0 1 0 0 0 0 0]
# [0 0 0 0 1 0 1 1 0 0]
# [1 0 0 1 0 1 0 0 0 1]
# [1 1 0 1 1 0 1 0 1 0]
# [1 1 1 1 0 1 0 1 1 0]
# [0 1 0 0 1 1 1 0 0 0]
# [1 1 1 1 1 1 1 0 1 0]
# [1 0 1 0 0 0 0 0 0 0]
# [0 1 1 1 0 1 0 0 1 1]]
print('Row indices :', hrows)
print('Col start ix :', hcols)
print('Col end ix :', hcols+1)
# Row indices : [0 0 0 1 2 4 4 5 5 5 5 6 6 7 7 7 7 7 7 9 9 9]
# Col start ix : [0 7 8 0 6 0 3 0 1 2 7 4 5 0 1 2 3 4 5 1 2 8]
# Col end ix : [1 8 9 1 7 1 4 1 2 3 8 5 6 1 2 3 4 5 6 2 3 9]
print('\nStart Row:', vrows, '\nEnd Row :',vrows+1, '\nColumn :', vcols)
# Start Row: [0 0 1 3 3 4 4 4 4 5 5 6 6 6 6 7 7 8]
# End Row : [1 1 2 4 4 5 5 5 5 6 6 7 7 7 7 8 8 9]
# Column : [0 1 4 0 3 0 1 3 8 1 5 1 4 5 6 0 2 2]
一個元素可以超過一對嗎? 在上面它可以。 兩個對角接觸的元素算作一對嗎? 如果是這樣,也需要 shift_left_and_down 數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.