[Numpy-discussion] numarray-->Numeric conversion?
Francesc Alted
falted at pytables.org
Mon Sep 13 02:09:02 CDT 2004
Hi,
I've been thinking in ways to convert from/to Numeric to numarray objects in
a non-expensive way. For the Numeric --> numarray there is an very easy way
to do that:
In [45]: num=Numeric.arange(10, typecode="i")
In [46]: na=numarray.array(buffer(num), typecode=num.typecode(),
shape=num.shape)
In [47]: na
Out[47]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
that creates a new numarray object without a memory copy
In [48]: num[2]=3
In [49]: num
Out[49]: array([0, 1, 3, 3, 4, 5, 6, 7, 8, 9],'i')
In [50]: na
Out[50]: array([0, 1, 3, 3, 4, 5, 6, 7, 8, 9])
i.e. both num (Numeric) and na (numarray) arrays shares the same memory. If
you delete one reference:
In [51]: del num
the other is still accessible
In [52]: na
Out[52]: array([0, 1, 3, 3, 4, 5, 6, 7, 8, 9])
However, it seems that it is not so easy to go the other way, that is
convert a numarray object to a Numeric without a memory copy. It seems that
Numeric.array constructor get the shape from the sequence object that is
passed, while numarray approach seems more sofisticated in the sense that if
it detects that the first argument is a buffer sequence, you must specify
the shape on the constructor.
Anyone knows if building a Numeric from a buffer (specifying both type and
shape) is possible (I mean, at Python level) at all?. If that would be the
case, adapting libraries that use Numeric to numarray objects and vice-versa
would be very easy and cheap (in terms of memory access).
--
Francesc Alted
More information about the Numpy-discussion
mailing list