【问题标题】:For numpy 2d array, how to find all pairs of adjacent elements?对于numpy 2d数组,如何找到所有相邻元素对?
【发布时间】:2020-02-28 04:54:27
【问题描述】:

请帮助我。我想问一下 numpy 矩阵(二维数组)。

我有一个二维数组x,其中所有元素都以10 作为值。 x的形状最多为(1000, 1000)

让我定义一下: 如果x 的两个不同元素的索引(分别为行和列)最多不同1,则称它们为相邻对;并且两者都有1 作为它们的值。

我想知道如何找到A 上的所有相邻对。

我需要使用 for 循环吗?

非常感谢您。

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    我认为在 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 数组。

    【讨论】:

    • 非常感谢您的回答。它对我有很大帮助并解决了我的问题。两者都“是”,“一个元素可以不止一对吗?在上面可以。两个对角接触的元素算作一对吗?”
    猜你喜欢
    • 2015-11-26
    • 2014-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多