4

I am creating an array with linspace:

>> a = np.linspace(0, 4, 9)
>> a
>> array([0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. ])

I am resizing it succesfully as below:

>> a.resize(3, 3)
>> a
>> array([[0. , 0.5, 1. ],
       [1.5, 2. , 2.5],
       [3. , 3.5, 4. ]])

However, when I try to resize it as below:

a.resize(4, 2, refcheck=False)

This gives me the following error: ValueError: cannot resize this array: it does not own its data

When I create the same value array and resize it, array is resized succesfully:

>> b = np.array([0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. ])
>> b.resize(4, 2, refcheck=False)
>> b
>> array([[0. , 0.5],
       [1. , 1.5],
       [2. , 2.5],
       [3. , 3.5]])

Both of a and b are numpy.ndarray

My question: Why does resize() give this error when the array is created with linspace? When resized with 3x3 (and so used all elements of the array), it does not complain about ownership but why does it complain with 4x2 even if I use refcheck=False option?

I read the docs about linspace and resize but cannot find an answer about the reason.

0

1 Answer 1

2

If you inspect a.flags of an array created by np.linspace() you will see that OWNDATA is False. This means the array is a view of another array. You can use a.base to see that other array.

As for why np.linspace() produces arrays with OWNDATA=False, see the source code: https://github.com/numpy/numpy/blob/v1.19.0/numpy/core/function_base.py#L23-L165

The last part of the code does this:

return y.astype(dtype, copy=False)

The copy=False means the result is a view. To get an array with OWNDATA=True, you can use a.copy(). Then resize() with refcheck=False will work.

See also: Numpy, the array doesn't have its own data?

Sign up to request clarification or add additional context in comments.

2 Comments

@MadPhysicist, I think this answer is superior to the marked duplicate (though it's good to cite that SO). The resize method operate in-place, while the function returns a new array. The function result doesn't OWNDATA either, ending with a reshape. Despite the name, the resize method and function are worlds apart in execution.
@hpaulj: Thanks for your input, I have reopened the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.