Please help me. I want to ask about numpy matrix(2D array).
I have a 2d array x
of which all element has 1
or 0
as the value. The shape of x
is (1000, 1000)
at most.
Let me define that: two distinct elements of x
are said an adjacent pair if their indices (rows and columns respectively) differ 1
at most; and both have 1
as their values.
I want to know how to find all adjacent pairs on A
.
Do I need to use a for loop?
Thank you very much in advance.
I think the requirements can be met without explicit loops in 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]
Can an element be in more than one pair? In the above it can be. Do two diagonally touching elements count as a pair? If so a shifted_left_and_down array would be required too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.