[Numpy-discussion] Fancy indexing question:
Christopher Barker
Chris.Barker@noaa....
Tue Feb 24 13:39:39 CST 2009
HI all,
I'm having a bit of trouble getting fancy indexing to do what I want.
Say I have a 2-d array:
>>> a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]])
I want to extract a sub-array:
The 1st, 3rd, and 4th rows:
>>> i
[1, 3, 4]
and the 1st and 3rd columns:
>>> j
[1, 3]
so I should get a 3x2 array:
[[ 5, 7],
[13, 15],
[17, 19]]
The obvious (to me!) way to do this:
>>> a[i,j]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast to a single shape
fails.
I can do:
extract the rows:
>>> rows = a[i]
>>> rows
array([[ 4, 5, 6, 7],
[12, 13, 14, 15],
[16, 17, 18, 19]])
then the columns:
>>> sub_array = rows[:,j]
>>> sub_array
array([[ 5, 7],
[13, 15],
[17, 19]])
or, of course:
>>> sub_array = a[i][:,j]
>>> sub_array
array([[ 5, 7],
[13, 15],
[17, 19]])
however, it seems I am doing one more data copy and array creation than
I want -- can this be done as a single indexing operation?
thanks,
Chris
--
Christopher Barker, Ph.D.
Oceanographer
Emergency Response Division
NOAA/NOS/OR&R (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception
Chris.Barker@noaa.gov
More information about the Numpy-discussion
mailing list