Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/Numpy subarray selection

I have some Numpy code which I'm trying to decipher. There's a line v1 = v1[:, a1.tolist()] which passes a numpy array a1 and converts it into a list. I'm confused as to what v1[:, a1.tolist()] actually does. I know that v1 is now being set to a column array given from v1 given by the selection [:, a1.tolist()] but what's getting selected? More precisely, what is [:, a.tolist()] doing?

like image 964
Black Avatar asked Jan 14 '15 06:01

Black


2 Answers

The syntax you observed is easier to understand if you split it in two parts:

1. Using a list as index

With numpy the meaning of

a[[1,2,3]]

is

[a[1], a[2], a[3]]

In other words when using a list as index is like creating a list of using elements as index.

2. Selecting a column with [:,x]

The meaning of

a2[:, x]

is

[a2[0][x],
 a2[1][x],
 a2[2][x],
 ...
 a2[n-1][x]]

I.e. is selecting one column from a matrix.

Summing up

The meaning of

a[:, [1, 3, 5]]

is therefore

[[a[ 0 ][1], a[ 0 ][3], a[ 0 ][5]],
 [a[ 1 ][1], a[ 1 ][3], a[ 1 ][5]],
               ...
 [a[n-1][1], a[n-1][3], a[n-1][5]]]

In other words a copy of a with a selection of columns (or duplication and reordering; elements in the list of indexes doesn't need to be distinct or sorted).

like image 95
6502 Avatar answered Oct 30 '22 14:10

6502


Assuming a simple example like a 2D array, v1[:, a1.tolist()] would selects all rows of v1, but only columns described by a1 values

Simple example:

>>> x
array([['a', 'b', 'c'],
       ['d', 'f', 'g']],
      dtype='|S1')

>>> x[:,[0]]
array([['a'],
       ['d']],
      dtype='|S1')
>>> x[:,[0, 1]]
array([['a', 'b'],
       ['d', 'f']],
      dtype='|S1')
like image 33
bakkal Avatar answered Oct 30 '22 14:10

bakkal