473,765 Members | 2,010 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

NumArray array-indexing

(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,1 0), 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(trans pose(x)[i]):\n",
transpose(trans pose(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(trans pose(x)[i]):
[[2 3]
[5 6]
[8 9]]
(G) Wish x[transpose(i)] would work, but alas:
[[4 5 6]
[7 8 9]]
Jul 18 '05 #1
6 2745
On 12 Aug 2004, Michael Drumheller wrote:
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*.
You can do this using slices, like so:
from numarray import *
a = array([[1, 2], [3, 4]])
a[:,1] array([2, 4])

':' means 'take all values along this axis', just like how with standard
Python lists it means 'take all values in the list'.
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?


False. You have to supply numarray with a two-dimensional array in order
to perform a two-dimensional transpose:
transpose([[1, 2, 3]])

array([[1],
[2],
[3]])

Jul 18 '05 #2
On Thu, 12 Aug 2004, Christopher T King wrote:
On 12 Aug 2004, Michael Drumheller wrote:
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?


False. You have to supply numarray with a two-dimensional array in order
to perform a two-dimensional transpose:


Where by "False" I meant "The first sentence is false, but the second
sentence is true". Column vectors and row vectors must be represented as
two-dimensional arrays; transpose() of a one-dimensional array is a no-op
since all transpose() does (by default) is reverse the order of the axes.

Jul 18 '05 #3
Christopher T King <sq******@WPI.E DU> wrote in message news:<Pi******* *************** *************** @ccc8.wpi.edu>. ..
On 12 Aug 2004, Michael Drumheller wrote:
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*.


You can do this using slices, like so:
from numarray import *
a = array([[1, 2], [3, 4]])
a[:,1]

array([2, 4])

':' means 'take all values along this axis', just like how with standard
Python lists it means 'take all values in the list'.


But that just gets me *one* column. I was trying to extract
an arbitrary subset of columns. Like I pointed out in the example
code I gave, this is trivial get take(), but does not seem to
be trivial with array indexing (and impossible with slicing).
Mike
Jul 18 '05 #4
Christopher T King <sq******@WPI.E DU> wrote in message news:<Pi******* *************** *************** @ccc8.wpi.edu>. ..
On Thu, 12 Aug 2004, Christopher T King wrote:
On 12 Aug 2004, Michael Drumheller wrote:
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?


False. You have to supply numarray with a two-dimensional array in order
to perform a two-dimensional transpose:


Where by "False" I meant "The first sentence is false, but the second
sentence is true". Column vectors and row vectors must be represented as
two-dimensional arrays; transpose() of a one-dimensional array is a no-op
since all transpose() does (by default) is reverse the order of the axes.


I understand that, but I think it just goes to support my contention that
NumArray does not support transposed vectors *from an array-indexing point
of view.* Here is what I mean:

As you pointed out in your previous message, you can get "the transpose
of a row vector" if the "row vector" is actually a single-row matrix,
i.e.,
transpose([[1, 2, 3]])

array([[1],
[2],
[3]])

However, whereas [1, 2, 3] passed as an index-array will get you the
second, third, and fourth rows of a rank-2 matrix, [[1,2,3]] will *not*
do that. (It gets you some other weird thing that I can't remember.)
That is, a single-row matrix may be the same thing as a row vector
in a mathematical context, but it is not the same thing in an
array-indexing context. Similarly, passing [[1],
[2],
[3]]
as an index array doesn't get you anything remotely like the second
third, and fourth columns. So it seems to me that array indexing
can easily get you an arbitrary subset of rows, but not an arbitrary
subset of columns. Would you agree?
By the way: Thank you for your attention to my problem!
Mike
Jul 18 '05 #5
Michael Drumheller wrote:
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


Could it be you are looking for the Ellipsis (...)?
a = numarray.array( range(9), shape=[3,3])
a array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
a[0:2] array([[0, 1, 2],
[3, 4, 5]]) a[..., 1] array([1, 4, 7]) a[..., 1:] array([[1, 2],
[4, 5],
[7, 8]]) a[..., 0:3:2] array([[0, 2],
[3, 5],
[6, 8]])

Of course in 2D you do not really need it:
a[:, :2] array([[0, 1],
[3, 4],
[6, 7]])
But at some point it may make things clearer:
a = numarray.array( range(2**10), shape=[2]*10)
a[...,:][(-1,)*7]

array([[[1016, 1017],
[1018, 1019]],

[[1020, 1021],
[1022, 1023]]])

Peter

Jul 18 '05 #6
On 16 Aug 2004, Michael Drumheller wrote:
However, whereas [1, 2, 3] passed as an index-array will get you the
second, third, and fourth rows of a rank-2 matrix, [[1,2,3]] will *not*
do that. (It gets you some other weird thing that I can't remember.)
That is, a single-row matrix may be the same thing as a row vector
in a mathematical context, but it is not the same thing in an
array-indexing context. Similarly, passing [[1],
[2],
[3]]
as an index array doesn't get you anything remotely like the second
third, and fourth columns. So it seems to me that array indexing
can easily get you an arbitrary subset of rows, but not an arbitrary
subset of columns. Would you agree?


Forgive the poor flow of the following; I've rewritten it a couple of
times.

Think about what you're trying to do for a second. You want to pass a
list of indices to extract along a given axis. You need three pieces of
information to do this: which indices, which axis, and possibly the
geometry of the output vector. You're supplying the wrong information;
you're supplying which indices, and a geometry. Matlab guesses the right
information (which axis) from the wrong information (the geometry).

When you index a 2-dimensional array in Matlab, what happens? If the
index array is a row vector, then the indices you supply index the first
dimension. If the index array is a column vector, then the indices index
the second dimension. But what if the index array is two-dimensional?
Which dimension should the indices index? (For the record, they seem to
index the second dimension.)

numarray, on the other hand, provides an exact mechanism for supplying
index arrays thusly:
a=array([[1,2,3],[4,5,6],[7,8,9]])
a[[1,2],[0,0]] array([4,7])

In this example, [1,2] are the row indices, and [0,0] are the column
indices (the information Matlab guesses for you). You can abbreviate
[0,0] as just 0:
a[[1,2],0] array([4,7])

(try the previous in Matlab; you will get similar results)

You can index along another column vector if you want:
a[[1,2],1] array([5,8])

Or you can arbitrarily index both dimensions (AFAICT, something not
possible in Matlab):
a[[1,2],[0,1]] array([4,8])

Note that doing the above in Matlab results in a 2x2 matrix, probably not
what was wanted. The explicit numarray equivalent to that Matlab
construction is a[[[1],[2]],[[0,1]]].

Note also that the output vector takes the shape of the index vector:
a[[[1,2]],0] array([[4,7]]) a[[[1],[2]],0]

array([[4],
[7]])

So the answer to your question is, yes, not only can you use arbitrary
array indices in numarray, they're more powerful than the Matlab
equivalent. Yet another reason why explicit is better than implicit.

Jul 18 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2991
by: RJS | last post by:
Hi all, I can't get a py2exe compiled app to run with numarray (numarray-0.5.win32- py2.2). Also wxPythonWIN32-2.3.3.1-Py22 and ActivePython-2.2.1-222. In the sample below, commenting out "import numarray" allows the exe to run. Left in, I get "4.exe has generated errors" etc. I'm going around and around and there isn't much on Google. py2exe output is last.
4
1987
by: Marco Bubke | last post by:
Hi I have tried to include numarray in Pyrex but I get allways this error: Traceback (most recent call last): File "gears.py", line 9, in ? import gl File "/home/marco/projects/test_pyrex/gl.pyx", line 40, in gl ctypedef class numarray.NumArray :
4
1990
by: Marco Bubke | last post by:
Hi Ok, I get a reproduceable seqmentation fault. Ok, fist the code: cdef NumArray array_to_double(NumArray array): # maybe here is memoty leak! cdef NumArray flat_array_obj flat_array_obj = NA_InputArray(NA_updateDataPtr(array), tFloat64,
2
2970
by: Marc Schellens | last post by:
Following the NumPy documentation, I took over some C code, but run into an error. Does anybody have a suggestion? Thanks, marc gdlpython.cpp:225: `PyArray_Type' undeclared (first use this function) #include <python2.3/Python.h>
3
1600
by: SunX | last post by:
I tried to initialize a float point array by: import numarray xur = numarray.fromfunction(lambda x,y,z:x*y*z, (2, 2, 2)) but I ended up with an integer array even though x, y, and z are all floats. BTW, how do you unzip NumTut in windows? And is there a newer version? Thank you
11
1991
by: grv | last post by:
So it is supposed to be very fast to have an array of say 5 million integers stored in a binary file and do a = numarray.fromfile('filename', (2, 2, 2)) numarray.add(a, 9, a) but how is that faster than reading the entire file into memory and then having a for loop in C: (loop over range) { *p++ += 9 }
3
1558
by: Mizrandir | last post by:
I'd like to subclass numarray's array. I'd like to add some methods and override others like __init__. I don't know how to do this and haven't found help searching the manual or the web, can someone help? For example imagine I just want to do something as simple as making a subclass "NewClass" with the __init__ method overridden so that the behaviour would be: >>> a = NewClass(2) >>> print a
4
3142
by: Ben Champion | last post by:
I have installed python 2.3.3 on my windows machine have have ran several programs succesfully. I have also installed numarray 1.1 for my version of python and am now trying to create arrays using the array command, eg >>>Import Numeric >>> a = array() Traceback (most recent call last): File "<pyshell#1>", line 1, in -toplevel-
1
3213
by: Chris P. | last post by:
Hi. I have a very simple task to perform and I'm having a hard time doing it. Given an array called 'x' (created using the numarray library), is there a single command that rounds each of its elements to the nearest integer? I've already tried something like >>> x_rounded = x.astype(numarray.Int) but that only truncates each element (i.e. '5.9' becomes '5'). I've read over all the relevant numarray documentation, and it
0
1246
by: andrewfelch | last post by:
Below is the code to/from Boolean arrays and Unsigned integers. On my Pentium 4, functions such as "bitwise_and" are 32 times faster when run on 32-bit integers instead of the entire-byte-consuming-Boolean. Good luck all:-) uint32Mask = numarray.array(, numarray.UInt32) uint32MaskInner = numarray.copy.deepcopy(uint32Mask) uint32MaskInner.shape =
0
9399
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10163
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10007
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9957
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7379
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5276
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.