[Numpy-discussion] Quick Question about Optimization

Eric Firing efiring at hawaii.edu
Tue May 20 21:16:07 EDT 2008


James Snyder wrote:
>> Well, if you do f = a[n, :], you would get a view, another object that
>> shares the data in memory with a but is a separate object.
> 
> OK, so it is a new object, with the properties of the slice it
> references, but if I write anything to it, it will consistently go
> back to the same spot in the original array.
> 
> In general, if I work on that, and don't do something that allocates a
> new set of memory locations for that, it will reference the same
> memory location.
> 
> If I do:
> a = np.zeros((20,30))
> b = a[2,:]
> 
> b += 1 # will add 1 to the original slice
> 
> b.resize will fail...
> 
> b = np.zeros((1,30)) # allocates new memory and disconnects the view
> 
> The appropriate way to zero out the original memory locations would be
> to do something like b *= 0?

or, from fastest to slowest:

b.fill(0)
b.flat = 0
b[:] = 0


Eric



More information about the NumPy-Discussion mailing list