AleG
AleG

Reputation: 150

numpy: modifyng a transposed array don't work as expected

I have, from a more complex program, this code:

import numpy as np

ph=np.arange(6).reshape([2,3])
T=np.transpose(ph)
print 'T:\n',T
print 'ph:\n',ph              # printing arrays before for cycle
for i in range(0,len(T)):
  T[i]=2*T[i]
print 'ph:\n', ph             # printing arrays after for cycle
print 'T:\n',T

i expect to have in output T and

ph:
[[0 1 2]
 [3 4 5]]

instead, i have

ph:
[[ 0  2  4]
 [ 6  8 10]]
T:
[[ 0  6]
 [ 2  8]
 [ 4 10]]

So when i multiply *2 every line of T inside the for cicle, I am doing the same to ph. Why?

Upvotes: 1

Views: 107

Answers (2)

shx2
shx2

Reputation: 64318

transpose returns a view to the original array. To solve your problem, make a copy, like:

T=np.transpose(ph).copy()

Upvotes: 1

wim
wim

Reputation: 362716

You can find the reason in the docstring of np.transpose:

 Returns
 ------- p : ndarray
     `a` with its axes permuted.  A view is returned whenever
     possible.

Solution is to use T = ph.T.copy() if you don't want the view, but a copy.

Upvotes: 3

Related Questions