5

Having the example array below, how do you slice by column to get the following (e.g. 3rd column) [0, 0, ..., 1338, 1312, 1502, 0, ...] Looking for the most efficient way, thanks!

>>> r
array([[[   0,    0,    0],
        [   0,    0,    0],
        [   0,    0,    0],
        [   0,    0,    0],
        [   0,    0,    0],
        [   0,    0,    0]],

       [[   0,    0, 1338],
        [   0,    0, 1312],
        [   0,    0, 1502],
        [   0,    0,    0],
        [   0,    0,    0],
        [   0,    0,    0]],

       [[   0,    0, 1400],
        [   0,    0, 1277],
        [   0,    0, 1280],
        [   0,    0,    0],
        [   0,    0,    0],
        [   0,    0,    0]]], dtype=uint16)
3

2 Answers 2

13

For a generic ndarray of any dimensions, one way would be -

arr[...,n]

To get a flattened version, use .ravel() method -

arr[...,n].ravel()

Sample run -

In [317]: arr
Out[317]: 
array([[[[2, 1, 2],
         [0, 2, 3],
         [1, 0, 1]],

        [[0, 2, 0],
         [3, 1, 2],
         [3, 3, 1]]],


       [[[2, 0, 0],
         [0, 2, 3],
         [3, 3, 1]],

        [[2, 0, 1],
         [2, 3, 0],
         [3, 3, 2]]]])

In [318]: arr[...,2].ravel()
Out[318]: array([2, 3, 1, 0, 2, 1, 0, 3, 1, 1, 0, 2])
Sign up to request clarification or add additional context in comments.

Comments

2

Numpy supports the "semicolon notation" like matlab. In your case you should be able to take the third column by doing:
x = r[:,:,2]
and then
a = numpy.concatenate([x[0],x[1],x[2]])

1 Comment

You can use x.flatten() instead of numpy.concatenate([x[0],x[1],x[2]]).

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.