Hossam
Hossam

Reputation: 23

Extracting Columns from numpy array

Assuming I have a numpy array

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

and I want to access it row wise I can do

for row in A:
  print(row)

which results in me having

[1 2 3 4]
[5 6 7 8]

Is there a similar column wise method to access the array which will result in me having

[1 5]
[2 6]
[3 7]
[4 8]

I know I can use indices but, I just want to know if there is a way to access the array column wise without indices.

Thanks

Upvotes: 0

Views: 85

Answers (2)

Praveen
Praveen

Reputation: 7222

You could select the ith column of A, like so:

for i in range(A.shape[1]):
    print(A[:, i])

Upvotes: 0

Bi Rico
Bi Rico

Reputation: 25833

Transposing the array should get you what you want:

for item in A.T:
    print(item)

The T proprety is short for the transpose() method and returns a view on the array.

Upvotes: 2

Related Questions