How can I create a slice object for Numpy array?

后端 未结 2 2025
梦毁少年i
梦毁少年i 2021-01-07 19:30

I\'ve tried to find a neat solution to this, but I\'m slicing several 2D arrays of the same shape in the same manner. I\'ve tidied it up as much as I can by defining a list

2条回答
  •  一个人的身影
    2021-01-07 20:13

    You can index a multidimensional array by using a tuple of slice objects.

    window = slice(col_start, col_stop), slice(row_start, row_stop)
    a1 = array1[window]
    a2 = array2[window] 
    

    This is not specific to numpy and is simply how subscription/slicing syntax works in python.

    class mock_array:
        def __getitem__(self, key):
            print(key)
    m = mock_array()
    m[1:3, 7:9] # prints tuple(slice(1, 3, None), slice(7, 9, None))
    

提交回复
热议问题