Numpy-copies-and-views

提供:Dev Guides
移動先:案内検索

NumPy-コピーとビュー

関数の実行中に、入力配列のコピーを返す関数と、ビューを返す関数があります。 コンテンツが物理的に別の場所に保存されている場合、それは*コピー*と呼ばれます。 一方、同じメモリコンテンツの別のビューが提供される場合、 View と呼びます。

コピーなし

単純な割り当てでは、配列オブジェクトのコピーは作成されません。 代わりに、元の配列と同じid()を使用してアクセスします。 * id()*は、Cのポインターに似たPythonオブジェクトのユニバーサル識別子を返します。

さらに、いずれかの変更が他方に反映されます。 たとえば、一方の形状が変化すると、他方の形状も変化します。

import numpy as np
a = np.arange(6)

print 'Our array is:'
print a

print 'Applying id() function:'
print id(a)

print 'a is assigned to b:'
b = a
print b

print 'b has same id():'
print id(b)

print 'Change shape of b:'
b.shape = 3,2
print b

print 'Shape of a also gets changed:'
print a

それは次の出力を生成します-

Our array is:
[0 1 2 3 4 5]

Applying id() function:
139747815479536

a is assigned to b:
[0 1 2 3 4 5]
b has same id():
139747815479536

Change shape of b:
[[Shape of a also gets changed:
[[View or Shallow Copy

NumPy has *ndarray.view() *method which is a new array object that looks at the same data of the original array. Unlike the earlier case, change in dimensions of the new array doesn’t change dimensions of the original.

==== Example

[source,prettyprint,notranslate]

import numpy as np#そもそも、aは3X2配列a = np.arange(6).reshape(3,2)

print 'Array a:' print a

print 'a:のビューを作成' b = a.view()print b

両方の配列のprint 'id()は異なります:' print 'id()of a:' print id(a)print 'id()of b:' print id(b)

#bの形状を変更します。 b.shape = 2,3の形状は変更しません

'bの形状:'印刷b

'Shape of a:'を印刷します

It will produce the following output −

[source,result,notranslate]

配列a:[[aのビューを作成:[[id()両方の配列は異なります:id()of a:140424307227264 id()of b:140424151696288

bの形状:[[aの形状:[[配列のスライスはビューを作成します。

import numpy as np
a = np.array([[print 'Our array is:'
print a

print 'Create a slice:'
s = a[:, :2]
print s

それは次の出力を生成します-

Our array is:
[[Create a slice:
[[Deep Copy

The* ndarray.copy()* function creates a deep copy. It is a complete copy of the array and its data, and doesn’t share with the original array.

==== Example

[source,prettyprint,notranslate]

numpy as np a = np.array([[print 'Array a is:' print a

print 'aのディープコピーを作成:' b = a.copy()print 'Array b is:' print b

  1. bは印刷のメモリを共有しません 'b is a can' write a b 'print b is a

print 'b:の内容を変更します' b [0,0] = 100

print 'Modified array b:' print b

印刷 'aは変わりません:'印刷

It will produce the following output −

[source,result,notranslate]

配列aは次のとおりです。[[aのディープコピーを作成:配列bは次のとおりです。

bの内容を変更します:変更された配列b:[[aは変更されないままです:[[