Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

slicing numpy array to get nth column

Tags:

python

numpy

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)
like image 991
Georges Avatar asked Dec 07 '22 21:12

Georges


2 Answers

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])
like image 111
Divakar Avatar answered Dec 10 '22 11:12

Divakar


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]])

like image 28
magicleon94 Avatar answered Dec 10 '22 11:12

magicleon94