Python/Numpy subarray selection
Solution 1
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).
Solution 2
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')
Related videos on Youtube
Black
Updated on October 06, 2022Comments
-
Black over 1 year
I have some Numpy code which I'm trying to decipher. There's a line
v1 = v1[:, a1.tolist()]
which passes a numpy arraya1
and converts it into a list. I'm confused as to whatv1[:, a1.tolist()]
actually does. I know thatv1
is now being set to a column array given fromv1
given by the selection[:, a1.tolist()]
but what's getting selected? More precisely, what is[:, a.tolist()]
doing? -
Black over 9 yearsThank you for the explanation.