Next / Previous / Contents / Shipman's homepage

5.6. Array methods

You may find these methods on ndarray instances to be useful.

A.astype(T)

Creates a new array with the elements from A, but as type T, where T is one of the dtype values discussed in Section 4, “Basic types”.

>>> s1 = np.arange(5, 10)
>>> print s1
[5 6 7 8 9]
>>> s2 = s1.astype(np.float_)
>>> print s2
[ 5.  6.  7.  8.  9.]
A.copy()

Creates a new ndarray as an exact copy of A.

>>> s3 = s2.copy()
>>> s2[2] = 73.88
>>> print s2
[  5.     6.    73.88   8.     9.  ]
>>> print s3
[ 5.  6.  7.  8.  9.]
A.reshape(dims)

Returns a new array that is a copy of the values A but having a shape given by dims.

>>> a1 = np.arange(0.0, 12.0, 1.0)
>>> print a1
[  0.   1.   2.   3.   4.   5.   6.   7.   8.   9.  10.  11.]
>>> a2 = a1.reshape( (2,6) )
>>> print a2
[[  0.   1.   2.   3.   4.   5.]
 [  6.   7.   8.   9.  10.  11.]]
A.resize(dims)

Changes the shape of array A, but does so in place.

print a1
[  0.   1.   2.   3.   4.   5.   6.   7.   8.   9.  10.  11.]
>>> a1.resize([2,6])
>>> print a1
[[  0.   1.   2.   3.   4.   5.]
 [  6.   7.   8.   9.  10.  11.]]
A.mean()

Returns the mean of the values in A.

A.var()

Returns the variance of the values in A.

>>> print a1.mean(), a1.var()
5.5 11.9166666667

There are many other array methods; these are just some of the more common ones.