1

How can i do indexing of a 2D array column wise. For example-

array([[ 0,  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, 31, 32, 33, 34],
   [35, 36, 37, 38, 39],
   [40, 41, 42, 43, 44],
   [45, 46, 47, 48, 49]])

This is a 2D array. I can access to it column wise by using a[:,0] which will give me the first column. But if I want to read all column at a time and want to pick values for example

[5]

[10][15]

[20][25][37]

then it should pick the values like

20

45, 21

46,22, 33

I know it must be easy. But i am learning the stuff.

1 Answer 1

2

If you want [5] to give 20, you must be starting to count from 1. Since Python starts counting from 0, that's a habit to break now: it'll only cause headaches.

I'm not sure what output format you want because numpy doesn't support ragged arrays, but maybe

>>> idx = np.array([5, 10, 15, 20, 25, 37])
>>> a.T.flat[idx-1]
array([20, 45, 21, 46, 22, 33])

would suffice? Here I had to take the transpose, view it as a flat array, and then subtract 1 from the indices to match the way you seem to be counting.

We can use a list instead of an array (but then we'd need to do a listcomp or something to subtract the 1s.) For example:

>>> a.T.flat[[4, 9, 14, 19, 24, 36]]
array([20, 45, 21, 46, 22, 33])
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your answer. the transpose, flat array is something new for me as I am learning still. I will try to understand them well.
Just to be clear, flat isn't a view but an iterator (albeit one that supports fancy indexing). You can return a genuine view by using ravel() if you want to play around with the array itself as a 1D object without making copies (or more generally, reshape()).
@HenryGomersall: ah, I wasn't even thinking about that. I just meant "view" as "think of it as"/"treat it as", which is an unfortunate choice of words given that "view" has a technical meaning in a numpy context.
@DSM :) I realise that, I just wanted Enamul to be clear since he mentioned not knowing about flat.

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.