copy

という結果が得られる.ここでx is yはxとyが同一のメモリに取られているかを判定する.最初の例では単にxの実体にyという名前でも参照できるようになっただけなので,yを変えるとxも変わってしまう.一方,次の例ではnumpyの機能であるcopyを使って,別なメモリ領域にコピーを作っている.そうすることで,yを変えてもxが変わらなくなる.

をpythonで実行すると

x is y = True

x=0 y=0

x is y = False

x=1 y=0

x=np.array([1])

y=x.copy()

print 'x is y = %s'%(x is y)

y[0]=0

print 'x=%d y=%d'%(x[0],y[0])

import numpy as np

x=np.array([1])

y=x

print 'x is y = %s'%(x is y)

y[0]=0

print 'x=%d y=%d'%(x[0],y[0])

pythonの代入(=)は基本的に値を渡すのではなく,その右辺のメモリに左辺の名前でも参照できるようにすることであり,実体(メモリ上の値)は同一である.このため,一方を変えると他方も変わってしまって,ある種の操作には都合が悪い.これを避けるにはcopyを使う.たとえば,

The assignment "=" of python is basically not to pass a value but to make it possible to refer to the value of the right hand side name by the left hand side name like a symbolic link of linux. The entity (value on memory) is the same. Therefore, when the value of the one side is changed, the value of the other side is also changed. This is often inconvenient. To avoid this, use copy of numpy. For example, when you run the following source code of python

import numpy as np

x=np.array([1])

y=x

print 'x is y = %s'%(x is y)

y[0]=0

print 'x=%d y=%d'%(x[0],y[0])

x=np.array([1])

y=x.copy()

print 'x is y = %s'%(x is y)

y[0]=0

print 'x=%d y=%d'%(x[0],y[0])

You will get the following results

x is y = True

x=0 y=0

x is y = False

x=1 y=0

Here, 'is' in 'x is y' judges whether x and y are taken in the same memory position or not. In the first example, the entity of x and y are the same, and thus change of y results in change of x. On the other hand, in the following example, entity of x is copied to another memory area. By doing so, even if you change y, x will not change.