2

I'm new to python and numpy. Suppose I have an array A = np.random.rand(10,100) , how do i access some of its columns easily?

In Matlab I would write something like B = A(:,[2,4,6:10,50:80]). What is the equivalent of this line of code in Python?

I've looked at the examples in http://scipy.github.io/old-wiki/pages/NumPy_for_Matlab_Users.html but none of them answer my question.

3
  • 2
    See docs.scipy.org/doc/numpy/reference/arrays.indexing.html, and numpy.r_[] Commented Jun 22, 2016 at 19:51
  • Well, one way would be to use range to simulate the colon operation and then just index into cols : A[:,np.hstack((2,4,range(6,10+1),range(50,80+1)))]. Commented Jun 22, 2016 at 19:53
  • @Divakar I've actually also tried this way, but I believed there must be some method simpler than it :) Commented Jun 22, 2016 at 21:46

1 Answer 1

2

As Benjamin suggested, np.r_ handles an expression like this nicely

In [1329]: np.r_[2,4,6:10,50:80]
Out[1329]: 
array([ 2,  4,  6,  7,  8,  9, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
       61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
       78, 79])

which can be used as:

B = A[:, np.r_[2,4,6:10,50:80]]

r_ expands the slices into ranges and concatenates everything together, as in Divakar's comment.

Sign up to request clarification or add additional context in comments.

3 Comments

Ah didn't know that colon could be used within np.r_[], nice!
There are more features in r_ (and c_) than most of us need. I've never had to use the first argument string. The j step is just a cute way of using linspace instead of arange. If features are useful, great. But if you don't understand them, don't worry.
This is exactly the information I'm looking for. I believe the link Benjamin provides is a good knowledge base. For now it seems overwhelming to me. I'm still trying to understand r_[] and c_[]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.