Reputation: 49
Why is this code not working? I can't get this numpy array to resize correctly.
import numpy
a = numpy.zeros((10,10))
a[3,2] = 8
a.resize((5,5))
if a[3,2] == 8:
print "yay"
else:
print "not working"
raw_input()
Upvotes: 0
Views: 2468
Reputation: 1839
From the documentation, http://docs.scipy.org/doc/numpy/reference/generated/numpy.resize.html
numpy.resize(a, new_shape)
Return a new array with the specified shape.
If the new array is larger than the original array, then the new array is filled with repeated copies of a. Note that this behavior is different from a.resize(new_shape) which fills with zeros instead of repeated copies of a.
For the behavior you're expecting you need to manually copy the values you want the new array to keep, something like
a=a[:5,:5]
Upvotes: 3
Reputation: 353019
From the docs [help(a.resize)
]:
Shrinking an array: array is flattened (in the order that the data are
stored in memory), resized, and reshaped:
>>> a = np.array([[0, 1], [2, 3]], order='C')
>>> a.resize((2, 1))
>>> a
array([[0],
[1]])
In your case, [3,2]
is being stored at index 32 when considered as a flattened data list:
>>> a = numpy.zeros((10,10))
>>> a[3,2] = 8
>>> list(a.flat).index(8)
32
32 >= 25, so your change isn't surviving the resize. If you simply want to keep only a few of the values, then you could use
>>> a = a[:5, :5]
>>> a
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 8., 0., 0.],
[ 0., 0., 0., 0., 0.]])
>>> a[3,2]
8.0
or if you really wanted, you could copy the data over before a resize:
>>> a = numpy.zeros((10,10))
>>> a[3,2] = 8
>>> a.flat[:(5*5)] = a[:5, :5].flat
>>> a.resize((5,5))
>>> a[3,2]
8.0
but I don't quite see the point. [I can't remember how resize handles memory, but I wouldn't worry about it.]
Upvotes: 6