[Numpy-discussion] Fancy indexing question:
Ryan May
rmay31 at gmail.com
Tue Feb 24 15:13:00 EST 2009
On Tue, Feb 24, 2009 at 1:39 PM, Christopher Barker
<Chris.Barker at noaa.gov>wrote:
> 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
>
You need to listen more closely to the error message you get back. :) It's
a broadcasting issue, so why not try this:
a = np.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 = np.array([1, 3, 4]).reshape(-1,1)
j = np.array([1, 3])
a[i,j]
You need to make i,j conformable to the numpy broadcasting rules by manually
appending size 1 dimension.
Ryan
--
Ryan May
Graduate Research Assistant
School of Meteorology
University of Oklahoma
Sent from: Norman Oklahoma United States.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20090224/ff6ed22d/attachment.html>
More information about the NumPy-Discussion
mailing list