亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

對于numpy 2d數組,如何找到所有相鄰元素對?

對于numpy 2d數組,如何找到所有相鄰元素對?

收到一只叮咚 2022-08-11 20:21:06
請幫幫我。我想問一下numpy matrix(2D array)。我有一個2d數組,其中所有元素都具有或作為值。的形狀最多是。x10x(1000, 1000)讓我定義一下:如果兩個不同的元素的索引(分別分別為行和列)最多不同,則稱為相鄰對;兩者都有自己的價值觀。x11我想知道如何查找 上的所有相鄰對。A我是否需要使用 for 循環?非常感謝你提前。
查看完整描述

1 回答

?
互換的青春

TA貢獻1797條經驗 獲得超6個贊

我認為這些要求可以在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]

一個元素可以有多個對嗎?在上面,它可以是。兩個對角線接觸的元素算作一對嗎?如果是這樣,還需要一個shifted_left_and_down數組。


查看完整回答
反對 回復 2022-08-11
  • 1 回答
  • 0 關注
  • 140 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號