Python array extraction

85 Views Asked by At

I am extracting the first two rows of an array A. In x1, I first used A[:,] and then [0:2,:]. In x2, I immediately used [0:2,:]. They are basically the same as shown below. However, I saw someone used A[:,][0:2,:] but I really don't know the reason for having [:,] first. This seems redundant to me. Is there any specific reason that we use A[:,][0:2,:] rather than A[0:2,:]? Sorry if this question looks so easy.

import numpy as np

A =np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])

x1=A[:,][0:2,:]

x2=A[0:2,:]

x1
Out[1]: 
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])

x2
Out[2]: 
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])
1

There are 1 best solutions below

2
On

If you do the following code , you will see the reason for the same behaviour -

import numpy as np
A =np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
x1=A[:,]
print(x1)
>> array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])

This is because in numpy , , is used as the slicing character , if you do `A[:,1] , it would give the results only from 2nd column (index = 1).

If you want reference