How can I simultaneously select all odd rows and all even columns of an array

后端 未结 3 1981
忘了有多久
忘了有多久 2021-02-01 04:33

I\'m new to programming and I need a program, that can select all odd rows and all even columns of a Numpy array at the same time in one code. here is what I tried:



        
3条回答
  •  心在旅途
    2021-02-01 04:40

    Let's say you have this array, x:

    >>> import numpy
    >>> x = numpy.array([[ 1,  2,  3,  4,  5],
    ... [ 6,  7,  8,  9, 10],
    ... [11, 12, 13, 14, 15],
    ... [16, 17, 18, 19, 20]])
    

    To get every other odd row, like you mentioned above:

    >>> x[::2]
    array([[ 1,  2,  3,  4,  5],
           [11, 12, 13, 14, 15]])
    

    To get every other even column, like you mentioned above:

    >>> x[:, 1::2]
    array([[ 2,  4],
           [ 7,  9],
           [12, 14],
           [17, 19]])
    

    Then, combining them together yields:

    >>> x[::2, 1::2]
    array([[ 2,  4],
           [12, 14]])
    

    For more details, see the Indexing docs page.

提交回复
热议问题