When operating and manipulating arrays, their data is sometimes copied into a new array and sometimes not. (配列の演算や操作のとき、それらのデータは、新しい配列にコピーされる時もあればそうでない時もある。)
This is often a source of confusion for beginners. (これは時として初心者にとって混乱の元となる。)
There are three cases(3ケースある):
Simple assignments make no copy of array objects or of their data. (シンプルな代入では、配列オブジェクトもそれらのデータもコピーされない。)
import numpy as np
a = np.arange(12)
b = a # no new object is create 新しいオブジェクトを作らない
b is a # a and b are two names for the same ndarray object aとbは同じndarray objectを指す
True
b.shape = (3, 4) # changes the shape of a
a.shape
(3, 4)
Python passes mutable objects as references, so function calls make no copy. (Python は、書き換え可能なオブジェクトを参照を渡すため、 関数コールはコピーしない。)
def f(x):
print(id(x))
id(a) # id is a unique identifier of an object(id はオブジェクトのユニークな識別子)
1864188480048
f(a)
1864188480048
Different array objects can share the same data. (異なる配列オブジェクトが、同じデータを共有することができる。)
The view
method creates a new array object that looks at the same data.
(view
メソッドは、同じデータに見える新しい配列オブジェクトを作成する。)
c = a.view()
c is a
False
c.base is a # c is a view of the data owned by a (c は、a が所有しているデータのビュー)
True
c.flags.owndata
False
c.shape = (2, 6) # a's shape doesn't change
a.shape
(3, 4)
c[0, 4] = 1234 # a's data changes (a のデータは変更される)
a
array([[ 0, 1, 2, 3], [1234, 5, 6, 7], [ 8, 9, 10, 11]])
Slicing an array returns a view
of it
(配列をスライスすると、その view が返される):
s = a[ : , 1:3] # spaces added for clarity; could also be written "s = a[:,1:3]"
s
array([[ 1, 2], [ 5, 6], [ 9, 10]])
s[:] = 10 # s[:] is a view of s. Note the difference between s=10 and s[:]=10
s #(s[:] はs のview。s=10 と s[:]=10 の違いに注意。)
array([[10, 10], [10, 10], [10, 10]])
a # aのデータも書き換わる
array([[ 0, 10, 10, 3], [1234, 10, 10, 7], [ 8, 10, 10, 11]])
test = [1,2,3,4,5]
test
[1, 2, 3, 4, 5]
_slice = test[1:4]
_slice
[2, 3, 4]
_slice = [0,0,0]
_slice
[0, 0, 0]
test # pythonのlist は、sliceしても別オブジェクト
[1, 2, 3, 4, 5]
The copy
method makes a complete copy of the array and its data.
(copyメソッドは、配列とそのデータの完全なコピーを作る。)
d = a.copy() # a new array object with new data is created(dは新たに作成されたデータを持つ新たな配列オブジェクト)
d
array([[ 0, 10, 10, 3], [1234, 10, 10, 7], [ 8, 10, 10, 11]])
d is a
False
d.base is a # d doesn't share anything with a
False
d[0, 0] = 9999
d
array([[9999, 10, 10, 3], [1234, 10, 10, 7], [ 8, 10, 10, 11]])
a
array([[ 0, 10, 10, 3], [1234, 10, 10, 7], [ 8, 10, 10, 11]])
Here is a list of some useful NumPy functions and methods names ordered in categories. See Routines for the full list. (NumPy の関数およびメソッドのカテゴリ別一覧(name order)である。)