Reputation: 614
How do I store data into a numpy view without changing the view
into a copy
? This code snippet examplifies my question:
>>> import numpy as np
>>> #-- init arrays and view
>>> a = np.ones([4])
>>> z = np.zeros([2,4])
>>> z0 = z[0,:] #-- view
>>> z0.flags.owndata
False
>>> #-- This works!
>>> #-- modify view in-place
>>> np.add(a,z0,z0)
>>> z0.flags.owndata
False
>>> z
array([[ 1., 1., 1., 1.],
[ 0., 0., 0., 0.]])
>>> #-- reinit arrays and view
>>> z = np.zeros([2,4])
>>> z0 = z[0,:] #-- view
>>> #-- This does NOT work!
>>> #-- store data into view
>>> z0 = a
>>> z0.flags.owndata
True
I know about in-place modifications using +=
-=
*=
/=
and numpy functions that take an out
parameter, so you can do things like np.abs(x, x)
to take the absolute value of x
in-place.
But how to just store data into a view
without modification?
Abusing the add
function (to add zero and store) works but doesn't feel 'right':
np.add(a,0,z0)
Upvotes: 2
Views: 103
Reputation: 8975
When you do z0 = a
, then z0
is the same object as a
by python logic. What you want to do is this:
z0[...] = a
using the slicing syntax. Which uses the in-place __setitem__
python logic. On numpy 1.7. or later you could use np.copyto
as well, which is probably a little faster, but I like the slicing syntax personally.
Upvotes: 2