IdentifiantMot de passe
Mot de passe oublié ?
9. Array Methods

# 9. Array Methods

As we discussed at the beginning of the last chapter, there are very few array methods for good reasons, and these all depend on the implementation details. They're worth knowing, though.

 argmax( axis=-1)
The argmax method returns the index of the largest element in a 1D array. In the case of a multi-dimensional array, it returns and array of indices.
```>>> array([1,2,4,3]).argmax()
2
>>> arange(100, shape=(10,10)).argmax()
array([9, 9, 9, 9, 9, 9, 9, 9, 9, 9])
```

 argmin( axis=-1)
The argmin method returns the index of the smallest element in a 1D array. In the case of a multi-dimensional array, it returns and array of indices.

 argsort( axis=-1)
The argsort method returns the array of indices which if taken from the array using take would return a sorted copy of the array. For multi-dimensional arrays, argsort computes the indices for each 1D subarray independently and aggregates them all into a single array result; The argsort of a multi-dimensional array does not produce a sorted copy of the array when applied directly to it using take; instead, each 1D subarray must be passed to take independently.
```  >>> array([1,2,4,3]).argsort()
array([0, 1, 3, 2])
>>> take([1,2,4,3], argsort([1,2,4,3]))
array([1, 2, 3, 4])
```

 astype( type)
The astype method returns a copy of the array converted to the specified type. As with any copy, the new array is aligned, contiguous, and in native machine byte order. If the specified type is the same as current type, a copy is still made.
```  >>> arange(5).astype('Float64')
array([ 0.,  1.,  2.,  3.,  4.])
```

 byteswap( )
The byteswap method performs a byte swapping operation on all the elements in the array, working inplace (i.e. it returns None). byteswap does not affect the array's byte order state variable. See togglebyteorder for changing the array's byte order state in addition to or rather than physically swapping bytes.
```>>> print a
[1 2 3]
>>> a.byteswap()
>>> print a
[16777216 33554432 50331648]
```

 byteswapped( )
The byteswapped method returns a byteswapped copy of the array. byteswapped does not affect the array's own byte order state variable. The result of byteswapped is logically in native byte order.
```>>> array([1,2,3]).byteswapped()
array([16777216, 33554432, 50331648])
```

 conjugate( )
The conjugate method returns the complex conjugate of an array.
```>>> (arange(3) + 1j).conjugate()
array([ 0.-1.j,  1.-1.j,  2.-1.j])
```

 copy( )
The copy method returns a copy of an array. When making an assignment or taking a slice, a new array object is created and has its own attributes, except that the data attribute just points to the data of the first array (a "view"). The copy method is used when it is important to obtain an independent copy. copy returns arrays which are contiguous, aligned, and not byteswapped, i.e. well behaved.
```>>> c = a[3:8:2].copy()
>>> print c.iscontiguous()
1
```

 diagonal( )
The diagonal method returns the diagonal elements of the array, those elements where the row and column indices are equal.
```>>> arange(25,shape=(5,5)).diagonal()
array([ 0,  6, 12, 18, 24])
```

 info( )
Calling an array's info method prints out information about the array which is useful for debugging.
```>>> arange(10).info()
class: <class 'numarray.numarraycore.NumArray'>
shape: (10,)
strides: (4,)
byteoffset: 0
bytestride: 4
itemsize: 4
aligned: 1
contiguous: 1
data: <memory at 0x08931d18 with size:0x00000028 held by object 0x3ff91bd8 aliasing object 0x00000000>
byteorder: little
byteswap: 0
type: Int32
```

 isaligned( )
isaligned returns 1 IFF the buffer address for an array modulo the array itemsize is 0. When the array itemsize exceeds 8 (sizeof(double)) aligment is done modulo 8.

 isbyteswapped( )
isbyteswapped returns 1 IFF the array's binary data is not in native machine byte order, possibly because it originated on a machine with a different native order.

 iscontiguous( )
iscontiguous returns 1 IFF an array is C-contiguous and 0 otherwise. An array is C-contiguous if its smallest stride corresponds to the innermost dimension and its other strides strictly increase in size from the innermost dimension to the outermost, with each stride being the product of the previous inner stride and shape. A non-contiguous array can be converted to a contiguous array by the copy method.
```>>> a=arange(25, shape=(5,5))
>>> a
array([[ 0,  1,  2,  3,  4],
[ 5,  6,  7,  8,  9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
>>> a.iscontiguous()
1
```

 is_c_array( )
