7

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?

2 Answers 2

11

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

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

Comments

1

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

Comments

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.