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

后端 未结 3 1975
忘了有多久
忘了有多久 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

    Slicing an array:

    import numpy as np
    
    arr = np.array([[1, 2, 3], [4, 5, 6],[7, 8, 9],[10, 11, 12],[13, 14, 15]])
    
    case1=arr[::2,:]    #odd rows
    case2=arr[1::2,:]   #even rows
    case3=arr[:,::2]    #odd cols
    case4=arr[:,1::2]   #even cols
    print(case1)
    print("\n") 
    print(case2)
    print("\n") 
    print(case3)
    print("\n") 
    print(case4)
    print("\n")      
    

    Gives:

    [[ 1  2  3]
     [ 7  8  9]
     [13 14 15]]
    
    
    [[ 4  5  6]
     [10 11 12]]
    
    
    [[ 1  3]
     [ 4  6]
     [ 7  9]
     [10 12]
     [13 15]]
    
    
    [[ 2]
     [ 5]
     [ 8]
     [11]
     [14]]
    

提交回复
热议问题