is_c_array returns 1 IFF an array is C-contiguous, aligned, and not byteswapped, and returns 0 otherwise.
```>>> a=arange(25, shape=(5,5))
>>> a.is_c_array()
1
>>> a.is_f_array()
0
```

 is_fortran_contiguous( )
is_fortran_contiguous returns 1 IFF an array is Fortran-contiguous and 0 otherwise. An array is Fortran-contiguous if its smallest stride corresponds to its outermost dimension and each succesive stride is the product of the previous stride and shape element.
```>>> a=arange(25, shape=(5,5))
>>> a.transpose()
>>> a
array([[ 0,  5, 10, 15, 20],
[ 1,  6, 11, 16, 21],
[ 2,  7, 12, 17, 22],
[ 3,  8, 13, 18, 23],
[ 4,  9, 14, 19, 24]])
>>> a.iscontiguous()
0
>>> a.is_fortran_contiguous()
1
```

 is_f_array( )
is_f_array returns 1 IFF an array is Fortran-contiguous, aligned, and not byteswapped, and returns 0 otherwise.
```>>> a=arange(25, shape=(5,5))
>>> a.transpose()
>>> a.is_f_array()
1
>>> a.is_c_array()
0
```

 itemsize( )
The itemsize method returns the number of bytes used by any one of its elements.
```>>> a = arange(10)
>>> a.itemsize()
4
>>> a = array([1.0])
>>> a.itemsize()
8
>>> a = array([1], type=Complex64)
>>> a.itemsize()
16
```

 max( )
The max method returns the largest element in an array.
```>>> arange(100, shape=(10,10)).max()
99
```
 mean( )
The mean method returns the average of all elements in an array.
```>>> arange(10).mean() 4.5
```
 min( )
The min method returns the smallest element in an array.
```>>> arange(10).min()
0
```

 nelements( )
nelements returns the total number of elements in this array. Synonymous with size.
```>>> arange(100).nelements()
100
```

 new( type=None)
new returns a new array of the specified type with the same shape as this array. The new array is uninitialized.

 nonzero( axis=-1)
nonzero returns a tuple of arrays containing the indices of the elements that are nonzero.
```>>> arange(5).nonzero()
(array([1, 2, 3, 4]),)
>>> b = arange(9, shape=(3,3)) % 2; b
array([[0, 1, 0],
[1, 0, 1],
[0, 1, 0]])
>>>b.nonzero()
(array([0, 1, 1, 2]), array([1, 0, 2, 1]))
```

 repeat( r, axis=0)
The repeat method returns a new array with each element self[i] (along the specified axis) repeated r[i] times.
```>>> a=arange(25, shape=(5,5))
>>> a
array([[ 0,  1,  2,  3,  4],
[ 5,  6,  7,  8,  9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
>>> a.repeat(arange(5)%2*2)
array([[ 5,  6,  7,  8,  9],
[ 5,  6,  7,  8,  9],
[15, 16, 17, 18, 19],
[15, 16, 17, 18, 19]])
```

 resize( shape)
resize shrinks/grows the array to new shape, possibly replacing the underlying buffer object.
```>>> a = array([0, 1, 2, 3])
>>> a.resize(10)
array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1])
```

 size( )
size returns the total number of elements in this array. Synonymous with nelements.
```>>> arange(100).size()
100
```

 type( )
The type method returns the type of the array it is applied to. While we've been talking about them as Float32, Int16, etc., it is important to note that they are not character strings, they are instances of NumericType classes.
```>>> a = array([1,2,3])
>>> a.type()
Int32
>>> a = array([1], type=Complex64)
>>> a.type()
Complex64
```

 typecode( )
The typecode method returns the typecode character of the array it is applied to. typecode exists for backward compatibility with Numeric but the type method is preferred.
```>>> a = array([1,2,3])
>>> a.typecode()
'l'
>>> a = array([1], type=Complex64)
>>> a.typecode()
'D'
```

 tofile( file)
The tofile method writes the binary data of the array into file. If file is a Python string, it is interpreted as the name of a file to be created. Otherwise, file must be Python file object to which the data will be written.
```>>> a = arange(65,100)
>>> a.tofile('test.dat')   # writes a's binary data to file 'test.dat'.
>>> f = open('test2.dat', 'w')
>>> a.tofile(f)            # writes a's binary data to file 'test2.dat'
```
Note that the binary representation of array data depends on the platform, with some platforms being little endian (sys.byteorder == 'little') and others being big endian. The byte order of the array data is not recorded in the file, nor are the array's shape and type.

 tolist( )
