Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError resizing an ndarray

I have a small python script, and I always run into an error:

ValueError: cannot resize an array references or is referenced
by another array in this way.  Use the resize function

Code:

points = comp.findall('Points')              # comp is a parsed .xml
diffvals = np.arange(10, dtype=float)
diffvals.resize(len(points),8)

But there are two things I do not understand:

  1. I only get this error when I use debugger.
  2. I have another script with identical code, and everything works fine. I checked this with debugger, all values, data types and so on are identical (except the memory addresses of course)

I have no idea what I could possibly do to resolve this.

like image 457
PKlumpp Avatar asked Jun 04 '14 10:06

PKlumpp


2 Answers

You cannot resize NumPy arrays that share data with another array in-place using the resize method by default. Instead, you can create a new resized array using the np.resize function:

np.resize(a, new_shape)

or you can disable reference checking using:

a.resize(new_shape, refcheck=False)

The likely reason you are only seeing it with a debugger is that the debugger references the array to e.g. print it. Also, the debugger may not store references to temporary arrays before you assign them into a variable, which probably explains why the other script works.

like image 72
otus Avatar answered Nov 11 '22 18:11

otus


Use

a = a.copy()

before resizing

like image 29
Shahnawaz Akhtar Avatar answered Nov 11 '22 18:11

Shahnawaz Akhtar