-1

Hi I am trying to slice 2 columns from a 2D numpy array but it seems that I can't get it without using a loop.
What am i missing? I am trying to get [3 7 11] and [4 8 12].

import numpy as np

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

a=np.reshape(a,(3,4))

print a[:,2] #vgives me [ 3  7 11]

The only way I can do it seems to be with a loop

for i in range(2,4):
    print a[:,i]

How can I do that with pure Numpy slicing?

1
  • if you want 2nd (0-based) column to the last column you can do a[:, 2:] elseif you want explicitly 2nd and 3rd columns, you can do a[:, 2:4] Commented Dec 12, 2018 at 22:58

1 Answer 1

2

The elements you are trying to get with this code:

for i in range(2,4):
    print a[:, i]

correspond to that:

print a[:, 2:4]
Sign up to request clarification or add additional context in comments.

4 Comments

This gives me [[3 4] [7 8] [11 12]], how can I get [3 7 11] and [4 8 12] ?
You have to transpose the result : a[:, 2:4].T
Thanks ! @AxelPuig that’s what I needed :)
Or a.T[2:4]..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.