Calling an array's tolist method returns a hierarchical python list version of the same array:
```>>> print a
[[65 66 67 68 69 70 71]
[72 73 74 75 76 77 78]
[79 80 81 82 83 84 85]
[86 87 88 89 90 91 92]
[93 94 95 96 97 98 99]]
>>> print a.tolist()
[[65, 66, 67, 68, 69, 70, 71], [72, 73, 74, 75, 76, 77, 78], [79, 80,
81, 82, 83, 84, 85], [86, 87, 88, 89, 90, 91, 92], [93, 94, 95, 96, 97,
98, 99]]
```

 tostring( )
The tostring method returns a string representation of the array data.
```>>> a = arange(65,70)
>>> a.tostring()
'A\x00\x00\x00B\x00\x00\x00C\x00\x00\x00D\x00\x00\x00E\x00\x00\x00'
```
Note that the arangement of the printable characters and interspersed NULL characters is dependent on machine architecture. The layout shown here is for little endian platform.

 transpose( axis=-1)
transpose re-shapes the array by permuting it's dimensions as specified by 'axes'. If 'axes' is none, transpose reverses the array's dimensions. transpose operates in-place and returns None.
```>>> a = arange(9, shape=(3,3))
>>> a.transpose()
>>> a
array([[0, 3, 6],
[1, 4, 7],
[2, 5, 8]])
```

 stddev( )
The stddev method returns the standard deviation of all elements in an array.
```>>> arange(10).stddev()
3.0276503540974917
```

 sum( )
The sum method returns the sum of all elements in an array.
```>>> arange(10).sum()
45
```

 swapaxes( axis1, axis2)
The swapaxes method adjusts the strides of an array so that the two specified axes appear to be swapped. swapaxes operates in place and returns None.
```>>> a = arange(25, shape=(5,5))
>>> a.swapaxes(0,1)
>>> a
array([[ 0,  5, 10, 15, 20],
[ 1,  6, 11, 16, 21],
[ 2,  7, 12, 17, 22],
[ 3,  8, 13, 18, 23],
[ 4,  9, 14, 19, 24]])
```

 togglebyteorder( )
The togglebyteorder method adjusts the byte order state variable for an array, with ``little'' being replaced by ``big'' and ``big'' being replaced by ``little''. togglebyteorder just reinterprets the existing data, it does not actually rearrange bytes.
```>>> a = arange(4)
>>> a.togglebyteorder()
>>> a
array([       0, 16777216, 33554432, 50331648])
```

 trace( )
The trace method returns the sum of the diagonal elements of an array.
```>>> a = arange(25, shape=(5,5))
>>> a.trace()
60
```

 view( )
The view method returns a new state object for an array but does not actually copy the array's data; views are used to reinterpret an existing data buffer by changing the array's properties.
```>>> a = arange(4)
>>> b = a.view()
>>> b.shape = (2,2)
>>> a
array([0, 1, 2, 3])
>>> b
array([[0, 1],
[2, 3]])
>>> a is b
False
>>> a._data is b._data
True
```

When using Python 2.2 or later, there are four public attributes which correspond to those of Numeric type objects. These are shape, flat, real, and imag (or imaginary). The following methods are used to implement and provide an alternative to using these attributes.

 getshape( )
 setshape( )
The getshape method returns the tuple that gives the shape of the array. setshape assigns its argument (a tuple) to the internal attribute which defines the array shape. When using Python 2.2 or later, the shape attribute can be accessed or assigned to, which is equivalent to using these methods.
```>>> a = arange(12)
>>> a.setshape((3,4))
>>> print a.getshape()
(3, 4)
>>> print a
[[ 0  1  2  3]
[ 4  5  6  7]
[ 8  9 10 11]]
```

 getflat( )
The getflat method is equivalent to using the flat attribute of Numeric. For compatibility with Numeric, there is no setflat method, although the attribute can in fact be set using setshape.
```>>> print a
[[ 0  1  2  3]
[ 4  5  6  7]
[ 8  9 10 11]]
>>> print a.getflat()
[ 0  1  2  3  4  5  6  7  8  9 10 11]
```

 getreal( )
 setreal( )
The getreal and setreal methods can be used to access or assign to the real part of an array containing imaginary elements.

 getimag( )
 getimaginary( )
 setimag( )
 setimaginary( )
The getimag and setimag methods can be used to access or assign to the imaginary part of an array containing imaginary elements. getimaginary is equivalent to getimag, and setimaginary is equivalent to setimag.

Send comments to the NumArray community.