Home > other >  finding every squares value in array
finding every squares value in array

Time:07-31

I have different sizes of arrays that each element is its index if it was flatten. Is there a way to print out every element per square going clockwise? I thought about slicing the arrays but that doesn't go clockwise and only prints one square and not all.

arr1 = np.array([[0, 1],[2, 3]])
arr2 = np.array([[0, 1, 2],[3, 4, 5]])
arr3 = np.array([[0, 1],[2, 3],[4, 5]])

print(arr1[0:2,0:2])
print()
print(arr2[0:2,0:2])
print()
print(arr3[0:2,0:2])
output:

[[0 1]
 [2 3]]

[[0 1]
 [3 4]]

[[0 1]
 [2 3]]

enter image description here

CodePudding user response:

Maybe this helps

import numpy as np


a = np.random.randint(0, 10, size=(7, 9))

print(a)


for i in range(a.shape[0]):
    for j in range(a.shape[1]):
        x = a[i:i 2, j:j 2]
        if x.flatten().size == 4:
            print(x) # every 2 by 2 array of 4 elements

CodePudding user response:

from numpy.lib.stride_tricks import sliding_window_view

def zay_117(arr):
    output = []
    for row in sliding_window_view(arr, window_shape=(2,2)):
        for sq in row:
            output.append(np.hstack((sq[0, 0:2], sq[1, 0:2][::-1])).tolist())
    return output

# zay_117(arr1)
# [[0, 1, 3, 2]]

# zay_117(arr2)
# [[0, 1, 4, 3], [1, 2, 5, 4]]

# zay_117(arr3)
# [[0, 1, 3, 2], [2, 3, 5, 4]]
  • Related