Search code examples
pythonarrayspython-3.xnumpymatrix

How to easily get these values from a 2d matrix using numpy?


I have this 2d numpy matrix

a = np.array(
[[ 1  2  3  4  5] 
 [ 6  7  8  9 10] 
 [11 12 13 14 15] 
 [16 17 18 19 20] 
 [21 22 23 24 25] 
 [26 27 28 29 30]])

and I want to extract these values from it just for the sake of learning :)

[[11,12],[16,17],[29,30]]

After so many tries I ended up in chatGPT which gave me a wrong answer :(. chatGPT suggested this a[[2, 3, 5], [0, 1, 1]] but yeilded these values [11 17 27].

Any help would be appreciated thanks


Solution

  • You need to add commas to your array.

    You can use numpy indexing: https://numpy.org/doc/stable/user/basics.indexing.html

    import numpy as np
    a=np.array([[ 1,  2,  3,  4,  5],
           [ 6,  7,  8,  9, 10],
           [11, 12, 13, 14, 15],
           [16, 17, 18, 19, 20],
           [21, 22, 23, 24, 25],
           [26, 27, 28, 29, 30]])
    

    print(a[2:4,0:2]) 
    

    or

    print(a[[2,3],0:2])    
    

    #output

    array([[11, 12],
           [16, 17]])
    

    print(a[5:,3:])
    

    or

    print(a[[5],3:])
    

    #output

    array([[29, 30]])
    

    Everything in one go:

    a[[2,3],0:2].tolist() + a[[5],3:].tolist()
    

    or

    a[2:4,0:2].tolist() + a[5:,3:].tolist()
    

    #output

    [[11, 12], [16, 17], [29, 30]]