| |
- object
-
- MaskedRecords(MaskedArray, object)
- MaskedRecords(MaskedArray, object)
- MaskedArray(ndarray)
-
- MaskedRecords(MaskedArray, object)
- MaskedRecords(MaskedArray, object)
class MaskedRecords(MaskedArray, object) |
|
*IVariables*:
_data : {recarray}
Underlying data, as a record array.
_mask : {boolean array}
Mask of the records. A record is masked when all its fields are masked.
_fieldmask : {boolean recarray}
Record array of booleans, setting the mask of each individual field of each record.
_fill_value : {record}
Filling values for each field. |
|
- Method resolution order:
- MaskedRecords
- MaskedArray
- ndarray
- object
Methods defined here:
- __array_finalize__(self, obj)
- #......................................................
- __getattribute__(self, attr)
- __getitem__(self, indx)
- Returns all the fields sharing the same fieldname base.
The fieldname base is either `_data` or `_mask`.
- __getstate__(self)
- Return the internal state of the masked array, for pickling purposes.
- __len__(self)
- Returns the length
- __reduce__(self)
- Return a 3-tuple for pickling a MaskedArray.
- __repr__(self)
- Calculates the repr representation.
- __setattr__(self, attr, val)
- Sets the attribute attr to the value val.
- __setitem__(self, indx, value)
- Sets the given record to value.
- __setstate__(self, state)
- Restore the internal state of the masked array, for pickling purposes.
``state`` is typically the output of the ``__getstate__`` output, and is a
5-tuple:
- class name
- a tuple giving the shape of the data
- a typecode for the data
- a binary string for the data
- a binary string for the mask.
- __str__(self)
- Calculates the string representation.
- copy(self)
- Returns a copy of the masked record.
- harden_mask(self)
- Forces the mask to hard
- soften_mask(self)
- Forces the mask to soft
- tolist(self, fill_value=None)
- Copy the data portion of the array to a hierarchical python
list and returns that list.
Data items are converted to the nearest compatible Python
type. Masked values are converted to fill_value. If
fill_value is None, the corresponding entries in the output
list will be ``None``.
- view(self, dtype=None, type=None)
- Returns a view of the mrecarray.
Static methods defined here:
- __new__(cls, shape, dtype=None, buf=None, offset=0, strides=None, formats=None, names=None, titles=None, byteorder=None, aligned=False, mask=False, hard_mask=False, fill_value=None, keep_mask=True, copy=False, **options)
- #............................................
Methods inherited from MaskedArray:
- __add__(self, other)
- Add other to self, and return a new masked array.
- __array_wrap__(self, obj, context=None)
- Special hook for ufuncs.
Wraps the numpy array and sets the mask according to context.
- __deepcopy__(self, memo=None)
- __div__(self, other)
- Divide other into self, and return a new masked array.
- __eq__(self, other)
- Check whether other equals self elementwise
- __float__(self)
- Convert to float.
- __floordiv__(self, other)
- Divide other into self, and return a new masked array.
- __getslice__(self, i, j)
- x.__getslice__(i, j) <==> x[i:j]
Return the slice described by (i, j). The use of negative
indices is not supported.
- __iadd__(self, other)
- Add other to self in-place.
- __idiv__(self, other)
- Divide self by other in-place.
- __imul__(self, other)
- Multiply self by other in-place.
- __int__(self)
- Convert to int.
- __ipow__(self, other)
- Raise self to the power other, in place.
- __isub__(self, other)
- Subtract other from self in-place.
- __mul__(self, other)
- Multiply other by self, and return a new masked array.
- __ne__(self, other)
- Check whether other doesn't equal self elementwise
- __pow__(self, other)
- Raise self to the power other, masking the potential NaNs/Infs
- __radd__(self, other)
- Add other to self, and return a new masked array.
- __rmul__(self, other)
- Multiply other by self, and return a new masked array.
- __rsub__(self, other)
- Subtract other to self, and return a new masked array.
- __setmask__(self, mask, copy=False)
- Set the mask.
- __setslice__(self, i, j, value)
- x.__setslice__(i, j, value) <==> x[i:j]=value
Set the slice (i,j) of a to value. If value is masked, mask
those locations.
- __sub__(self, other)
- Subtract other to self, and return a new masked array.
- __truediv__(self, other)
- Divide other into self, and return a new masked array.
- all(self, axis=None, out=None)
- Check if all of the elements of `a` are true.
Performs a :func:`logical_and` over the given axis and returns the result.
Masked values are considered as True during computation.
For convenience, the output array is masked where ALL the values along the
current axis are masked: if the output would have been a scalar and that
all the values are masked, then the output is `masked`.
Parameters
----------
axis : {None, integer}
Axis to perform the operation over.
If None, perform over flattened array.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved
and it must be of the right shape to hold the output.
See Also
--------
all : equivalent function
Examples
--------
>>> np.ma.array([1,2,3]).all()
True
>>> a = np.ma.array([1,2,3], mask=True)
>>> (a.all() is np.ma.masked)
True
- anom(self, axis=None, dtype=None)
- Return the anomalies (deviations from the average) along the given axis.
Parameters
----------
axis : int, optional
Axis along which to perform the operation.
If None, applies to a flattened version of the array.
dtype : {dtype}, optional
Datatype for the intermediary computation.
If not given, the current dtype is used instead.
- any(self, axis=None, out=None)
- Check if any of the elements of `a` are true.
Performs a logical_or over the given axis and returns the result.
Masked values are considered as False during computation.
Parameters
----------
axis : {None, integer}
Axis to perform the operation over.
If None, perform over flattened array and return a scalar.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved
and it must be of the right shape to hold the output.
See Also
--------
any : equivalent function
- argmax(self, axis=None, fill_value=None, out=None)
- Returns array of indices of the maximum values along the given axis.
Masked values are treated as if they had the value fill_value.
Parameters
----------
axis : {None, integer}
If None, the index is into the flattened array, otherwise along
the specified axis
fill_value : {var}, optional
Value used to fill in the masked values. If None, the output of
maximum_fill_value(self._data) is used instead.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved
and it must be of the right shape to hold the output.
Returns
-------
index_array : {integer_array}
Examples
--------
>>> a = np.arange(6).reshape(2,3)
>>> a.argmax()
5
>>> a.argmax(0)
array([1, 1, 1])
>>> a.argmax(1)
array([2, 2])
- argmin(self, axis=None, fill_value=None, out=None)
- Return array of indices to the minimum values along the given axis.
Parameters
----------
axis : {None, integer}
If None, the index is into the flattened array, otherwise along
the specified axis
fill_value : {var}, optional
Value used to fill in the masked values. If None, the output of
minimum_fill_value(self._data) is used instead.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved
and it must be of the right shape to hold the output.
Returns
-------
{ndarray, scalar}
If multi-dimension input, returns a new ndarray of indices to the
minimum values along the given axis. Otherwise, returns a scalar
of index to the minimum values along the given axis.
Examples
--------
>>> x = np.ma.array(arange(4), mask=[1,1,0,0])
>>> x.shape = (2,2)
>>> print x
[[-- --]
[2 3]]
>>> print x.argmin(axis=0, fill_value=-1)
[0 0]
>>> print x.argmin(axis=0, fill_value=9)
[1 1]
- argsort(self, axis=None, fill_value=None, kind='quicksort', order=None)
- Return an ndarray of indices that sort the array along the
specified axis. Masked values are filled beforehand to
fill_value.
Parameters
----------
axis : int, optional
Axis along which to sort. If not given, the flattened array is used.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm.
order : list, optional
When `a` is an array with fields defined, this argument specifies
which fields to compare first, second, etc. Not all fields need be
specified.
Returns
-------
index_array : ndarray, int
Array of indices that sort `a` along the specified axis.
In other words, ``a[index_array]`` yields a sorted `a`.
See Also
--------
sort : Describes sorting algorithms used.
lexsort : Indirect stable sort with multiple keys.
ndarray.sort : Inplace sort.
Notes
-----
See `sort` for notes on the different sorting algorithms.
- astype(self, newtype)
- Returns a copy of the MaskedArray cast to given newtype.
Returns
-------
output : MaskedArray
A copy of self cast to input newtype.
The returned record shape matches self.shape.
Examples
--------
>>> x = np.ma.array([[1,2,3.1],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1.0 -- 3.1]
[-- 5.0 --]
[7.0 -- 9.0]]
>>> print x.astype(int32)
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
- clip(...)
- a.clip(a_min, a_max, out=None)
Return an array whose values are limited to ``[a_min, a_max]``.
Refer to `numpy.clip` for full documentation.
See Also
--------
numpy.clip : equivalent function
- compress(self, condition, axis=None, out=None)
- Return `a` where condition is ``True``.
If condition is a `MaskedArray`, missing values are considered
as ``False``.
Parameters
----------
condition : var
Boolean 1-d array selecting which entries to return. If len(condition)
is less than the size of a along the axis, then output is truncated
to length of condition array.
axis : {None, int}, optional
Axis along which the operation must be performed.
out : {None, ndarray}, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type will be cast if
necessary.
Returns
-------
result : MaskedArray
A :class:`MaskedArray` object.
Notes
-----
Please note the difference with :meth:`compressed` !
The output of :meth:`compress` has a mask, the output of
:meth:`compressed` does not.
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> x.compress([1, 0, 1])
masked_array(data = [1 3],
mask = [False False],
fill_value=999999)
>>> x.compress([1, 0, 1], axis=1)
masked_array(data =
[[1 3]
[-- --]
[7 9]],
mask =
[[False False]
[ True True]
[False False]],
fill_value=999999)
- compressed(self)
- Return a 1-D array of all the non-masked data.
Returns
-------
data : ndarray.
A new ndarray holding the non-masked data is returned.
Notes
-----
+ The result is NOT a MaskedArray !
Examples
--------
>>> x = array(arange(5), mask=[0]+[1]*4)
>>> print x.compressed()
[0]
>>> print type(x.compressed())
<type 'numpy.ndarray'>
- count(self, axis=None)
- Count the non-masked elements of the array along the given axis.
Parameters
----------
axis : int, optional
Axis along which to count the non-masked elements. If axis is None,
all the non masked elements are counted.
Returns
-------
result : MaskedArray
A masked array where the mask is True where all data are
masked. If axis is None, returns either a scalar ot the
masked singleton if all values are masked.
- cumprod(self, axis=None, dtype=None, out=None)
- Return the cumulative product of the elements along the given axis.
The cumulative product is taken over the flattened array by
default, otherwise over the specified axis.
Masked values are set to 1 internally during the computation.
However, their position is saved, and the result will be masked at
the same locations.
Parameters
----------
axis : {None, -1, int}, optional
Axis along which the product is computed. The default
(`axis` = None) is to compute over the flattened array.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator
where the elements are multiplied. If ``dtype`` has the value ``None`` and
the type of ``a`` is an integer type of precision less than the default
platform integer, then the default platform integer precision is
used. Otherwise, the dtype is the same as that of ``a``.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary.
Warnings
--------
The mask is lost if out is not a valid MaskedArray !
Returns
-------
cumprod : ndarray
A new array holding the result is returned unless out is specified,
in which case a reference to out is returned.
Notes
-----
Arithmetic is modular when using integer types, and no error is
raised on overflow.
- cumsum(self, axis=None, dtype=None, out=None)
- Return the cumulative sum of the elements along the given axis.
The cumulative sum is calculated over the flattened array by
default, otherwise over the specified axis.
Masked values are set to 0 internally during the computation.
However, their position is saved, and the result will be masked at
the same locations.
Parameters
----------
axis : {None, -1, int}, optional
Axis along which the sum is computed. The default (`axis` = None) is to
compute over the flattened array. `axis` may be negative, in which case
it counts from the last to the first axis.
dtype : {None, dtype}, optional
Type of the returned array and of the accumulator in which the
elements are summed. If `dtype` is not specified, it defaults
to the dtype of `a`, unless `a` has an integer dtype with a
precision less than that of the default platform integer. In
that case, the default platform integer is used.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary.
Warnings
--------
The mask is lost if out is not a valid :class:`MaskedArray` !
Returns
-------
cumsum : ndarray.
A new array holding the result is returned unless ``out`` is
specified, in which case a reference to ``out`` is returned.
Examples
--------
>>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0])
>>> print marr.cumsum()
[0 1 3 -- -- -- 9 16 24 33]
Notes
-----
Arithmetic is modular when using integer types, and no error is
raised on overflow.
- diagonal(...)
- a.diagonal(offset=0, axis1=0, axis2=1)
Return specified diagonals.
Refer to `numpy.diagonal` for full documentation.
See Also
--------
numpy.diagonal : equivalent function
- filled(self, fill_value=None)
- Return a copy of self, where masked values are filled with `fill_value`.
If `fill_value` is None, `self.fill_value` is used instead.
Notes
-----
+ Subclassing is preserved
+ The result is NOT a MaskedArray !
Examples
--------
>>> x = np.ma.array([1,2,3,4,5], mask=[0,0,1,0,1], fill_value=-999)
>>> x.filled()
array([1,2,-999,4,-999])
>>> type(x.filled())
<type 'numpy.ndarray'>
- flatten(...)
- a.flatten(order='C')
Return a copy of the array collapsed into one dimension.
Parameters
----------
order : {'C', 'F'}, optional
Whether to flatten in C (row-major) or Fortran (column-major) order.
The default is 'C'.
Returns
-------
y : ndarray
A copy of the input array, flattened to one dimension.
See Also
--------
ravel : Return a flattened array.
flat : A 1-D flat iterator over the array.
Examples
--------
>>> a = np.array([[1,2], [3,4]])
>>> a.flatten()
array([1, 2, 3, 4])
>>> a.flatten('F')
array([1, 3, 2, 4])
- get_fill_value(self)
- Return the filling value.
- get_imag(self)
- Returns the imaginary part.
- get_real(self)
- Returns the real part.
- ids(self)
- Return the addresses of the data and mask areas.
- iscontiguous(self)
- Is the data contiguous?
- max(self, axis=None, out=None, fill_value=None)
- Return the maximum along a given axis.
Parameters
----------
axis : {None, int}, optional
Axis along which to operate. By default, ``axis`` is None and the
flattened input is used.
out : array_like, optional
Alternative output array in which to place the result. Must
be of the same shape and buffer length as the expected output.
fill_value : {var}, optional
Value used to fill in the masked values.
If None, use the output of maximum_fill_value().
Returns
-------
amax : array_like
New array holding the result.
If ``out`` was specified, ``out`` is returned.
See Also
--------
maximum_fill_value
Returns the maximum filling value for a given datatype.
- mean(self, axis=None, dtype=None, out=None)
- Returns the average of the array elements along given axis.
Refer to `numpy.mean` for full documentation.
See Also
--------
numpy.mean : equivalent function'
- min(self, axis=None, out=None, fill_value=None)
- Return the minimum along a given axis.
Parameters
----------
axis : {None, int}, optional
Axis along which to operate. By default, ``axis`` is None and the
flattened input is used.
out : array_like, optional
Alternative output array in which to place the result. Must be of
the same shape and buffer length as the expected output.
fill_value : {var}, optional
Value used to fill in the masked values.
If None, use the output of `minimum_fill_value`.
Returns
-------
amin : array_like
New array holding the result.
If ``out`` was specified, ``out`` is returned.
See Also
--------
minimum_fill_value
Returns the minimum filling value for a given datatype.
- mini(self, axis=None)
- nonzero(self)
- Return the indices of the elements of a that are not zero
nor masked, as a tuple of arrays.
There are as many tuples as dimensions of a, each tuple
contains the indices of the non-zero elements in that
dimension. The corresponding non-zero values can be obtained
with ``a[a.nonzero()]``.
To group the indices by element, rather than dimension, use
instead: ``transpose(a.nonzero())``.
The result of this is always a 2d array, with a row for each
non-zero element.
- prod(self, axis=None, dtype=None, out=None)
- Return the product of the array elements over the given axis.
Masked elements are set to 1 internally for computation.
Parameters
----------
axis : {None, int}, optional
Axis over which the product is taken. If None is used, then the
product is over all the array elements.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator
where the elements are multiplied. If ``dtype`` has the value ``None``
and the type of a is an integer type of precision less than the default
platform integer, then the default platform integer precision is
used. Otherwise, the dtype is the same as that of a.
out : {None, array}, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type will be cast if
necessary.
Returns
-------
product_along_axis : {array, scalar}, see dtype parameter above.
Returns an array whose shape is the same as a with the specified
axis removed. Returns a 0d array when a is 1d or axis=None.
Returns a reference to the specified output array if specified.
See Also
--------
prod : equivalent function
Notes
-----
Arithmetic is modular when using integer types, and no error is raised
on overflow.
Examples
--------
>>> np.prod([1.,2.])
2.0
>>> np.prod([1.,2.], dtype=np.int32)
2
>>> np.prod([[1.,2.],[3.,4.]])
24.0
>>> np.prod([[1.,2.],[3.,4.]], axis=1)
array([ 2., 12.])
- product = prod(self, axis=None, dtype=None, out=None)
- Return the product of the array elements over the given axis.
Masked elements are set to 1 internally for computation.
Parameters
----------
axis : {None, int}, optional
Axis over which the product is taken. If None is used, then the
product is over all the array elements.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator
where the elements are multiplied. If ``dtype`` has the value ``None``
and the type of a is an integer type of precision less than the default
platform integer, then the default platform integer precision is
used. Otherwise, the dtype is the same as that of a.
out : {None, array}, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type will be cast if
necessary.
Returns
-------
product_along_axis : {array, scalar}, see dtype parameter above.
Returns an array whose shape is the same as a with the specified
axis removed. Returns a 0d array when a is 1d or axis=None.
Returns a reference to the specified output array if specified.
See Also
--------
prod : equivalent function
Notes
-----
Arithmetic is modular when using integer types, and no error is raised
on overflow.
Examples
--------
>>> np.prod([1.,2.])
2.0
>>> np.prod([1.,2.], dtype=np.int32)
2
>>> np.prod([[1.,2.],[3.,4.]])
24.0
>>> np.prod([[1.,2.],[3.,4.]], axis=1)
array([ 2., 12.])
- ptp(self, axis=None, out=None, fill_value=None)
- Return (maximum - minimum) along the the given dimension
(i.e. peak-to-peak value).
Parameters
----------
axis : {None, int}, optional
Axis along which to find the peaks. If None (default) the
flattened array is used.
out : {None, array_like}, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary.
fill_value : {var}, optional
Value used to fill in the masked values.
Returns
-------
ptp : ndarray.
A new array holding the result, unless ``out`` was
specified, in which case a reference to ``out`` is returned.
- put(self, indices, values, mode='raise')
- Set storage-indexed locations to corresponding values.
Sets self._data.flat[n] = values[n] for each n in indices.
If `values` is shorter than `indices` then it will repeat.
If `values` has some masked values, the initial mask is updated
in consequence, else the corresponding values are unmasked.
Parameters
----------
indices : 1-D array_like
Target indices, interpreted as integers.
values : array_like
Values to place in self._data copy at target indices.
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices will behave.
'raise' : raise an error.
'wrap' : wrap around.
'clip' : clip to the range.
Notes
-----
`values` can be a scalar or length 1 array.
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> x.put([0,4,8],[10,20,30])
>>> print x
[[10 -- 3]
[-- 20 --]
[7 -- 30]]
>>> x.put(4,999)
>>> print x
[[10 -- 3]
[-- 999 --]
[7 -- 30]]
- ravel(self)
- Returns a 1D version of self, as a view.
Returns
-------
MaskedArray
Output view is of shape ``(self.size,)`` (or
``(np.ma.product(self.shape),)``).
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> print x.ravel()
[1 -- 3 -- 5 -- 7 -- 9]
- raw_data(self)
- Return the _data part of the MaskedArray.
DEPRECATED: You should really use ``.data`` instead...
- repeat(...)
- a.repeat(repeats, axis=None)
Repeat elements of an array.
Refer to `numpy.repeat` for full documentation.
See Also
--------
numpy.repeat : equivalent function
- reshape(self, *s, **kwargs)
- Returns a masked array containing the data of a, but with a new shape.
The result is a view to the original array; if this is not possible,
a ValueError is raised.
Parameters
----------
shape : shape tuple or int
The new shape should be compatible with the original shape. If an
integer, then the result will be a 1D array of that length.
order : {'C', 'F'}, optional
Determines whether the array data should be viewed as in C
(row-major) order or FORTRAN (column-major) order.
Returns
-------
reshaped_array : array
A new view to the array.
Notes
-----
If you want to modify the shape in place, please use ``a.shape = s``
Examples
--------
>>> x = np.ma.array([[1,2],[3,4]], mask=[1,0,0,1])
>>> print x
[[-- 2]
[3 --]]
>>> x = x.reshape((4,1))
>>> print x
[[--]
[2]
[3]
[--]]
- resize(self, newshape, refcheck=True, order=False)
- Change shape and size of array in-place.
- round(self, decimals=0, out=None)
- a.round(decimals=0, out=None)
Return an array rounded a to the given number of decimals.
Refer to `numpy.around` for full documentation.
See Also
--------
numpy.around : equivalent function
- set_fill_value(self, value=None)
- Set the filling value to value.
If value is None, use a default based on the data type.
- shrink_mask(self)
- Reduce a mask to nomask when possible.
- sort(self, axis=-1, kind='quicksort', order=None, endwith=True, fill_value=None)
- Return a sorted copy of an array.
Parameters
----------
a : array_like
Array to be sorted.
axis : int or None, optional
Axis along which to sort. If None, the array is flattened before
sorting. The default is -1, which sorts along the last axis.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm. Default is 'quicksort'.
order : list, optional
When `a` is a structured array, this argument specifies which fields
to compare first, second, and so on. This list does not need to
include all of the fields.
endwith : {True, False}, optional
Whether missing values (if any) should be forced in the upper indices
(at the end of the array) (True) or lower indices (at the beginning).
fill_value : {var}
Value used to fill in the masked values. If None, use
the the output of minimum_fill_value().
Returns
-------
sorted_array : ndarray
Array of the same type and shape as `a`.
See Also
--------
ndarray.sort : Method to sort an array in-place.
argsort : Indirect sort.
lexsort : Indirect stable sort on multiple keys.
searchsorted : Find elements in a sorted array.
Notes
-----
The various sorting algorithms are characterized by their average speed,
worst case performance, work space size, and whether they are stable. A
stable sort keeps items with the same key in the same relative
order. The three available algorithms have the following
properties:
=========== ======= ============= ============ =======
kind speed worst case work space stable
=========== ======= ============= ============ =======
'quicksort' 1 O(n^2) 0 no
'mergesort' 2 O(n*log(n)) ~n/2 yes
'heapsort' 3 O(n*log(n)) 0 no
=========== ======= ============= ============ =======
All the sort algorithms make temporary copies of the data when
sorting along any but the last axis. Consequently, sorting along
the last axis is faster and uses less space than sorting along
any other axis.
Examples
--------
>>> a = np.array([[1,4],[3,1]])
>>> np.sort(a) # sort along the last axis
array([[1, 4],
[1, 3]])
>>> np.sort(a, axis=None) # sort the flattened array
array([1, 1, 3, 4])
>>> np.sort(a, axis=0) # sort along the first axis
array([[1, 1],
[3, 4]])
Use the `order` keyword to specify a field to use when sorting a
structured array:
>>> dtype = [('name', 'S10'), ('height', float), ('age', int)]
>>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
... ('Galahad', 1.7, 38)]
>>> a = np.array(values, dtype=dtype) # create a structured array
>>> np.sort(a, order='height') # doctest: +SKIP
array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
('Lancelot', 1.8999999999999999, 38)],
dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
Sort by age, then height if ages are equal:
>>> np.sort(a, order=['age', 'height']) # doctest: +SKIP
array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),
('Arthur', 1.8, 41)],
dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
- squeeze(...)
- a.squeeze()
Remove single-dimensional entries from the shape of `a`.
Refer to `numpy.squeeze` for full documentation.
See Also
--------
numpy.squeeze : equivalent function
- std(self, axis=None, dtype=None, out=None, ddof=0)
- Compute the standard deviation along the specified axis.
Returns the standard deviation, a measure of the spread of a distribution,
of the array elements. The standard deviation is computed for the
flattened array by default, otherwise over the specified axis.
Parameters
----------
a : array_like
Calculate the standard deviation of these values.
axis : int, optional
Axis along which the standard deviation is computed. The default is
to compute the standard deviation of the flattened array.
dtype : dtype, optional
Type to use in computing the standard deviation. For arrays of
integer type the default is float64, for arrays of float types it is
the same as the array type.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type (of the calculated
values) will be cast if necessary.
ddof : int, optional
Means Delta Degrees of Freedom. The divisor used in calculations
is ``N - ddof``, where ``N`` represents the number of elements.
By default `ddof` is zero.
Returns
-------
standard_deviation : {ndarray, scalar}; see dtype parameter above.
If `out` is None, return a new array containing the standard deviation,
otherwise return a reference to the output array.
See Also
--------
numpy.var : Variance
numpy.mean : Average
Notes
-----
The standard deviation is the square root of the average of the squared
deviations from the mean, i.e., ``std = sqrt(mean(abs(x - x.mean())**2))``.
The mean is normally calculated as ``x.sum() / N``, where
``N = len(x)``. If, however, `ddof` is specified, the divisor ``N - ddof``
is used instead. In standard statistical practice, ``ddof=1`` provides an
unbiased estimator of the variance of the infinite population. ``ddof=0``
provides a maximum likelihood estimate of the variance for normally
distributed variables. The standard deviation computed in this function
is the square root of the estimated variance, so even with ``ddof=1``, it
will not be an unbiased estimate of the standard deviation per se.
Note that, for complex numbers, std takes the absolute
value before squaring, so that the result is always real and nonnegative.
Examples
--------
>>> a = np.array([[1, 2], [3, 4]])
>>> np.std(a)
1.1180339887498949
>>> np.std(a, 0)
array([ 1., 1.])
>>> np.std(a, 1)
array([ 0.5, 0.5])
- sum(self, axis=None, dtype=None, out=None)
- Return the sum of the array elements over the given axis.
Masked elements are set to 0 internally.
Parameters
----------
axis : {None, -1, int}, optional
Axis along which the sum is computed. The default
(`axis` = None) is to compute over the flattened array.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator
where the elements are summed. If dtype has the value None and
the type of a is an integer type of precision less than the default
platform integer, then the default platform integer precision is
used. Otherwise, the dtype is the same as that of a.
out : {None, ndarray}, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary.
Returns
-------
sum_along_axis : MaskedArray or scalar
An array with the same shape as self, with the specified
axis removed. If self is a 0-d array, or if `axis` is None, a scalar
is returned. If an output array is specified, a reference to
`out` is returned.
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> print x.sum()
25
>>> print x.sum(axis=1)
[4 5 16]
>>> print x.sum(axis=0)
[8 5 12]
>>> print type(x.sum(axis=0, dtype=np.int64)[0])
<type 'numpy.int64'>
- swapaxes(...)
- a.swapaxes(axis1, axis2)
Return a view of the array with `axis1` and `axis2` interchanged.
Refer to `numpy.swapaxes` for full documentation.
See Also
--------
numpy.swapaxes : equivalent function
- take(...)
- a.take(indices, axis=None, out=None, mode='raise')
Return an array formed from the elements of a at the given indices.
Refer to `numpy.take` for full documentation.
See Also
--------
numpy.take : equivalent function
- tofile(self, fid, sep='', format='%s')
- #........................
- toflex(self)
- Transforms a MaskedArray into a flexible-type array with two fields:
* the ``_data`` field stores the ``_data`` part of the array;
* the ``_mask`` field stores the ``_mask`` part of the array;
Returns
-------
record : ndarray
A new flexible-type ndarray with two fields: the first element
containing a value, the second element containing the corresponding
mask boolean. The returned record shape matches self.shape.
Notes
-----
A side-effect of transforming a masked array into a flexible ndarray is
that meta information (``fill_value``, ...) will be lost.
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> print x.toflex()
[[(1, False) (2, True) (3, False)]
[(4, True) (5, False) (6, True)]
[(7, False) (8, True) (9, False)]]
- torecords = toflex(self)
- Transforms a MaskedArray into a flexible-type array with two fields:
* the ``_data`` field stores the ``_data`` part of the array;
* the ``_mask`` field stores the ``_mask`` part of the array;
Returns
-------
record : ndarray
A new flexible-type ndarray with two fields: the first element
containing a value, the second element containing the corresponding
mask boolean. The returned record shape matches self.shape.
Notes
-----
A side-effect of transforming a masked array into a flexible ndarray is
that meta information (``fill_value``, ...) will be lost.
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> print x.toflex()
[[(1, False) (2, True) (3, False)]
[(4, True) (5, False) (6, True)]
[(7, False) (8, True) (9, False)]]
- tostring(self, fill_value=None, order='C')
- Return a copy of array data as a Python string containing the raw bytes
in the array. The array is filled beforehand.
Parameters
----------
fill_value : {var}, optional
Value used to fill in the masked values.
If None, uses self.fill_value instead.
order : {string}
Order of the data item in the copy {'C','F','A'}.
'C' -- C order (row major)
'Fortran' -- Fortran order (column major)
'Any' -- Current order of array.
None -- Same as "Any"
Notes
-----
As for method:`ndarray.tostring`, information about the shape, dtype...,
but also fill_value will be lost.
- trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None)
- a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
Return the sum along diagonals of the array.
Refer to `numpy.trace` for full documentation.
See Also
--------
numpy.trace : equivalent function
- transpose(...)
- a.transpose(*axes)
Returns a view of 'a' with axes transposed. If no axes are given,
or None is passed, switches the order of the axes. For a 2-d
array, this is the usual matrix transpose. If axes are given,
they describe how the axes are permuted.
See Also
--------
ndarray.T : array property returning the array transposed
Examples
--------
>>> a = np.array([[1,2],[3,4]])
>>> a
array([[1, 2],
[3, 4]])
>>> a.transpose()
array([[1, 3],
[2, 4]])
>>> a.transpose((1,0))
array([[1, 3],
[2, 4]])
>>> a.transpose(1,0)
array([[1, 3],
[2, 4]])
- unshare_mask(self)
- Copy the mask and set the sharedmask flag to False.
- var(self, axis=None, dtype=None, out=None, ddof=0)
- Compute the variance along the specified axis.
Returns the variance of the array elements, a measure of the spread of a
distribution. The variance is computed for the flattened array by default,
otherwise over the specified axis.
Parameters
----------
a : array_like
Array containing numbers whose variance is desired. If `a` is not an
array, a conversion is attempted.
axis : int, optional
Axis along which the variance is computed. The default is to compute
the variance of the flattened array.
dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type
the default is float32; for arrays of float types it is the same as
the array type.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type is cast if
necessary.
ddof : int, optional
"Delta Degrees of Freedom": the divisor used in calculation is
``N - ddof``, where ``N`` represents the number of elements. By
default `ddof` is zero.
Returns
-------
variance : ndarray, see dtype parameter above
If out=None, returns a new array containing the variance; otherwise
a reference to the output array is returned.
See Also
--------
std : Standard deviation
mean : Average
Notes
-----
The variance is the average of the squared deviations from the mean,
i.e., ``var = mean(abs(x - x.mean())**2)``.
The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``.
If, however, `ddof` is specified, the divisor ``N - ddof`` is used
instead. In standard statistical practice, ``ddof=1`` provides an
unbiased estimator of the variance of the infinite population. ``ddof=0``
provides a maximum likelihood estimate of the variance for normally
distributed variables.
Note that for complex numbers, the absolute value is taken before
squaring, so that the result is always real and nonnegative.
Examples
--------
>>> a = np.array([[1,2],[3,4]])
>>> np.var(a)
1.25
>>> np.var(a,0)
array([ 1., 1.])
>>> np.var(a,1)
array([ 0.25, 0.25])
Data descriptors inherited from MaskedArray:
- T
- __dict__
- dictionary for instance variables (if defined)
- baseclass
- Class of the underlying data (read-only).
- data
- Return the current data, as a view of the original
underlying data.
- fill_value
- Filling value.
- flat
- Flat version of the array.
- hardmask
- Hardness of the mask
- imag
- Imaginary part.
- mask
- Mask
- real
- Real part
- recordmask
- Return the mask of the records.
A record is masked when all the fields are masked.
- sharedmask
- Share status of the mask (read-only).
Data and other attributes inherited from MaskedArray:
- __array_priority__ = 15
Methods inherited from ndarray:
- __abs__(...)
- x.__abs__() <==> abs(x)
- __and__(...)
- x.__and__(y) <==> x&y
- __array__(...)
- a.__array__(|dtype) -> reference if type unchanged, copy otherwise.
Returns either a new reference to self if dtype is not given or a new array
of provided data type if dtype is different from the current dtype of the
array.
- __contains__(...)
- x.__contains__(y) <==> y in x
- __copy__(...)
- a.__copy__([order])
Return a copy of the array.
Parameters
----------
order : {'C', 'F', 'A'}, optional
If order is 'C' (False) then the result is contiguous (default).
If order is 'Fortran' (True) then the result has fortran order.
If order is 'Any' (None) then the result has fortran order
only if the array already is in fortran order.
- __delitem__(...)
- x.__delitem__(y) <==> del x[y]
- __delslice__(...)
- x.__delslice__(i, j) <==> del x[i:j]
Use of negative indices is not supported.
- __divmod__(...)
- x.__divmod__(y) <==> divmod(x, y)
- __ge__(...)
- x.__ge__(y) <==> x>=y
- __gt__(...)
- x.__gt__(y) <==> x>y
- __hex__(...)
- x.__hex__() <==> hex(x)
- __iand__(...)
- x.__iand__(y) <==> x&y
- __ifloordiv__(...)
- x.__ifloordiv__(y) <==> x//y
- __ilshift__(...)
- x.__ilshift__(y) <==> x<<y
- __imod__(...)
- x.__imod__(y) <==> x%y
- __index__(...)
- x[y:z] <==> x[y.__index__():z.__index__()]
- __invert__(...)
- x.__invert__() <==> ~x
- __ior__(...)
- x.__ior__(y) <==> x|y
- __irshift__(...)
- x.__irshift__(y) <==> x>>y
- __iter__(...)
- x.__iter__() <==> iter(x)
- __itruediv__(...)
- x.__itruediv__(y) <==> x/y
- __ixor__(...)
- x.__ixor__(y) <==> x^y
- __le__(...)
- x.__le__(y) <==> x<=y
- __long__(...)
- x.__long__() <==> long(x)
- __lshift__(...)
- x.__lshift__(y) <==> x<<y
- __lt__(...)
- x.__lt__(y) <==> x<y
- __mod__(...)
- x.__mod__(y) <==> x%y
- __neg__(...)
- x.__neg__() <==> -x
- __nonzero__(...)
- x.__nonzero__() <==> x != 0
- __oct__(...)
- x.__oct__() <==> oct(x)
- __or__(...)
- x.__or__(y) <==> x|y
- __pos__(...)
- x.__pos__() <==> +x
- __rand__(...)
- x.__rand__(y) <==> y&x
- __rdiv__(...)
- x.__rdiv__(y) <==> y/x
- __rdivmod__(...)
- x.__rdivmod__(y) <==> divmod(y, x)
- __rfloordiv__(...)
- x.__rfloordiv__(y) <==> y//x
- __rlshift__(...)
- x.__rlshift__(y) <==> y<<x
- __rmod__(...)
- x.__rmod__(y) <==> y%x
- __ror__(...)
- x.__ror__(y) <==> y|x
- __rpow__(...)
- y.__rpow__(x[, z]) <==> pow(x, y[, z])
- __rrshift__(...)
- x.__rrshift__(y) <==> y>>x
- __rshift__(...)
- x.__rshift__(y) <==> x>>y
- __rtruediv__(...)
- x.__rtruediv__(y) <==> y/x
- __rxor__(...)
- x.__rxor__(y) <==> y^x
- __xor__(...)
- x.__xor__(y) <==> x^y
- byteswap(...)
- a.byteswap(inplace)
Swap the bytes of the array elements
Toggle between low-endian and big-endian data representation by
returning a byteswapped array, optionally swapped in-place.
Parameters
----------
inplace: bool, optional
If ``True``, swap bytes in-place, default is ``False``.
Returns
-------
out: ndarray
The byteswapped array. If `inplace` is ``True``, this is
a view to self.
Examples
--------
>>> A = np.array([1, 256, 8755], dtype=np.int16)
>>> map(hex, A)
['0x1', '0x100', '0x2233']
>>> A.byteswap(True)
array([ 256, 1, 13090], dtype=int16)
>>> map(hex, A)
['0x100', '0x1', '0x3322']
Arrays of strings are not swapped
>>> A = np.array(['ceg', 'fac'])
>>> A.byteswap()
array(['ceg', 'fac'],
dtype='|S3')
- choose(...)
- a.choose(choices, out=None, mode='raise')
Use an index array to construct a new array from a set of choices.
Refer to `numpy.choose` for full documentation.
See Also
--------
numpy.choose : equivalent function
- conj(...)
- a.conj()
Return an array with all complex-valued elements conjugated.
- conjugate(...)
- a.conjugate()
Return an array with all complex-valued elements conjugated.
- dump(...)
- a.dump(file)
Dump a pickle of the array to the specified file.
The array can be read back with pickle.load or numpy.load.
Parameters
----------
file : str
A string naming the dump file.
- dumps(...)
- a.dumps()
Returns the pickle of the array as a string.
pickle.loads or numpy.loads will convert the string back to an array.
- fill(...)
- a.fill(value)
Fill the array with a scalar value.
Parameters
----------
a : ndarray
Input array
value : scalar
All elements of `a` will be assigned this value.
Examples
--------
>>> a = np.array([1, 2])
>>> a.fill(0)
>>> a
array([0, 0])
>>> a = np.empty(2)
>>> a.fill(1)
>>> a
array([ 1., 1.])
- getfield(...)
- a.getfield(dtype, offset)
Returns a field of the given array as a certain type. A field is a view of
the array data with each itemsize determined by the given type and the
offset into the current array.
- item(...)
- a.item()
Copy the first element of array to a standard Python scalar and return
it. The array must be of size one.
- itemset(...)
- newbyteorder(...)
- arr.newbyteorder(new_order='S')
Return the array with the same data viewed with a different byte order.
Equivalent to::
arr.view(arr.dtype.newbytorder(new_order))
Changes are also made in all fields and sub-arrays of the array data
type.
Parameters
----------
new_order : string, optional
Byte order to force; a value from the byte order specifications
above. `new_order` codes can be any of::
* 'S' - swap dtype from current to opposite endian
* {'<', 'L'} - little endian
* {'>', 'B'} - big endian
* {'=', 'N'} - native order
* {'|', 'I'} - ignore (no change to byte order)
The default value ('S') results in swapping the current
byte order. The code does a case-insensitive check on the first
letter of `new_order` for the alternatives above. For example,
any of 'B' or 'b' or 'biggish' are valid to specify big-endian.
Returns
-------
new_arr : array
New array object with the dtype reflecting given change to the
byte order.
- searchsorted(...)
- a.searchsorted(v, side='left')
Find indices where elements of v should be inserted in a to maintain order.
For full documentation, see `numpy.searchsorted`
See Also
--------
numpy.searchsorted : equivalent function
- setfield(...)
- m.setfield(value, dtype, offset) -> None.
places val into field of the given array defined by the data type and offset.
- setflags(...)
- a.setflags(write=None, align=None, uic=None)
Data descriptors inherited from ndarray:
- __array_interface__
- Array protocol: Python side.
- __array_struct__
- Array protocol: C-struct side.
- base
- Base object if memory is from some other object.
Examples
--------
Base of an array owning its memory is None:
>>> x = np.array([1,2,3,4])
>>> x.base is None
True
Slicing creates a view, and the memory is shared with x:
>>> y = x[2:]
>>> y.base is x
True
- ctypes
- A ctypes interface object.
- dtype
- Data-type for the array.
- flags
- Information about the memory layout of the array.
Attributes
----------
C_CONTIGUOUS (C)
The data is in a single, C-style contiguous segment.
F_CONTIGUOUS (F)
The data is in a single, Fortran-style contiguous segment.
OWNDATA (O)
The array owns the memory it uses or borrows it from another object.
WRITEABLE (W)
The data area can be written to.
ALIGNED (A)
The data and strides are aligned appropriately for the hardware.
UPDATEIFCOPY (U)
This array is a copy of some other array. When this array is
deallocated, the base array will be updated with the contents of
this array.
FNC
F_CONTIGUOUS and not C_CONTIGUOUS.
FORC
F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
BEHAVED (B)
ALIGNED and WRITEABLE.
CARRAY (CA)
BEHAVED and C_CONTIGUOUS.
FARRAY (FA)
BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
Notes
-----
The `flags` object can be also accessed dictionary-like, and using
lowercased attribute names. Short flag names are only supported in
dictionary access.
Only the UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be changed by
the user, via assigning to ``flags['FLAGNAME']`` or `ndarray.setflags`.
The array flags cannot be set arbitrarily:
- UPDATEIFCOPY can only be set ``False``.
- ALIGNED can only be set ``True`` if the data is truly aligned.
- WRITEABLE can only be set ``True`` if the array owns its own memory
or the ultimate owner of the memory exposes a writeable buffer
interface or is a string.
- itemsize
- Length of one element in bytes.
Examples
--------
>>> x = np.array([1,2,3], dtype=np.float64)
>>> x.itemsize
8
>>> x = np.array([1,2,3], dtype=np.complex128)
>>> x.itemsize
16
- nbytes
- Number of bytes in the array.
Examples
--------
>>> x = np.zeros((3,5,2), dtype=np.complex128)
>>> x.nbytes
480
>>> np.prod(x.shape) * x.itemsize
480
- ndim
- Number of array dimensions.
Examples
--------
>>> x = np.array([1,2,3])
>>> x.ndim
1
>>> y = np.zeros((2,3,4))
>>> y.ndim
3
- shape
- Tuple of array dimensions.
Examples
--------
>>> x = np.array([1,2,3,4])
>>> x.shape
(4,)
>>> y = np.zeros((4,5,6))
>>> y.shape
(4, 5, 6)
>>> y.shape = (2, 5, 2, 3, 2)
>>> y.shape
(2, 5, 2, 3, 2)
- size
- Number of elements in the array.
Examples
--------
>>> x = np.zeros((3,5,2), dtype=np.complex128)
>>> x.size
30
- strides
- Tuple of bytes to step in each dimension.
The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
is::
offset = sum(np.array(i) * a.strides)
Examples
--------
>>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
>>> x.strides
(32, 4, 224, 1344)
>>> i = np.array([3,5,2,2])
>>> offset = sum(i * x.strides)
>>> x[3,5,2,2]
813
>>> offset / x.itemsize
813
|
mrecarray = class MaskedRecords(MaskedArray, object) |
|
*IVariables*:
_data : {recarray}
Underlying data, as a record array.
_mask : {boolean array}
Mask of the records. A record is masked when all its fields are masked.
_fieldmask : {boolean recarray}
Record array of booleans, setting the mask of each individual field of each record.
_fill_value : {record}
Filling values for each field. |
|
- Method resolution order:
- MaskedRecords
- MaskedArray
- ndarray
- object
Methods defined here:
- __array_finalize__(self, obj)
- #......................................................
- __getattribute__(self, attr)
- __getitem__(self, indx)
- Returns all the fields sharing the same fieldname base.
The fieldname base is either `_data` or `_mask`.
- __getstate__(self)
- Return the internal state of the masked array, for pickling purposes.
- __len__(self)
- Returns the length
- __reduce__(self)
- Return a 3-tuple for pickling a MaskedArray.
- __repr__(self)
- Calculates the repr representation.
- __setattr__(self, attr, val)
- Sets the attribute attr to the value val.
- __setitem__(self, indx, value)
- Sets the given record to value.
- __setstate__(self, state)
- Restore the internal state of the masked array, for pickling purposes.
``state`` is typically the output of the ``__getstate__`` output, and is a
5-tuple:
- class name
- a tuple giving the shape of the data
- a typecode for the data
- a binary string for the data
- a binary string for the mask.
- __str__(self)
- Calculates the string representation.
- copy(self)
- Returns a copy of the masked record.
- harden_mask(self)
- Forces the mask to hard
- soften_mask(self)
- Forces the mask to soft
- tolist(self, fill_value=None)
- Copy the data portion of the array to a hierarchical python
list and returns that list.
Data items are converted to the nearest compatible Python
type. Masked values are converted to fill_value. If
fill_value is None, the corresponding entries in the output
list will be ``None``.
- view(self, dtype=None, type=None)
- Returns a view of the mrecarray.
Static methods defined here:
- __new__(cls, shape, dtype=None, buf=None, offset=0, strides=None, formats=None, names=None, titles=None, byteorder=None, aligned=False, mask=False, hard_mask=False, fill_value=None, keep_mask=True, copy=False, **options)
- #............................................
Methods inherited from MaskedArray:
- __add__(self, other)
- Add other to self, and return a new masked array.
- __array_wrap__(self, obj, context=None)
- Special hook for ufuncs.
Wraps the numpy array and sets the mask according to context.
- __deepcopy__(self, memo=None)
- __div__(self, other)
- Divide other into self, and return a new masked array.
- __eq__(self, other)
- Check whether other equals self elementwise
- __float__(self)
- Convert to float.
- __floordiv__(self, other)
- Divide other into self, and return a new masked array.
- __getslice__(self, i, j)
- x.__getslice__(i, j) <==> x[i:j]
Return the slice described by (i, j). The use of negative
indices is not supported.
- __iadd__(self, other)
- Add other to self in-place.
- __idiv__(self, other)
- Divide self by other in-place.
- __imul__(self, other)
- Multiply self by other in-place.
- __int__(self)
- Convert to int.
- __ipow__(self, other)
- Raise self to the power other, in place.
- __isub__(self, other)
- Subtract other from self in-place.
- __mul__(self, other)
- Multiply other by self, and return a new masked array.
- __ne__(self, other)
- Check whether other doesn't equal self elementwise
- __pow__(self, other)
- Raise self to the power other, masking the potential NaNs/Infs
- __radd__(self, other)
- Add other to self, and return a new masked array.
- __rmul__(self, other)
- Multiply other by self, and return a new masked array.
- __rsub__(self, other)
- Subtract other to self, and return a new masked array.
- __setmask__(self, mask, copy=False)
- Set the mask.
- __setslice__(self, i, j, value)
- x.__setslice__(i, j, value) <==> x[i:j]=value
Set the slice (i,j) of a to value. If value is masked, mask
those locations.
- __sub__(self, other)
- Subtract other to self, and return a new masked array.
- __truediv__(self, other)
- Divide other into self, and return a new masked array.
- all(self, axis=None, out=None)
- Check if all of the elements of `a` are true.
Performs a :func:`logical_and` over the given axis and returns the result.
Masked values are considered as True during computation.
For convenience, the output array is masked where ALL the values along the
current axis are masked: if the output would have been a scalar and that
all the values are masked, then the output is `masked`.
Parameters
----------
axis : {None, integer}
Axis to perform the operation over.
If None, perform over flattened array.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved
and it must be of the right shape to hold the output.
See Also
--------
all : equivalent function
Examples
--------
>>> np.ma.array([1,2,3]).all()
True
>>> a = np.ma.array([1,2,3], mask=True)
>>> (a.all() is np.ma.masked)
True
- anom(self, axis=None, dtype=None)
- Return the anomalies (deviations from the average) along the given axis.
Parameters
----------
axis : int, optional
Axis along which to perform the operation.
If None, applies to a flattened version of the array.
dtype : {dtype}, optional
Datatype for the intermediary computation.
If not given, the current dtype is used instead.
- any(self, axis=None, out=None)
- Check if any of the elements of `a` are true.
Performs a logical_or over the given axis and returns the result.
Masked values are considered as False during computation.
Parameters
----------
axis : {None, integer}
Axis to perform the operation over.
If None, perform over flattened array and return a scalar.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved
and it must be of the right shape to hold the output.
See Also
--------
any : equivalent function
- argmax(self, axis=None, fill_value=None, out=None)
- Returns array of indices of the maximum values along the given axis.
Masked values are treated as if they had the value fill_value.
Parameters
----------
axis : {None, integer}
If None, the index is into the flattened array, otherwise along
the specified axis
fill_value : {var}, optional
Value used to fill in the masked values. If None, the output of
maximum_fill_value(self._data) is used instead.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved
and it must be of the right shape to hold the output.
Returns
-------
index_array : {integer_array}
Examples
--------
>>> a = np.arange(6).reshape(2,3)
>>> a.argmax()
5
>>> a.argmax(0)
array([1, 1, 1])
>>> a.argmax(1)
array([2, 2])
- argmin(self, axis=None, fill_value=None, out=None)
- Return array of indices to the minimum values along the given axis.
Parameters
----------
axis : {None, integer}
If None, the index is into the flattened array, otherwise along
the specified axis
fill_value : {var}, optional
Value used to fill in the masked values. If None, the output of
minimum_fill_value(self._data) is used instead.
out : {None, array}, optional
Array into which the result can be placed. Its type is preserved
and it must be of the right shape to hold the output.
Returns
-------
{ndarray, scalar}
If multi-dimension input, returns a new ndarray of indices to the
minimum values along the given axis. Otherwise, returns a scalar
of index to the minimum values along the given axis.
Examples
--------
>>> x = np.ma.array(arange(4), mask=[1,1,0,0])
>>> x.shape = (2,2)
>>> print x
[[-- --]
[2 3]]
>>> print x.argmin(axis=0, fill_value=-1)
[0 0]
>>> print x.argmin(axis=0, fill_value=9)
[1 1]
- argsort(self, axis=None, fill_value=None, kind='quicksort', order=None)
- Return an ndarray of indices that sort the array along the
specified axis. Masked values are filled beforehand to
fill_value.
Parameters
----------
axis : int, optional
Axis along which to sort. If not given, the flattened array is used.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm.
order : list, optional
When `a` is an array with fields defined, this argument specifies
which fields to compare first, second, etc. Not all fields need be
specified.
Returns
-------
index_array : ndarray, int
Array of indices that sort `a` along the specified axis.
In other words, ``a[index_array]`` yields a sorted `a`.
See Also
--------
sort : Describes sorting algorithms used.
lexsort : Indirect stable sort with multiple keys.
ndarray.sort : Inplace sort.
Notes
-----
See `sort` for notes on the different sorting algorithms.
- astype(self, newtype)
- Returns a copy of the MaskedArray cast to given newtype.
Returns
-------
output : MaskedArray
A copy of self cast to input newtype.
The returned record shape matches self.shape.
Examples
--------
>>> x = np.ma.array([[1,2,3.1],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1.0 -- 3.1]
[-- 5.0 --]
[7.0 -- 9.0]]
>>> print x.astype(int32)
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
- clip(...)
- a.clip(a_min, a_max, out=None)
Return an array whose values are limited to ``[a_min, a_max]``.
Refer to `numpy.clip` for full documentation.
See Also
--------
numpy.clip : equivalent function
- compress(self, condition, axis=None, out=None)
- Return `a` where condition is ``True``.
If condition is a `MaskedArray`, missing values are considered
as ``False``.
Parameters
----------
condition : var
Boolean 1-d array selecting which entries to return. If len(condition)
is less than the size of a along the axis, then output is truncated
to length of condition array.
axis : {None, int}, optional
Axis along which the operation must be performed.
out : {None, ndarray}, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type will be cast if
necessary.
Returns
-------
result : MaskedArray
A :class:`MaskedArray` object.
Notes
-----
Please note the difference with :meth:`compressed` !
The output of :meth:`compress` has a mask, the output of
:meth:`compressed` does not.
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> x.compress([1, 0, 1])
masked_array(data = [1 3],
mask = [False False],
fill_value=999999)
>>> x.compress([1, 0, 1], axis=1)
masked_array(data =
[[1 3]
[-- --]
[7 9]],
mask =
[[False False]
[ True True]
[False False]],
fill_value=999999)
- compressed(self)
- Return a 1-D array of all the non-masked data.
Returns
-------
data : ndarray.
A new ndarray holding the non-masked data is returned.
Notes
-----
+ The result is NOT a MaskedArray !
Examples
--------
>>> x = array(arange(5), mask=[0]+[1]*4)
>>> print x.compressed()
[0]
>>> print type(x.compressed())
<type 'numpy.ndarray'>
- count(self, axis=None)
- Count the non-masked elements of the array along the given axis.
Parameters
----------
axis : int, optional
Axis along which to count the non-masked elements. If axis is None,
all the non masked elements are counted.
Returns
-------
result : MaskedArray
A masked array where the mask is True where all data are
masked. If axis is None, returns either a scalar ot the
masked singleton if all values are masked.
- cumprod(self, axis=None, dtype=None, out=None)
- Return the cumulative product of the elements along the given axis.
The cumulative product is taken over the flattened array by
default, otherwise over the specified axis.
Masked values are set to 1 internally during the computation.
However, their position is saved, and the result will be masked at
the same locations.
Parameters
----------
axis : {None, -1, int}, optional
Axis along which the product is computed. The default
(`axis` = None) is to compute over the flattened array.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator
where the elements are multiplied. If ``dtype`` has the value ``None`` and
the type of ``a`` is an integer type of precision less than the default
platform integer, then the default platform integer precision is
used. Otherwise, the dtype is the same as that of ``a``.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary.
Warnings
--------
The mask is lost if out is not a valid MaskedArray !
Returns
-------
cumprod : ndarray
A new array holding the result is returned unless out is specified,
in which case a reference to out is returned.
Notes
-----
Arithmetic is modular when using integer types, and no error is
raised on overflow.
- cumsum(self, axis=None, dtype=None, out=None)
- Return the cumulative sum of the elements along the given axis.
The cumulative sum is calculated over the flattened array by
default, otherwise over the specified axis.
Masked values are set to 0 internally during the computation.
However, their position is saved, and the result will be masked at
the same locations.
Parameters
----------
axis : {None, -1, int}, optional
Axis along which the sum is computed. The default (`axis` = None) is to
compute over the flattened array. `axis` may be negative, in which case
it counts from the last to the first axis.
dtype : {None, dtype}, optional
Type of the returned array and of the accumulator in which the
elements are summed. If `dtype` is not specified, it defaults
to the dtype of `a`, unless `a` has an integer dtype with a
precision less than that of the default platform integer. In
that case, the default platform integer is used.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary.
Warnings
--------
The mask is lost if out is not a valid :class:`MaskedArray` !
Returns
-------
cumsum : ndarray.
A new array holding the result is returned unless ``out`` is
specified, in which case a reference to ``out`` is returned.
Examples
--------
>>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0])
>>> print marr.cumsum()
[0 1 3 -- -- -- 9 16 24 33]
Notes
-----
Arithmetic is modular when using integer types, and no error is
raised on overflow.
- diagonal(...)
- a.diagonal(offset=0, axis1=0, axis2=1)
Return specified diagonals.
Refer to `numpy.diagonal` for full documentation.
See Also
--------
numpy.diagonal : equivalent function
- filled(self, fill_value=None)
- Return a copy of self, where masked values are filled with `fill_value`.
If `fill_value` is None, `self.fill_value` is used instead.
Notes
-----
+ Subclassing is preserved
+ The result is NOT a MaskedArray !
Examples
--------
>>> x = np.ma.array([1,2,3,4,5], mask=[0,0,1,0,1], fill_value=-999)
>>> x.filled()
array([1,2,-999,4,-999])
>>> type(x.filled())
<type 'numpy.ndarray'>
- flatten(...)
- a.flatten(order='C')
Return a copy of the array collapsed into one dimension.
Parameters
----------
order : {'C', 'F'}, optional
Whether to flatten in C (row-major) or Fortran (column-major) order.
The default is 'C'.
Returns
-------
y : ndarray
A copy of the input array, flattened to one dimension.
See Also
--------
ravel : Return a flattened array.
flat : A 1-D flat iterator over the array.
Examples
--------
>>> a = np.array([[1,2], [3,4]])
>>> a.flatten()
array([1, 2, 3, 4])
>>> a.flatten('F')
array([1, 3, 2, 4])
- get_fill_value(self)
- Return the filling value.
- get_imag(self)
- Returns the imaginary part.
- get_real(self)
- Returns the real part.
- ids(self)
- Return the addresses of the data and mask areas.
- iscontiguous(self)
- Is the data contiguous?
- max(self, axis=None, out=None, fill_value=None)
- Return the maximum along a given axis.
Parameters
----------
axis : {None, int}, optional
Axis along which to operate. By default, ``axis`` is None and the
flattened input is used.
out : array_like, optional
Alternative output array in which to place the result. Must
be of the same shape and buffer length as the expected output.
fill_value : {var}, optional
Value used to fill in the masked values.
If None, use the output of maximum_fill_value().
Returns
-------
amax : array_like
New array holding the result.
If ``out`` was specified, ``out`` is returned.
See Also
--------
maximum_fill_value
Returns the maximum filling value for a given datatype.
- mean(self, axis=None, dtype=None, out=None)
- Returns the average of the array elements along given axis.
Refer to `numpy.mean` for full documentation.
See Also
--------
numpy.mean : equivalent function'
- min(self, axis=None, out=None, fill_value=None)
- Return the minimum along a given axis.
Parameters
----------
axis : {None, int}, optional
Axis along which to operate. By default, ``axis`` is None and the
flattened input is used.
out : array_like, optional
Alternative output array in which to place the result. Must be of
the same shape and buffer length as the expected output.
fill_value : {var}, optional
Value used to fill in the masked values.
If None, use the output of `minimum_fill_value`.
Returns
-------
amin : array_like
New array holding the result.
If ``out`` was specified, ``out`` is returned.
See Also
--------
minimum_fill_value
Returns the minimum filling value for a given datatype.
- mini(self, axis=None)
- nonzero(self)
- Return the indices of the elements of a that are not zero
nor masked, as a tuple of arrays.
There are as many tuples as dimensions of a, each tuple
contains the indices of the non-zero elements in that
dimension. The corresponding non-zero values can be obtained
with ``a[a.nonzero()]``.
To group the indices by element, rather than dimension, use
instead: ``transpose(a.nonzero())``.
The result of this is always a 2d array, with a row for each
non-zero element.
- prod(self, axis=None, dtype=None, out=None)
- Return the product of the array elements over the given axis.
Masked elements are set to 1 internally for computation.
Parameters
----------
axis : {None, int}, optional
Axis over which the product is taken. If None is used, then the
product is over all the array elements.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator
where the elements are multiplied. If ``dtype`` has the value ``None``
and the type of a is an integer type of precision less than the default
platform integer, then the default platform integer precision is
used. Otherwise, the dtype is the same as that of a.
out : {None, array}, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type will be cast if
necessary.
Returns
-------
product_along_axis : {array, scalar}, see dtype parameter above.
Returns an array whose shape is the same as a with the specified
axis removed. Returns a 0d array when a is 1d or axis=None.
Returns a reference to the specified output array if specified.
See Also
--------
prod : equivalent function
Notes
-----
Arithmetic is modular when using integer types, and no error is raised
on overflow.
Examples
--------
>>> np.prod([1.,2.])
2.0
>>> np.prod([1.,2.], dtype=np.int32)
2
>>> np.prod([[1.,2.],[3.,4.]])
24.0
>>> np.prod([[1.,2.],[3.,4.]], axis=1)
array([ 2., 12.])
- product = prod(self, axis=None, dtype=None, out=None)
- Return the product of the array elements over the given axis.
Masked elements are set to 1 internally for computation.
Parameters
----------
axis : {None, int}, optional
Axis over which the product is taken. If None is used, then the
product is over all the array elements.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator
where the elements are multiplied. If ``dtype`` has the value ``None``
and the type of a is an integer type of precision less than the default
platform integer, then the default platform integer precision is
used. Otherwise, the dtype is the same as that of a.
out : {None, array}, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type will be cast if
necessary.
Returns
-------
product_along_axis : {array, scalar}, see dtype parameter above.
Returns an array whose shape is the same as a with the specified
axis removed. Returns a 0d array when a is 1d or axis=None.
Returns a reference to the specified output array if specified.
See Also
--------
prod : equivalent function
Notes
-----
Arithmetic is modular when using integer types, and no error is raised
on overflow.
Examples
--------
>>> np.prod([1.,2.])
2.0
>>> np.prod([1.,2.], dtype=np.int32)
2
>>> np.prod([[1.,2.],[3.,4.]])
24.0
>>> np.prod([[1.,2.],[3.,4.]], axis=1)
array([ 2., 12.])
- ptp(self, axis=None, out=None, fill_value=None)
- Return (maximum - minimum) along the the given dimension
(i.e. peak-to-peak value).
Parameters
----------
axis : {None, int}, optional
Axis along which to find the peaks. If None (default) the
flattened array is used.
out : {None, array_like}, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary.
fill_value : {var}, optional
Value used to fill in the masked values.
Returns
-------
ptp : ndarray.
A new array holding the result, unless ``out`` was
specified, in which case a reference to ``out`` is returned.
- put(self, indices, values, mode='raise')
- Set storage-indexed locations to corresponding values.
Sets self._data.flat[n] = values[n] for each n in indices.
If `values` is shorter than `indices` then it will repeat.
If `values` has some masked values, the initial mask is updated
in consequence, else the corresponding values are unmasked.
Parameters
----------
indices : 1-D array_like
Target indices, interpreted as integers.
values : array_like
Values to place in self._data copy at target indices.
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices will behave.
'raise' : raise an error.
'wrap' : wrap around.
'clip' : clip to the range.
Notes
-----
`values` can be a scalar or length 1 array.
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> x.put([0,4,8],[10,20,30])
>>> print x
[[10 -- 3]
[-- 20 --]
[7 -- 30]]
>>> x.put(4,999)
>>> print x
[[10 -- 3]
[-- 999 --]
[7 -- 30]]
- ravel(self)
- Returns a 1D version of self, as a view.
Returns
-------
MaskedArray
Output view is of shape ``(self.size,)`` (or
``(np.ma.product(self.shape),)``).
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> print x.ravel()
[1 -- 3 -- 5 -- 7 -- 9]
- raw_data(self)
- Return the _data part of the MaskedArray.
DEPRECATED: You should really use ``.data`` instead...
- repeat(...)
- a.repeat(repeats, axis=None)
Repeat elements of an array.
Refer to `numpy.repeat` for full documentation.
See Also
--------
numpy.repeat : equivalent function
- reshape(self, *s, **kwargs)
- Returns a masked array containing the data of a, but with a new shape.
The result is a view to the original array; if this is not possible,
a ValueError is raised.
Parameters
----------
shape : shape tuple or int
The new shape should be compatible with the original shape. If an
integer, then the result will be a 1D array of that length.
order : {'C', 'F'}, optional
Determines whether the array data should be viewed as in C
(row-major) order or FORTRAN (column-major) order.
Returns
-------
reshaped_array : array
A new view to the array.
Notes
-----
If you want to modify the shape in place, please use ``a.shape = s``
Examples
--------
>>> x = np.ma.array([[1,2],[3,4]], mask=[1,0,0,1])
>>> print x
[[-- 2]
[3 --]]
>>> x = x.reshape((4,1))
>>> print x
[[--]
[2]
[3]
[--]]
- resize(self, newshape, refcheck=True, order=False)
- Change shape and size of array in-place.
- round(self, decimals=0, out=None)
- a.round(decimals=0, out=None)
Return an array rounded a to the given number of decimals.
Refer to `numpy.around` for full documentation.
See Also
--------
numpy.around : equivalent function
- set_fill_value(self, value=None)
- Set the filling value to value.
If value is None, use a default based on the data type.
- shrink_mask(self)
- Reduce a mask to nomask when possible.
- sort(self, axis=-1, kind='quicksort', order=None, endwith=True, fill_value=None)
- Return a sorted copy of an array.
Parameters
----------
a : array_like
Array to be sorted.
axis : int or None, optional
Axis along which to sort. If None, the array is flattened before
sorting. The default is -1, which sorts along the last axis.
kind : {'quicksort', 'mergesort', 'heapsort'}, optional
Sorting algorithm. Default is 'quicksort'.
order : list, optional
When `a` is a structured array, this argument specifies which fields
to compare first, second, and so on. This list does not need to
include all of the fields.
endwith : {True, False}, optional
Whether missing values (if any) should be forced in the upper indices
(at the end of the array) (True) or lower indices (at the beginning).
fill_value : {var}
Value used to fill in the masked values. If None, use
the the output of minimum_fill_value().
Returns
-------
sorted_array : ndarray
Array of the same type and shape as `a`.
See Also
--------
ndarray.sort : Method to sort an array in-place.
argsort : Indirect sort.
lexsort : Indirect stable sort on multiple keys.
searchsorted : Find elements in a sorted array.
Notes
-----
The various sorting algorithms are characterized by their average speed,
worst case performance, work space size, and whether they are stable. A
stable sort keeps items with the same key in the same relative
order. The three available algorithms have the following
properties:
=========== ======= ============= ============ =======
kind speed worst case work space stable
=========== ======= ============= ============ =======
'quicksort' 1 O(n^2) 0 no
'mergesort' 2 O(n*log(n)) ~n/2 yes
'heapsort' 3 O(n*log(n)) 0 no
=========== ======= ============= ============ =======
All the sort algorithms make temporary copies of the data when
sorting along any but the last axis. Consequently, sorting along
the last axis is faster and uses less space than sorting along
any other axis.
Examples
--------
>>> a = np.array([[1,4],[3,1]])
>>> np.sort(a) # sort along the last axis
array([[1, 4],
[1, 3]])
>>> np.sort(a, axis=None) # sort the flattened array
array([1, 1, 3, 4])
>>> np.sort(a, axis=0) # sort along the first axis
array([[1, 1],
[3, 4]])
Use the `order` keyword to specify a field to use when sorting a
structured array:
>>> dtype = [('name', 'S10'), ('height', float), ('age', int)]
>>> values = [('Arthur', 1.8, 41), ('Lancelot', 1.9, 38),
... ('Galahad', 1.7, 38)]
>>> a = np.array(values, dtype=dtype) # create a structured array
>>> np.sort(a, order='height') # doctest: +SKIP
array([('Galahad', 1.7, 38), ('Arthur', 1.8, 41),
('Lancelot', 1.8999999999999999, 38)],
dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
Sort by age, then height if ages are equal:
>>> np.sort(a, order=['age', 'height']) # doctest: +SKIP
array([('Galahad', 1.7, 38), ('Lancelot', 1.8999999999999999, 38),
('Arthur', 1.8, 41)],
dtype=[('name', '|S10'), ('height', '<f8'), ('age', '<i4')])
- squeeze(...)
- a.squeeze()
Remove single-dimensional entries from the shape of `a`.
Refer to `numpy.squeeze` for full documentation.
See Also
--------
numpy.squeeze : equivalent function
- std(self, axis=None, dtype=None, out=None, ddof=0)
- Compute the standard deviation along the specified axis.
Returns the standard deviation, a measure of the spread of a distribution,
of the array elements. The standard deviation is computed for the
flattened array by default, otherwise over the specified axis.
Parameters
----------
a : array_like
Calculate the standard deviation of these values.
axis : int, optional
Axis along which the standard deviation is computed. The default is
to compute the standard deviation of the flattened array.
dtype : dtype, optional
Type to use in computing the standard deviation. For arrays of
integer type the default is float64, for arrays of float types it is
the same as the array type.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type (of the calculated
values) will be cast if necessary.
ddof : int, optional
Means Delta Degrees of Freedom. The divisor used in calculations
is ``N - ddof``, where ``N`` represents the number of elements.
By default `ddof` is zero.
Returns
-------
standard_deviation : {ndarray, scalar}; see dtype parameter above.
If `out` is None, return a new array containing the standard deviation,
otherwise return a reference to the output array.
See Also
--------
numpy.var : Variance
numpy.mean : Average
Notes
-----
The standard deviation is the square root of the average of the squared
deviations from the mean, i.e., ``std = sqrt(mean(abs(x - x.mean())**2))``.
The mean is normally calculated as ``x.sum() / N``, where
``N = len(x)``. If, however, `ddof` is specified, the divisor ``N - ddof``
is used instead. In standard statistical practice, ``ddof=1`` provides an
unbiased estimator of the variance of the infinite population. ``ddof=0``
provides a maximum likelihood estimate of the variance for normally
distributed variables. The standard deviation computed in this function
is the square root of the estimated variance, so even with ``ddof=1``, it
will not be an unbiased estimate of the standard deviation per se.
Note that, for complex numbers, std takes the absolute
value before squaring, so that the result is always real and nonnegative.
Examples
--------
>>> a = np.array([[1, 2], [3, 4]])
>>> np.std(a)
1.1180339887498949
>>> np.std(a, 0)
array([ 1., 1.])
>>> np.std(a, 1)
array([ 0.5, 0.5])
- sum(self, axis=None, dtype=None, out=None)
- Return the sum of the array elements over the given axis.
Masked elements are set to 0 internally.
Parameters
----------
axis : {None, -1, int}, optional
Axis along which the sum is computed. The default
(`axis` = None) is to compute over the flattened array.
dtype : {None, dtype}, optional
Determines the type of the returned array and of the accumulator
where the elements are summed. If dtype has the value None and
the type of a is an integer type of precision less than the default
platform integer, then the default platform integer precision is
used. Otherwise, the dtype is the same as that of a.
out : {None, ndarray}, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output
but the type will be cast if necessary.
Returns
-------
sum_along_axis : MaskedArray or scalar
An array with the same shape as self, with the specified
axis removed. If self is a 0-d array, or if `axis` is None, a scalar
is returned. If an output array is specified, a reference to
`out` is returned.
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> print x.sum()
25
>>> print x.sum(axis=1)
[4 5 16]
>>> print x.sum(axis=0)
[8 5 12]
>>> print type(x.sum(axis=0, dtype=np.int64)[0])
<type 'numpy.int64'>
- swapaxes(...)
- a.swapaxes(axis1, axis2)
Return a view of the array with `axis1` and `axis2` interchanged.
Refer to `numpy.swapaxes` for full documentation.
See Also
--------
numpy.swapaxes : equivalent function
- take(...)
- a.take(indices, axis=None, out=None, mode='raise')
Return an array formed from the elements of a at the given indices.
Refer to `numpy.take` for full documentation.
See Also
--------
numpy.take : equivalent function
- tofile(self, fid, sep='', format='%s')
- #........................
- toflex(self)
- Transforms a MaskedArray into a flexible-type array with two fields:
* the ``_data`` field stores the ``_data`` part of the array;
* the ``_mask`` field stores the ``_mask`` part of the array;
Returns
-------
record : ndarray
A new flexible-type ndarray with two fields: the first element
containing a value, the second element containing the corresponding
mask boolean. The returned record shape matches self.shape.
Notes
-----
A side-effect of transforming a masked array into a flexible ndarray is
that meta information (``fill_value``, ...) will be lost.
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> print x.toflex()
[[(1, False) (2, True) (3, False)]
[(4, True) (5, False) (6, True)]
[(7, False) (8, True) (9, False)]]
- torecords = toflex(self)
- Transforms a MaskedArray into a flexible-type array with two fields:
* the ``_data`` field stores the ``_data`` part of the array;
* the ``_mask`` field stores the ``_mask`` part of the array;
Returns
-------
record : ndarray
A new flexible-type ndarray with two fields: the first element
containing a value, the second element containing the corresponding
mask boolean. The returned record shape matches self.shape.
Notes
-----
A side-effect of transforming a masked array into a flexible ndarray is
that meta information (``fill_value``, ...) will be lost.
Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
[-- 5 --]
[7 -- 9]]
>>> print x.toflex()
[[(1, False) (2, True) (3, False)]
[(4, True) (5, False) (6, True)]
[(7, False) (8, True) (9, False)]]
- tostring(self, fill_value=None, order='C')
- Return a copy of array data as a Python string containing the raw bytes
in the array. The array is filled beforehand.
Parameters
----------
fill_value : {var}, optional
Value used to fill in the masked values.
If None, uses self.fill_value instead.
order : {string}
Order of the data item in the copy {'C','F','A'}.
'C' -- C order (row major)
'Fortran' -- Fortran order (column major)
'Any' -- Current order of array.
None -- Same as "Any"
Notes
-----
As for method:`ndarray.tostring`, information about the shape, dtype...,
but also fill_value will be lost.
- trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None)
- a.trace(offset=0, axis1=0, axis2=1, dtype=None, out=None)
Return the sum along diagonals of the array.
Refer to `numpy.trace` for full documentation.
See Also
--------
numpy.trace : equivalent function
- transpose(...)
- a.transpose(*axes)
Returns a view of 'a' with axes transposed. If no axes are given,
or None is passed, switches the order of the axes. For a 2-d
array, this is the usual matrix transpose. If axes are given,
they describe how the axes are permuted.
See Also
--------
ndarray.T : array property returning the array transposed
Examples
--------
>>> a = np.array([[1,2],[3,4]])
>>> a
array([[1, 2],
[3, 4]])
>>> a.transpose()
array([[1, 3],
[2, 4]])
>>> a.transpose((1,0))
array([[1, 3],
[2, 4]])
>>> a.transpose(1,0)
array([[1, 3],
[2, 4]])
- unshare_mask(self)
- Copy the mask and set the sharedmask flag to False.
- var(self, axis=None, dtype=None, out=None, ddof=0)
- Compute the variance along the specified axis.
Returns the variance of the array elements, a measure of the spread of a
distribution. The variance is computed for the flattened array by default,
otherwise over the specified axis.
Parameters
----------
a : array_like
Array containing numbers whose variance is desired. If `a` is not an
array, a conversion is attempted.
axis : int, optional
Axis along which the variance is computed. The default is to compute
the variance of the flattened array.
dtype : dtype, optional
Type to use in computing the variance. For arrays of integer type
the default is float32; for arrays of float types it is the same as
the array type.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape as the expected output but the type is cast if
necessary.
ddof : int, optional
"Delta Degrees of Freedom": the divisor used in calculation is
``N - ddof``, where ``N`` represents the number of elements. By
default `ddof` is zero.
Returns
-------
variance : ndarray, see dtype parameter above
If out=None, returns a new array containing the variance; otherwise
a reference to the output array is returned.
See Also
--------
std : Standard deviation
mean : Average
Notes
-----
The variance is the average of the squared deviations from the mean,
i.e., ``var = mean(abs(x - x.mean())**2)``.
The mean is normally calculated as ``x.sum() / N``, where ``N = len(x)``.
If, however, `ddof` is specified, the divisor ``N - ddof`` is used
instead. In standard statistical practice, ``ddof=1`` provides an
unbiased estimator of the variance of the infinite population. ``ddof=0``
provides a maximum likelihood estimate of the variance for normally
distributed variables.
Note that for complex numbers, the absolute value is taken before
squaring, so that the result is always real and nonnegative.
Examples
--------
>>> a = np.array([[1,2],[3,4]])
>>> np.var(a)
1.25
>>> np.var(a,0)
array([ 1., 1.])
>>> np.var(a,1)
array([ 0.25, 0.25])
Data descriptors inherited from MaskedArray:
- T
- __dict__
- dictionary for instance variables (if defined)
- baseclass
- Class of the underlying data (read-only).
- data
- Return the current data, as a view of the original
underlying data.
- fill_value
- Filling value.
- flat
- Flat version of the array.
- hardmask
- Hardness of the mask
- imag
- Imaginary part.
- mask
- Mask
- real
- Real part
- recordmask
- Return the mask of the records.
A record is masked when all the fields are masked.
- sharedmask
- Share status of the mask (read-only).
Data and other attributes inherited from MaskedArray:
- __array_priority__ = 15
Methods inherited from ndarray:
- __abs__(...)
- x.__abs__() <==> abs(x)
- __and__(...)
- x.__and__(y) <==> x&y
- __array__(...)
- a.__array__(|dtype) -> reference if type unchanged, copy otherwise.
Returns either a new reference to self if dtype is not given or a new array
of provided data type if dtype is different from the current dtype of the
array.
- __contains__(...)
- x.__contains__(y) <==> y in x
- __copy__(...)
- a.__copy__([order])
Return a copy of the array.
Parameters
----------
order : {'C', 'F', 'A'}, optional
If order is 'C' (False) then the result is contiguous (default).
If order is 'Fortran' (True) then the result has fortran order.
If order is 'Any' (None) then the result has fortran order
only if the array already is in fortran order.
- __delitem__(...)
- x.__delitem__(y) <==> del x[y]
- __delslice__(...)
- x.__delslice__(i, j) <==> del x[i:j]
Use of negative indices is not supported.
- __divmod__(...)
- x.__divmod__(y) <==> divmod(x, y)
- __ge__(...)
- x.__ge__(y) <==> x>=y
- __gt__(...)
- x.__gt__(y) <==> x>y
- __hex__(...)
- x.__hex__() <==> hex(x)
- __iand__(...)
- x.__iand__(y) <==> x&y
- __ifloordiv__(...)
- x.__ifloordiv__(y) <==> x//y
- __ilshift__(...)
- x.__ilshift__(y) <==> x<<y
- __imod__(...)
- x.__imod__(y) <==> x%y
- __index__(...)
- x[y:z] <==> x[y.__index__():z.__index__()]
- __invert__(...)
- x.__invert__() <==> ~x
- __ior__(...)
- x.__ior__(y) <==> x|y
- __irshift__(...)
- x.__irshift__(y) <==> x>>y
- __iter__(...)
- x.__iter__() <==> iter(x)
- __itruediv__(...)
- x.__itruediv__(y) <==> x/y
- __ixor__(...)
- x.__ixor__(y) <==> x^y
- __le__(...)
- x.__le__(y) <==> x<=y
- __long__(...)
- x.__long__() <==> long(x)
- __lshift__(...)
- x.__lshift__(y) <==> x<<y
- __lt__(...)
- x.__lt__(y) <==> x<y
- __mod__(...)
- x.__mod__(y) <==> x%y
- __neg__(...)
- x.__neg__() <==> -x
- __nonzero__(...)
- x.__nonzero__() <==> x != 0
- __oct__(...)
- x.__oct__() <==> oct(x)
- __or__(...)
- x.__or__(y) <==> x|y
- __pos__(...)
- x.__pos__() <==> +x
- __rand__(...)
- x.__rand__(y) <==> y&x
- __rdiv__(...)
- x.__rdiv__(y) <==> y/x
- __rdivmod__(...)
- x.__rdivmod__(y) <==> divmod(y, x)
- __rfloordiv__(...)
- x.__rfloordiv__(y) <==> y//x
- __rlshift__(...)
- x.__rlshift__(y) <==> y<<x
- __rmod__(...)
- x.__rmod__(y) <==> y%x
- __ror__(...)
- x.__ror__(y) <==> y|x
- __rpow__(...)
- y.__rpow__(x[, z]) <==> pow(x, y[, z])
- __rrshift__(...)
- x.__rrshift__(y) <==> y>>x
- __rshift__(...)
- x.__rshift__(y) <==> x>>y
- __rtruediv__(...)
- x.__rtruediv__(y) <==> y/x
- __rxor__(...)
- x.__rxor__(y) <==> y^x
- __xor__(...)
- x.__xor__(y) <==> x^y
- byteswap(...)
- a.byteswap(inplace)
Swap the bytes of the array elements
Toggle between low-endian and big-endian data representation by
returning a byteswapped array, optionally swapped in-place.
Parameters
----------
inplace: bool, optional
If ``True``, swap bytes in-place, default is ``False``.
Returns
-------
out: ndarray
The byteswapped array. If `inplace` is ``True``, this is
a view to self.
Examples
--------
>>> A = np.array([1, 256, 8755], dtype=np.int16)
>>> map(hex, A)
['0x1', '0x100', '0x2233']
>>> A.byteswap(True)
array([ 256, 1, 13090], dtype=int16)
>>> map(hex, A)
['0x100', '0x1', '0x3322']
Arrays of strings are not swapped
>>> A = np.array(['ceg', 'fac'])
>>> A.byteswap()
array(['ceg', 'fac'],
dtype='|S3')
- choose(...)
- a.choose(choices, out=None, mode='raise')
Use an index array to construct a new array from a set of choices.
Refer to `numpy.choose` for full documentation.
See Also
--------
numpy.choose : equivalent function
- conj(...)
- a.conj()
Return an array with all complex-valued elements conjugated.
- conjugate(...)
- a.conjugate()
Return an array with all complex-valued elements conjugated.
- dump(...)
- a.dump(file)
Dump a pickle of the array to the specified file.
The array can be read back with pickle.load or numpy.load.
Parameters
----------
file : str
A string naming the dump file.
- dumps(...)
- a.dumps()
Returns the pickle of the array as a string.
pickle.loads or numpy.loads will convert the string back to an array.
- fill(...)
- a.fill(value)
Fill the array with a scalar value.
Parameters
----------
a : ndarray
Input array
value : scalar
All elements of `a` will be assigned this value.
Examples
--------
>>> a = np.array([1, 2])
>>> a.fill(0)
>>> a
array([0, 0])
>>> a = np.empty(2)
>>> a.fill(1)
>>> a
array([ 1., 1.])
- getfield(...)
- a.getfield(dtype, offset)
Returns a field of the given array as a certain type. A field is a view of
the array data with each itemsize determined by the given type and the
offset into the current array.
- item(...)
- a.item()
Copy the first element of array to a standard Python scalar and return
it. The array must be of size one.
- itemset(...)
- newbyteorder(...)
- arr.newbyteorder(new_order='S')
Return the array with the same data viewed with a different byte order.
Equivalent to::
arr.view(arr.dtype.newbytorder(new_order))
Changes are also made in all fields and sub-arrays of the array data
type.
Parameters
----------
new_order : string, optional
Byte order to force; a value from the byte order specifications
above. `new_order` codes can be any of::
* 'S' - swap dtype from current to opposite endian
* {'<', 'L'} - little endian
* {'>', 'B'} - big endian
* {'=', 'N'} - native order
* {'|', 'I'} - ignore (no change to byte order)
The default value ('S') results in swapping the current
byte order. The code does a case-insensitive check on the first
letter of `new_order` for the alternatives above. For example,
any of 'B' or 'b' or 'biggish' are valid to specify big-endian.
Returns
-------
new_arr : array
New array object with the dtype reflecting given change to the
byte order.
- searchsorted(...)
- a.searchsorted(v, side='left')
Find indices where elements of v should be inserted in a to maintain order.
For full documentation, see `numpy.searchsorted`
See Also
--------
numpy.searchsorted : equivalent function
- setfield(...)
- m.setfield(value, dtype, offset) -> None.
places val into field of the given array defined by the data type and offset.
- setflags(...)
- a.setflags(write=None, align=None, uic=None)
Data descriptors inherited from ndarray:
- __array_interface__
- Array protocol: Python side.
- __array_struct__
- Array protocol: C-struct side.
- base
- Base object if memory is from some other object.
Examples
--------
Base of an array owning its memory is None:
>>> x = np.array([1,2,3,4])
>>> x.base is None
True
Slicing creates a view, and the memory is shared with x:
>>> y = x[2:]
>>> y.base is x
True
- ctypes
- A ctypes interface object.
- dtype
- Data-type for the array.
- flags
- Information about the memory layout of the array.
Attributes
----------
C_CONTIGUOUS (C)
The data is in a single, C-style contiguous segment.
F_CONTIGUOUS (F)
The data is in a single, Fortran-style contiguous segment.
OWNDATA (O)
The array owns the memory it uses or borrows it from another object.
WRITEABLE (W)
The data area can be written to.
ALIGNED (A)
The data and strides are aligned appropriately for the hardware.
UPDATEIFCOPY (U)
This array is a copy of some other array. When this array is
deallocated, the base array will be updated with the contents of
this array.
FNC
F_CONTIGUOUS and not C_CONTIGUOUS.
FORC
F_CONTIGUOUS or C_CONTIGUOUS (one-segment test).
BEHAVED (B)
ALIGNED and WRITEABLE.
CARRAY (CA)
BEHAVED and C_CONTIGUOUS.
FARRAY (FA)
BEHAVED and F_CONTIGUOUS and not C_CONTIGUOUS.
Notes
-----
The `flags` object can be also accessed dictionary-like, and using
lowercased attribute names. Short flag names are only supported in
dictionary access.
Only the UPDATEIFCOPY, WRITEABLE, and ALIGNED flags can be changed by
the user, via assigning to ``flags['FLAGNAME']`` or `ndarray.setflags`.
The array flags cannot be set arbitrarily:
- UPDATEIFCOPY can only be set ``False``.
- ALIGNED can only be set ``True`` if the data is truly aligned.
- WRITEABLE can only be set ``True`` if the array owns its own memory
or the ultimate owner of the memory exposes a writeable buffer
interface or is a string.
- itemsize
- Length of one element in bytes.
Examples
--------
>>> x = np.array([1,2,3], dtype=np.float64)
>>> x.itemsize
8
>>> x = np.array([1,2,3], dtype=np.complex128)
>>> x.itemsize
16
- nbytes
- Number of bytes in the array.
Examples
--------
>>> x = np.zeros((3,5,2), dtype=np.complex128)
>>> x.nbytes
480
>>> np.prod(x.shape) * x.itemsize
480
- ndim
- Number of array dimensions.
Examples
--------
>>> x = np.array([1,2,3])
>>> x.ndim
1
>>> y = np.zeros((2,3,4))
>>> y.ndim
3
- shape
- Tuple of array dimensions.
Examples
--------
>>> x = np.array([1,2,3,4])
>>> x.shape
(4,)
>>> y = np.zeros((4,5,6))
>>> y.shape
(4, 5, 6)
>>> y.shape = (2, 5, 2, 3, 2)
>>> y.shape
(2, 5, 2, 3, 2)
- size
- Number of elements in the array.
Examples
--------
>>> x = np.zeros((3,5,2), dtype=np.complex128)
>>> x.size
30
- strides
- Tuple of bytes to step in each dimension.
The byte offset of element ``(i[0], i[1], ..., i[n])`` in an array `a`
is::
offset = sum(np.array(i) * a.strides)
Examples
--------
>>> x = np.reshape(np.arange(5*6*7*8), (5,6,7,8)).transpose(2,3,1,0)
>>> x.strides
(32, 4, 224, 1344)
>>> i = np.array([3,5,2,2])
>>> offset = sum(i * x.strides)
>>> x[3,5,2,2]
813
>>> offset / x.itemsize
813
| |