Numpy/Python: Array iteration without for-loop

前端 未结 3 1877
一生所求
一生所求 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:13

    How about just:

    np.diff(a) != 0
    

    ?

    If you need the neighbours in the other axis, maybe diff the result of np.swapaxes(a) and merge the results together somehow ?

    0 讨论(0)
  • 2020-12-11 12:14

    This might also be useful, this will compare each element to the following element, along axis=1. You can obviously adjust the axis or the distance. The trick is to make sure that both sides of the == operator have the same shape.

    a[:, :-1, :] == a[:, 1:, :]
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题