Numpy/Python: Array iteration without for-loop

前端 未结 3 1890
一生所求
一生所求 2020-12-11 11:35

So it\'s another n-dimensional array question: I want to be able to compare each value in an n-dimensional arrays with its neighbours. For example if a is the array which is

3条回答
  •  长情又很酷
    2020-12-11 12:17

    Something like:

    a = np.array([1,2,3,4,4,5])
    a == np.roll(a,1)
    

    which returns

    array([False, False, False, False,  True, False], dtype=bool
    

    You can specify an axis too for higher dimensions, though as others have said you'll need to handle the edges somehow as the values wrap around (as you can guess from the name)

    For a fuller example in 2D:

    # generate 2d data
    a = np.array((np.random.rand(5,5)) * 10, dtype=np.uint8)
    
    # check all neighbours
    for ax in range(len(a.shape)):
        for i in [-1,1]:
            print a == np.roll(a, i, axis=ax)
    

提交回复
热议问题