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?
The syntax you observed is easier to understand if you split it in two parts:
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.
[:,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.
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).
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With