next up previous contents index
Next: Using Python from SIC Up: NumPy basics Previous: Functions   Contents   Index

Subarrays and derivates

An important feature is that arrays that derive from numpy.ndarray are not copies: they still point to the memory area of the initial array.
>>> from numpy import zeros
>>> a = zeros((2,3))
>>> a
array([[0, 0, 0],
       [0, 0, 0]])
>>> b = a[0] # Subarray
>>> b
array([0, 0, 0])
>>> c = reshape(a,(6,)) # 1D version of 'a'
>>> c
array([0, 0, 0, 0, 0, 0])
>>> a[0,0] = 1
>>> b[1] = 2
>>> c[2] = 3
>>> a
array([[1, 2, 3],
       [0, 0, 0]])
>>> b
array([1, 2, 3])
>>> c
array([1, 2, 3, 0, 0, 0])

The array constructor (built-in function) array() can take an optional boolean argument copy which indicates if the above feature applies or not to the derived array:

>>> a = array((0,0,0))
>>> a
array([0, 0, 0])
>>> b = array(a,copy=True)  # A copy: does not share its data with 'a'
>>> c = array(a,copy=False) # Not a copy: shares its data with 'a'
>>> a[0] = 1
>>> b[1] = 2
>>> c[2] = 3
>>> a
array([1, 0, 3])
>>> b
array([0, 2, 0])
>>> c
array([1, 0, 3])



Gildas manager 2024-03-28