[Numpy-discussion] numpy reference array
Chris Barker - NOAA Federal
chris.barker at noaa.gov
Wed Mar 13 20:50:20 EDT 2013
On Wed, Mar 13, 2013 at 6:56 AM, Matt U <mpuecker at mit.edu> wrote:
> Is it possible to create a numpy array which points to the same data in a
> different numpy array (but in different order etc)?
You can do this (easily), but only if the "different order" can be
defined in terms of strides. A simple example is a transpose:
In [3]: a = np.arange(12).reshape((3,4))
In [4]: a
Out[4]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [5]: b = a.T
In [6]: b
Out[6]:
array([[ 0, 4, 8],
[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11]])
# b is the transpose of a
# but a view on the same data block:
# change a:
In [7]: a[2,1] = 44
In [8]: a
Out[8]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 44, 10, 11]])
# b is changed, too.
In [9]: b
Out[9]:
array([[ 0, 4, 8],
[ 1, 5, 44],
[ 2, 6, 10],
[ 3, 7, 11]])
check out "stride tricks" for clever things you can do.
But numpy does require that the data in your array be a contiguous
block, in order, so you can't arbitrarily re-arrange it while keeping
a view.
HTH,
-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 at noaa.gov
More information about the NumPy-Discussion
mailing list