Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Numpy memory layout

Tags:

python

numpy

I am trying to run a code

import numpy as np
a = np.zeros((3,2))
b = a.T.reshape(3*2)
b[0] = 99
a
array([[0,0],
       [0,0],
       [0,0]])

The question here is that the reshape function in numpy return a view of the original array and if any changes occurs in view object or in main object would be propogated throughout the views and main object.

But in the above stated case it is not happening. Please explain.

like image 812
Mayank Avatar asked Dec 20 '25 22:12

Mayank


2 Answers

The last reshape you are doing can't be expressed in strides in the original memory layout:

orig                  1 2  3 4  5 6  ok, strides 2, 1

transpose             1 3 5  2 4 6   ok, strides 1, 2

reshaped transpose    1 3 5 2 4 6    impossible

I'm not 100% sure I understand this correctly (or, more precisely, I'm almost 100% sure I don't), but there may be some obscure cases when a copy writes back. In any case, this is not one of them.

like image 158
Paul Panzer Avatar answered Dec 22 '25 10:12

Paul Panzer


The official document gives an answer to your question.

This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

like image 36
Wasi Ahmad Avatar answered Dec 22 '25 11:12

Wasi Ahmad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!