NumArray array-indexing
Michael Drumheller
drumheller at alum.mit.edu
Thu Aug 12 19:58:29 CEST 2004
(If you're not interested in NumArray, please skip this message.)
I am new to NumArray and I wonder if someone can help me with
array-indexing. Here's the basic situation: Given a rank-2 array
(i.e., a matrix) it seems to be trivial, with array indexing,
to extract a subset of its *columns*. But it does not seem
to be trivial to extract a subset of its *rows*. The code
snippet below describes the problem (if it really is a problem)
in detail. Note that the "problem" has an obvious, quick
solution via take(), but I wish it could be done with
the much more compact method of array indexing. I hope
my little snippet conveys what I'm after.
Basically, it seems to me that NumArray simply does not support
the distinction between a column vector and a row vector. That
is, if you have x=[1,2,3], then transpose(x) is a no-op. True?
(Note that doing x.shape=[3,1] does not do what I want; it produces
an awkward object that does not have the desired effect from
an array-indexing point of view.) Does this strike anyone
else as a rather serious limitation for someone (like me)
who would love to use Python/NumArray for my daily math
instead of, say, Matlab?
Thank you.
Mike D.
-----------------------cut here-----------------------------
Demo snippet:
from numarray import *
x = array(range(1,10), type=None, shape=[3,3])
print "(A) Original 3x3 array:\n", x
i = [1,2]
print "(B) An index set:\n", i
print "(C) 2nd and 3rd rows of x w/ take(x, i, 0):\n", take(x, i, 0)
print "(D) 2nd and 3rd cols of x w/ take(x, i, 1):\n", take(x, i, 1)
print "(E) 2nd and 3rd rows of x w/ x[i]:\n", x[i]
print "(F) 2nd and 3rd rows of x w/ transpose(transpose(x)[i]):\n",
transpose(transpose(x)[i])
print "(G) Wish x[transpose(i)] would work, but alas:\n",
x[transpose(i)]
It has this output:
(A) Original 3x3 array:
[[1 2 3]
[4 5 6]
[7 8 9]]
(B) An index set:
[1, 2]
(C) 2nd and 3rd rows of x w/ take(x, i, 0):
[[4 5 6]
[7 8 9]]
(D) 2nd and 3rd cols of x w/ take(x, i, 1):
[[2 3]
[5 6]
[8 9]]
(E) 2nd and 3rd rows of x w/ x[i]:
[[4 5 6]
[7 8 9]]
(F) 2nd and 3rd rows of x w/ transpose(transpose(x)[i]):
[[2 3]
[5 6]
[8 9]]
(G) Wish x[transpose(i)] would work, but alas:
[[4 5 6]
[7 8 9]]
More information about the Python-list
mailing list