diff options
author | Pauli Virtanen <pav@iki.fi> | 2008-10-28 00:13:44 +0000 |
---|---|---|
committer | Pauli Virtanen <pav@iki.fi> | 2008-10-28 00:13:44 +0000 |
commit | 18594cd9653a865fddfa4cd81f82ab54430be1c9 (patch) | |
tree | 04db708f8a8a3575d129390342ff789ef6f1e170 /numpy/core | |
parent | 7a70f54f515bb8c586c3967d62731a49217eef95 (diff) | |
download | numpy-18594cd9653a865fddfa4cd81f82ab54430be1c9.tar.gz |
Import documentation from doc wiki (part 2, work-in-progress docstrings, but they are still an improvement)
Diffstat (limited to 'numpy/core')
-rw-r--r-- | numpy/core/arrayprint.py | 19 | ||||
-rw-r--r-- | numpy/core/code_generators/docstrings.py | 427 | ||||
-rw-r--r-- | numpy/core/defchararray.py | 14 | ||||
-rw-r--r-- | numpy/core/fromnumeric.py | 209 | ||||
-rw-r--r-- | numpy/core/numeric.py | 236 | ||||
-rw-r--r-- | numpy/core/numerictypes.py | 8 |
6 files changed, 693 insertions, 220 deletions
diff --git a/numpy/core/arrayprint.py b/numpy/core/arrayprint.py index 8400802f7..98df924e7 100644 --- a/numpy/core/arrayprint.py +++ b/numpy/core/arrayprint.py @@ -42,23 +42,23 @@ def set_printoptions(precision=None, threshold=None, edgeitems=None, Parameters ---------- - precision : int + precision : int, optional Number of digits of precision for floating point output (default 8). - threshold : int + threshold : int, optional Total number of array elements which trigger summarization rather than full repr (default 1000). - edgeitems : int + edgeitems : int, optional Number of array items in summary at beginning and end of each dimension (default 3). - linewidth : int + linewidth : int, optional The number of characters per line for the purpose of inserting line breaks (default 75). - suppress : bool + suppress : bool, optional Whether or not suppress printing of small floating point values using scientific notation (default False). - nanstr : string + nanstr : string, optional String representation of floating point not-a-number (default nan). - infstr : string + infstr : string, optional String representation of floating point infinity (default inf). Examples @@ -242,7 +242,8 @@ def array2string(a, max_line_width = None, precision = None, The maximum number of columns the string should span. Newline characters splits the string appropriately after array elements. precision : int, optional - Floating point precision. + Floating point precision. Default is the current printing + precision (usually 8), which can be altered using `set_printoptions`. suppress_small : bool, optional Represent very small numbers as zero. separator : string, optional @@ -259,7 +260,7 @@ def array2string(a, max_line_width = None, precision = None, See Also -------- - array_str, array_repr + array_str, array_repr, set_printoptions Examples -------- diff --git a/numpy/core/code_generators/docstrings.py b/numpy/core/code_generators/docstrings.py index 5360d3bc2..882a781a8 100644 --- a/numpy/core/code_generators/docstrings.py +++ b/numpy/core/code_generators/docstrings.py @@ -95,7 +95,7 @@ add_newdoc('numpy.core.umath', 'arccos', Returns ------- - angle : {ndarray, scalar} + angle : ndarray The angle of the ray intersecting the unit circle at the given `x`-coordinate in radians [0, pi]. If `x` is a scalar then a scalar is returned, otherwise an array of the same shape as `x` @@ -156,7 +156,7 @@ add_newdoc('numpy.core.umath', 'arccosh', Returns ------- - out : {ndarray, scalar} + out : ndarray Array of the same shape and dtype as `x`. Notes @@ -198,7 +198,7 @@ add_newdoc('numpy.core.umath', 'arcsin', Returns ------- - angle : {ndarray, scalar} + angle : ndarray The angle of the ray intersecting the unit circle at the given `y`-coordinate in radians ``[-pi, pi]``. If `x` is a scalar then a scalar is returned, otherwise an array is returned. @@ -263,7 +263,7 @@ add_newdoc('numpy.core.umath', 'arcsinh', For real-valued input data types, `arcsinh` always returns real output. For each value that cannot be expressed as a real number or infinity, it - yields ``nan`` and sets the `invalid` floating point error flag. + returns ``nan`` and sets the `invalid` floating point error flag. For complex-valued input, `arccos` is a complex analytical function that has branch cuts `[1j, infj]` and `[-1j, -infj]` and is continuous from @@ -294,12 +294,12 @@ add_newdoc('numpy.core.umath', 'arctan', Parameters ---------- - x : {array_like, scalar} + x : array_like Input values. `arctan` is applied to each element of `x`. Returns ------- - out : {ndarray, scalar} + out : ndarray Out has the same shape as `x`. Its real part is in ``[-pi/2, pi/2]``. It is a scalar if `x` is a scalar. @@ -363,15 +363,15 @@ add_newdoc('numpy.core.umath', 'arctan2', Parameters ---------- - x1 : array-like, real-valued + x1 : array_like, real-valued y-coordinates. - x2 : array-like, real-valued + x2 : array_like, real-valued x-coordinates. `x2` must be broadcastable to match the shape of `x1`, or vice versa. Returns ------- - angle : array-like + angle : ndarray Array of angles in radians, in the range ``[-pi, pi]``. See Also @@ -726,7 +726,7 @@ add_newdoc('numpy.core.umath', 'conjugate', Returns ------- - y : {ndarray, scalar} + y : ndarray The complex conjugate of `x`, with same dtype as `y`. Examples @@ -793,12 +793,12 @@ add_newdoc('numpy.core.umath', 'degrees', Parameters ---------- - x : array-like + x : array_like Angle in radians. Returns ------- - y : {ndarray, scalar} + y : ndarray The corresponding angle in degrees. @@ -964,7 +964,37 @@ add_newdoc('numpy.core.umath', 'exp', add_newdoc('numpy.core.umath', 'expm1', """ - e**x-1 elementwise. + Return the exponential of the elements in the array minus one. + + Parameters + ---------- + x : array_like + Input values. + + Returns + ------- + out : ndarray + Element-wise exponential minus one: ``out=exp(x)-1``. + + See Also + -------- + log1p : ``log(1+x)``, the inverse of expm1. + + + Notes + ----- + This function provides greater precision than using ``exp(x)-1`` + for small values of `x`. + + Examples + -------- + Since the series expansion of ``e**x = 1 + x + x**2/2! + x**3/3! + ...``, + for very small `x` we expect that ``e**x -1 ~ x + x**2/2``: + + >>> np.expm1(1e-10) + 1.00000000005e-10 + >>> np.exp(1e-10) - 1 + 1.000000082740371e-10 """) @@ -1135,7 +1165,7 @@ add_newdoc('numpy.core.umath', 'greater', add_newdoc('numpy.core.umath', 'greater_equal', """ - Returns (x1 >= x2) element-wise. + Element-wise True if first array is greater or equal than second array. Parameters ---------- @@ -1144,12 +1174,12 @@ add_newdoc('numpy.core.umath', 'greater_equal', Returns ------- - Out : {ndarray, bool} - Output array of bools, or a single bool if `x1` and `x2` are scalars. + out : ndarray, bool + Output array. See Also -------- - greater + greater, less, less_equal, equal Examples -------- @@ -1164,17 +1194,16 @@ add_newdoc('numpy.core.umath', 'hypot', Parameters ---------- - x : array-like + x : array_like Base of the triangle. - y : array-like + y : array_like Height of the triangle. Returns ------- - z : {ndarray, scalar} + z : ndarray Hypotenuse of the triangle: sqrt(x**2 + y**2) - Examples -------- >>> np.hypot(3,4) @@ -1277,66 +1306,182 @@ add_newdoc('numpy.core.umath', 'invert', add_newdoc('numpy.core.umath', 'isfinite', """ - Returns True where x is finite, False otherwise. + Returns True for each element that is a finite number. + + Shows which elements of the input are finite (not infinity or not + Not a Number). Parameters ---------- x : array_like - input values + Input values. + y : array_like, optional + A boolean array with the same shape and type as `x` to store the result. Returns ------- - y : {ndarray, bool} - array of bools + y : ndarray, bool + For scalar input data, the result is a new numpy boolean with value True + if the input data is finite; otherwise the value is False (input is + either positive infinity, negative infinity or Not a Number). + + For array input data, the result is an numpy boolean array with the same + dimensions as the input and the values are True if the corresponding + element of the input is finite; otherwise the values are False (element + is either positive infinity, negative infinity or Not a Number). If the + second argument is supplied then an numpy integer array is returned with + values 0 or 1 corresponding to False and True, respectively. + + See Also + -------- + isinf : Shows which elements are negative or negative infinity. + isneginf : Shows which elements are negative infinity. + isposinf : Shows which elements are positive infinity. + isnan : Shows which elements are Not a Number (NaN). + Notes ----- - `Nan` is considered as non-finite. + Not a Number, positive infinity and negative infinity are considered + to be non-finite. + + Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic + (IEEE 754). This means that Not a Number is not equivalent to infinity. + Also that positive infinity is not equivalent to negative infinity. But + infinity is equivalent to positive infinity. + + Errors result if second argument is also supplied with scalar input or + if first and second arguments have different shapes. Examples -------- + >>> np.isfinite(1) + True + >>> np.isfinite(0) + True + >>> np.isfinite(np.nan) + False + >>> np.isfinite(np.inf) + False + >>> np.isfinite(np.NINF) + False >>> np.isfinite([np.log(-1.),1.,np.log(0)]) array([False, True, False], dtype=bool) + >>> x=np.array([-np.inf, 0., np.inf]) + >>> y=np.array([2,2,2]) + >>> np.isfinite(x,y) + array([0, 1, 0]) + >>> y + array([0, 1, 0]) """) add_newdoc('numpy.core.umath', 'isinf', """ - Returns True where x is +inf or -inf, False otherwise. + Shows which elements of the input are positive or negative infinity. + Returns a numpy boolean scalar or array resulting from an element-wise test + for positive or negative infinity. Parameters ---------- x : array_like input values + y : array_like, optional + An array with the same shape as `x` to store the result. Returns ------- y : {ndarray, bool} - array of bools + For scalar input data, the result is a new numpy boolean with value True + if the input data is positive or negative infinity; otherwise the value + is False. + + For array input data, the result is an numpy boolean array with the same + dimensions as the input and the values are True if the corresponding + element of the input is positive or negative infinity; otherwise the + values are False. If the second argument is supplied then an numpy + integer array is returned with values 0 or 1 corresponding to False and + True, respectively. + + See Also + -------- + isneginf : Shows which elements are negative infinity. + isposinf : Shows which elements are positive infinity. + isnan : Shows which elements are Not a Number (NaN). + isfinite: Shows which elements are not: Not a number, positive and + negative infinity + + Notes + ----- + Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic + (IEEE 754). This means that Not a Number is not equivalent to infinity. + Also that positive infinity is not equivalent to negative infinity. But + infinity is equivalent to positive infinity. + + Errors result if second argument is also supplied with scalar input or + if first and second arguments have different shapes. + + Numpy's definitions for positive infinity (PINF) and negative infinity + (NINF) may be change in the future versions. Examples -------- + >>> np.isinf(np.inf) + True + >>> np.isinf(np.nan) + False + >>> np.isinf(np.NINF) + True >>> np.isinf([np.inf, -np.inf, 1.0, np.nan]) array([ True, True, False, False], dtype=bool) + >>> x=np.array([-np.inf, 0., np.inf]) + >>> y=np.array([2,2,2]) + >>> np.isinf(x,y) + array([1, 0, 1]) + >>> y + array([1, 0, 1]) """) add_newdoc('numpy.core.umath', 'isnan', """ - Returns True where elements are Not-A-Number, False otherwise. + Returns a numpy boolean scalar or array resulting from an element-wise test + for Not a Number (NaN). Parameters ---------- x : array_like - input values. + input data. Returns ------- y : {ndarray, bool} - array of bools + For scalar input data, the result is a new numpy boolean with value True + if the input data is NaN; otherwise the value is False. + + For array input data, the result is an numpy boolean array with the same + dimensions as the input and the values are True if the corresponding + element of the input is Not a Number; otherwise the values are False. + + See Also + -------- + isinf : Tests for infinity. + isneginf : Tests for negative infinity. + isposinf : Tests for positive infinity. + isfinite : Shows which elements are not: Not a number, positive infinity + and negative infinity + + Notes + ----- + Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic + (IEEE 754). This means that Not a Number is not equivalent to infinity. Examples -------- + >>> np.isnan(np.nan) + True + >>> np.isnan(np.inf) + False >>> np.isnan([np.log(-1.),1.,np.log(0)]) array([ True, False, False], dtype=bool) @@ -1344,7 +1489,34 @@ add_newdoc('numpy.core.umath', 'isnan', add_newdoc('numpy.core.umath', 'left_shift', """ - Computes x1 << x2 (x1 shifted to left by x2 bits) elementwise. + Shift the bits of an integer to the left. + + Bits are shifted to the left by appending `x2` 0s at the right of `x1`. + Since the internal representation of numbers is in binary format, this + operation is equivalent to multiplying `x1` by ``2**x2``. + + Parameters + ---------- + x1 : array_like of integer type + Input values. + x2 : array_like of integer type + Number of zeros to append to `x1`. + + Returns + ------- + out : array of integer type + Return `x1` with bits shifted `x2` times to the left. + + See Also + -------- + right_shift : Shift the bits of an integer to the right. + binary_repr : Return the binary representation of the input number + as a string. + + Examples + -------- + >>> np.left_shift(5, [1,2,3]) + array([10, 20, 40]) """) @@ -1354,7 +1526,7 @@ add_newdoc('numpy.core.umath', 'less', Parameters ---------- - x1, x2 : array-like + x1, x2 : array_like Input arrays. Returns @@ -1408,12 +1580,12 @@ add_newdoc('numpy.core.umath', 'log', Parameters ---------- x : array_like - Input value. + Input value. Returns ------- - y : {ndarray, scalar} - The natural logarithm of `x`, element-wise. + y : ndarray + The natural logarithm of `x`, element-wise. See Also -------- @@ -1449,18 +1621,17 @@ add_newdoc('numpy.core.umath', 'log', add_newdoc('numpy.core.umath', 'log10', """ - Compute the logarithm in base 10 elementwise. + Compute the logarithm in base 10 element-wise. Parameters ---------- x : array_like - input values. + Input values. Returns ------- - y : {ndarray, scalar} - base-10 logarithm of `x`. - + y : ndarray + Base-10 logarithm of `x`. Notes ----- @@ -1501,7 +1672,7 @@ add_newdoc('numpy.core.umath', 'log1p', Returns ------- - y : {ndarray, scalar} + y : ndarray Natural logarithm of `1 + x`, elementwise. Notes @@ -1674,13 +1845,79 @@ add_newdoc('numpy.core.umath', 'logical_xor', add_newdoc('numpy.core.umath', 'maximum', """ - Returns maximum (if x1 > x2: x1; else: x2) elementwise. + Element-wise maximum of array elements. + + Compare two arrays and returns a new array containing + the element-wise maxima. + + Parameters + ---------- + x1, x2 : array_like + The arrays holding the elements to be compared. + + Returns + ------- + y : {ndarray, scalar} + The maximum of `x1` and `x2`, element-wise. Returns scalar if + both `x1` and `x2` are scalars. + + See Also + -------- + minimum : + element-wise minimum + + Notes + ----- + Equivalent to ``np.where(x1 > x2, x1, x2)`` but faster and does proper + broadcasting. + + Examples + -------- + >>> np.maximum([2, 3, 4], [1, 5, 2]) + array([2, 5, 4]) + + >>> np.maximum(np.eye(2), [0.5, 2]) + array([[ 1. , 2. ], + [ 0.5, 2. ]]) """) add_newdoc('numpy.core.umath', 'minimum', """ - Returns minimum (if x1 < x2: x1; else: x2) elementwise + Element-wise minimum of array elements. + + Compare two arrays and returns a new array containing + the element-wise minima. + + Parameters + ---------- + x1, x2 : array_like + The arrays holding the elements to be compared. + + Returns + ------- + y : {ndarray, scalar} + The minimum of `x1` and `x2`, element-wise. Returns scalar if + both `x1` and `x2` are scalars. + + See Also + -------- + maximum : + element-wise maximum + + Notes + ----- + Equivalent to ``np.where(x1 < x2, x1, x2)`` but faster and does proper + broadcasting. + + Examples + -------- + >>> np.minimum([2, 3, 4], [1, 5, 2]) + array([1, 3, 2]) + + >>> np.minimum(np.eye(2), [0.5, 2]) + array([[ 0.5, 0. ], + [ 0. , 1. ]]) """) @@ -1718,12 +1955,12 @@ add_newdoc('numpy.core.umath', 'multiply', Parameters ---------- - x1, x2 : array-like + x1, x2 : array_like The arrays to be multiplied. Returns ------- - y : {ndarray, scalar} + y : ndarray The product of `x1` and `x2`, elementwise. Returns a scalar if both `x1` and `x2` are scalars. @@ -1797,7 +2034,7 @@ add_newdoc('numpy.core.umath', 'not_equal', add_newdoc('numpy.core.umath', 'ones_like', """ - Returns an array of zeros with the same shape and type as a given array. + Returns an array of ones with the same shape and type as a given array. Equivalent to ``a.copy().fill(1)``. @@ -1818,7 +2055,7 @@ add_newdoc('numpy.core.umath', 'ones_like', add_newdoc('numpy.core.umath', 'power', """ - Computes `x1` ** `x2` elementwise. + Returns element-wise base array raised to power from second array. Raise each base in `x1` to the power of the exponents in `x2`. This requires that `x1` and `x2` must be broadcastable to the same shape. @@ -1874,7 +2111,7 @@ add_newdoc('numpy.core.umath', 'radians', Returns ------- - y : {ndarray, scalar} + y : ndarray The corresponding angle in radians. See Also @@ -1895,7 +2132,7 @@ add_newdoc('numpy.core.umath', 'radians', add_newdoc('numpy.core.umath', 'reciprocal', """ - Compute 1/x. + Return element-wise reciprocal. Parameters ---------- @@ -1904,7 +2141,7 @@ add_newdoc('numpy.core.umath', 'reciprocal', Returns ------- - y : {ndarray, scalar} + y : ndarray Return value. Examples @@ -1918,7 +2155,9 @@ add_newdoc('numpy.core.umath', 'reciprocal', add_newdoc('numpy.core.umath', 'remainder', """ - Computes x1-n*x2 where n is floor(x1 / x2) + Returns element-wise remainder of division. + + Computes `x1 - floor(x1/x2)*x2`. Parameters ---------- @@ -1929,9 +2168,9 @@ add_newdoc('numpy.core.umath', 'remainder', Returns ------- - y : {ndarray, scalar} - The quotient `x1/x2`, element-wise. Returns a scalar if - both `x1` and `x2` are scalars. + y : ndarray + The remainder of the quotient `x1/x2`, element-wise. Returns a scalar + if both `x1` and `x2` are scalars. See Also -------- @@ -1951,7 +2190,34 @@ add_newdoc('numpy.core.umath', 'remainder', add_newdoc('numpy.core.umath', 'right_shift', """ - Computes x1 >> x2 (x1 shifted to right by x2 bits) elementwise. + Shift the bits of an integer to the right. + + Bits are shifted to the right by removing `x2` bits at the right of `x1`. + Since the internal representation of numbers is in binary format, this + operation is equivalent to dividing `x1` by ``2**x2``. + + Parameters + ---------- + x1 : array_like, int + Input values. + x2 : array_like, int + Number of bits to remove at the right of `x1`. + + Returns + ------- + out : ndarray, int + Return `x1` with bits shifted `x2` times to the right. + + See Also + -------- + left_shift : Shift the bits of an integer to the left. + binary_repr : Return the binary representation of the input number + as a string. + + Examples + -------- + >>> np.right_shift(10, [1,2,3]) + array([5, 2, 1]) """) @@ -1979,9 +2245,9 @@ add_newdoc('numpy.core.umath', 'rint', add_newdoc('numpy.core.umath', 'sign', """ - Return the sign of a number. + Returns an element-wise indication of the sign of a number. - -1 if x < 0, 0 if x==0, 1 if x > 0. + The `sign` function returns ``-1 if x < 0, 0 if x==0, 1 if x > 0``. Parameters ---------- @@ -1990,7 +2256,7 @@ add_newdoc('numpy.core.umath', 'sign', Returns ------- - y : {ndarray, scalar} + y : ndarray The sign of `x`. Examples @@ -2004,20 +2270,23 @@ add_newdoc('numpy.core.umath', 'sign', add_newdoc('numpy.core.umath', 'signbit', """ - Returns True where `signbit` of `x` is set (`x<0`). + Returns element-wise True where signbit is set (less than zero). Parameters ---------- - x: array-like or scalar - the input value(s). - output : array-like or scalar - the returned boolean(s) + x: array_like + The input value(s). + + Returns + ------- + out : array_like, bool + Output. Examples -------- >>> np.signbit(-1.2) True - >>> np.signbit(np.array([1,-2.3,2.1])) + >>> np.signbit(np.array([1, -2.3, 2.1])) array([False, True, False], dtype=bool) """) @@ -2138,18 +2407,18 @@ add_newdoc('numpy.core.umath', 'sqrt', add_newdoc('numpy.core.umath', 'square', """ - Compute `x` squared, or `x` to the power of two. + Return the element-wise square of the input. Parameters ---------- - x : array_like or scalar + x : array_like Input data. Returns ------- - out : ndarray or scalar + out : ndarray Element-wise `x*x`, of the same shape and dtype as `x`. - `out` is a scalar if `x` is a scalar. + Returns scalar if `x` is a scalar. See Also -------- @@ -2166,18 +2435,18 @@ add_newdoc('numpy.core.umath', 'square', add_newdoc('numpy.core.umath', 'subtract', """ - Subtract arguments elementwise. + Subtract arguments element-wise. Parameters ---------- - x1, x2 : {array_like, scalar} + x1, x2 : array_like The arrays to be subtracted from each other. If type is 'array_like' the `x1` and `x2` shapes must be identical. Returns ------- - y : {ndarray, scalar} - The difference of `x1` and `x2`, elementwise. Returns a scalar if + y : ndarray + The difference of `x1` and `x2`, element-wise. Returns a scalar if both `x1` and `x2` are scalars. Notes @@ -2200,7 +2469,7 @@ add_newdoc('numpy.core.umath', 'subtract', add_newdoc('numpy.core.umath', 'tan', """ - Compute tangent elementwise. + Compute tangent element-wise. Parameters ---------- @@ -2209,7 +2478,7 @@ add_newdoc('numpy.core.umath', 'tan', Returns ------- - y : ndarray or scalar + y : ndarray The corresponding tangent values. @@ -2223,7 +2492,7 @@ add_newdoc('numpy.core.umath', 'tan', add_newdoc('numpy.core.umath', 'tanh', """ - Hyperbolic tangent elementwise. + Hyperbolic tangent element-wise. Parameters ---------- @@ -2232,14 +2501,14 @@ add_newdoc('numpy.core.umath', 'tanh', Returns ------- - y : ndarray or scalar + y : ndarray The corresponding hyperbolic tangent values. """) add_newdoc('numpy.core.umath', 'true_divide', """ - Returns an elementwise, true division of the inputs. + Returns an element-wise, true division of the inputs. Instead of the Python traditional 'floor division', this returns a true division. True division adjusts the output type to present the best @@ -2254,7 +2523,7 @@ add_newdoc('numpy.core.umath', 'true_divide', Returns ------- - out : {ndarray, scalar} + out : ndarray Result is scalar if both inputs are scalar, ndarray otherwise. Notes diff --git a/numpy/core/defchararray.py b/numpy/core/defchararray.py index 33e90c965..2dec5634e 100644 --- a/numpy/core/defchararray.py +++ b/numpy/core/defchararray.py @@ -16,6 +16,20 @@ _unicode = unicode # comparisons class chararray(ndarray): + """ + chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0, + strides=None, order=None) + + A character array of string or unicode type. + + The array items will be `itemsize` characters long. + + Create the array using buffer (with offset and strides) if it is + not None. If buffer is None, then construct a new array with strides + in Fortran order if len(shape) >=2 and order is 'Fortran' (otherwise + the strides will be in 'C' order). + + """ def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None, offset=0, strides=None, order='C'): global _globalvar diff --git a/numpy/core/fromnumeric.py b/numpy/core/fromnumeric.py index a6f4203be..0023c99f0 100644 --- a/numpy/core/fromnumeric.py +++ b/numpy/core/fromnumeric.py @@ -44,17 +44,17 @@ def _wrapit(obj, method, *args, **kwds): def take(a, indices, axis=None, out=None, mode='raise'): """ - Take elements from an array along a given axis. + Take elements from an array along an axis. This function does the same thing as "fancy" indexing (indexing arrays - using arrays); however, it can be easier to use if you need to specify - a given axis. + using arrays); however, it can be easier to use if you need elements + along a given axis. Parameters ---------- - a : ndarray + a : array_like The source array. - indices : int array + indices : array_like, int The indices of the values to extract. axis : int, optional The axis over which to select values. By default, the @@ -77,6 +77,18 @@ def take(a, indices, axis=None, out=None, mode='raise'): -------- ndarray.take : equivalent method + Examples + -------- + >>> a = [4, 3, 5, 7, 6, 8] + >>> indices = [0, 1, 4] + >>> np.take(a, indices) + array([4, 3, 6]) + + In this example if `a` is a ndarray, "fancy" indexing can be used. + >>> a = np.array(a) + >>> a[indices] + array([4, 3, 6]) + """ try: take = a.take @@ -88,15 +100,17 @@ def take(a, indices, axis=None, out=None, mode='raise'): # not deprecated --- copy if necessary, view otherwise def reshape(a, newshape, order='C'): """ - Returns an array containing the data of a, but with a new shape. + Gives a new shape to an array without changing its data. Parameters ---------- - a : ndarray + a : array_like Array to be reshaped. newshape : {tuple, int} - The new shape should be compatible with the original shape. If an - integer, then the result will be a 1-D array of that length. + The new shape should be compatible with the original shape. If + an integer, then the result will be a 1-D array of that length. + One shape dimension can be -1. In this case, the value is inferred + from the length of the array and remaining dimensions. order : {'C', 'F'}, optional Determines whether the array data should be viewed as in C (row-major) order or FORTRAN (column-major) order. @@ -113,16 +127,15 @@ def reshape(a, newshape, order='C'): Examples -------- - >>> a = np.array([[1,2], [3,4]]) - >>> a.reshape(4) - array([1, 2, 3, 4]) - >>> a.reshape(4, order='F') - array([1, 3, 2, 4]) - >>> a.reshape((4,1)) - array([[1], - [2], - [3], - [4]]) + >>> a = np.array([[1,2,3], [4,5,6]]) + >>> np.reshape(a, 6) + array([1, 2, 3, 4, 5, 6]) + >>> np.reshape(a, 6, order='F') + array([1, 4, 2, 5, 3, 6]) + >>> np.reshape(a, (3,-1)) # the unspecified value is inferred to be 2 + array([[1, 2], + [3, 4], + [5, 6]]) """ try: @@ -236,9 +249,10 @@ def repeat(a, repeats, axis=None): def put(a, ind, v, mode='raise'): """ - Set a.flat[n] = v[n] for all n in ind. + Changes specific elements of one array by replacing from another array. - If `v` is shorter than `ind`, it will repeat. + Set `a`.flat[n] = `v`\\[n] for all n in `ind`. If `v` is shorter than + `ind`, it will repeat which is different than `a[ind]` = `v`. Parameters ---------- @@ -379,28 +393,29 @@ def sort(a, axis=-1, kind='quicksort', order=None): Parameters ---------- - a : array-like + a : array_like Array to be sorted. - axis : int, optional - Axis along which to sort. If not specified, the flattened array - is used. + 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. + Sorting algorithm. Default is 'quicksort'. order : list, optional - When `a` is an ndarray with fields defined, this argument specifies - which fields to compare first, second, etc. Not all fields need be - specified. + 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. Returns ------- sorted_array : ndarray - Array of same type and shape as `a`. + 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 keys in sorted array. + searchsorted : Find elements in a sorted array. Notes ----- @@ -425,15 +440,34 @@ def sort(a, axis=-1, kind='quicksort', order=None): Examples -------- - >>> a=np.array([[1,4],[3,1]]) - >>> a.sort(1) - >>> a + >>> a = np.array([[1,4],[3,1]]) + >>> np.sort(a) # sort along the last axis array([[1, 4], [1, 3]]) - >>> a.sort(0) - >>> a - array([[1, 3], - [1, 4]]) + >>> 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')]) """ if axis is None: @@ -468,7 +502,7 @@ def argsort(a, axis=-1, kind='quicksort', order=None): Returns ------- - index_array : ndarray of ints + index_array : ndarray, int Array of indices that sort `a` along the specified axis. In other words, ``a[index_array]`` yields a sorted `a`. @@ -528,7 +562,7 @@ def argsort(a, axis=-1, kind='quicksort', order=None): def argmax(a, axis=None): """ - Indices of the maximum values along a given axis. + Indices of the maximum values along an axis. Parameters ---------- @@ -540,13 +574,14 @@ def argmax(a, axis=None): Returns ------- - index_array : ndarray of ints - Array of indices into the array. It has the same shape `a`, + index_array : ndarray, int + Array of indices into the array. It has the same shape as `a`, except with `axis` removed. See Also -------- - amax : The maximum along a given axis. + argmin : Indices of the minimum values along an axis. + amax : The maximum value along a given axis. unravel_index : Convert a flat index into an index tuple. Examples @@ -569,9 +604,12 @@ def argmax(a, axis=None): def argmin(a, axis=None): """ - Return the indices of the minimum values along the given axis of `a`. + Return the indices of the minimum values along an axis. - Refer to `numpy.argmax` for detailed documentation. + See Also + -------- + argmax : Similar function. Please refer to `numpy.argmax` for detailed + documentation. """ try: @@ -697,7 +735,7 @@ def squeeze(a): Parameters ---------- - a : array-like + a : array_like Input data. Returns @@ -726,7 +764,7 @@ def diagonal(a, offset=0, axis1=0, axis2=1): """ Return specified diagonals. - If `a` is 2-D, returns the diagonal of self with the given offset, + If `a` is 2-D, returns the diagonal of `a` with the given offset, i.e., the collection of elements of the form `a[i,i+offset]`. If `a` has more than two dimensions, then the axes specified by `axis1` and `axis2` are used to determine the 2-D subarray @@ -829,7 +867,7 @@ def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None): Returns ------- - sum_along_diagonals : array + sum_along_diagonals : ndarray If a is 2-d, a 0-d array containing the diagonal is returned. If a has larger dimensions, then an array of diagonals is returned. @@ -935,6 +973,8 @@ def nonzero(a): flatnonzero : Return indices that are non-zero in the flattened version of the input array. + ndarray.nonzero : + Equivalent ndarray method. Examples -------- @@ -980,6 +1020,7 @@ def shape(a): See Also -------- + alen, ndarray.shape : array method Examples @@ -993,10 +1034,10 @@ def shape(a): >>> np.shape(0) () - >>> x = np.array([(1,2),(3,4)], dtype=[('x', 'i4'), ('y', 'i4')]) - >>> np.shape(x) + >>> a = np.array([(1,2),(3,4)], dtype=[('x', 'i4'), ('y', 'i4')]) + >>> np.shape(a) (2,) - >>> x.shape + >>> a.shape (2,) """ @@ -1013,24 +1054,29 @@ def compress(condition, a, axis=None, out=None): Parameters ---------- - condition : {array} - 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. - a : {array_type} + condition : array_like + Boolean 1-D array selecting which entries to return. If len(condition) + is less than the size of `a` along the given axis, then output is + truncated to the length of the condition array. + a : array_like Array from which to extract a part. - axis : {None, integer} - Axis along which to take slices. If None, work on the flattened array. - out : array, optional + axis : int, optional + Axis along which to take slices. If None (default), work on the + flattened array. + out : ndarray, optional Output array. Its type is preserved and it must be of the right shape to hold the output. Returns ------- - compressed_array : array + compressed_array : ndarray A copy of `a` without the slices along axis for which `condition` is false. + See Also + -------- + ndarray.compress: Equivalent method. + Examples -------- >>> a = np.array([[1, 2], [3, 4]]) @@ -1127,7 +1173,7 @@ def sum(a, axis=None, dtype=None, out=None): Returns ------- - sum_along_axis : ndarray or scalar + sum_along_axis : ndarray An array with the same shape as `a`, with the specified axis removed. If `a` is a 0-d array, or if `axis` is None, a scalar is returned. If an output array is specified, a reference to @@ -1208,14 +1254,11 @@ def sometrue(a, axis=None, out=None): def alltrue (a, axis=None, out=None): """ - Check if all of the elements of `a` are true. - - Please refer to the `numpy.all` documentation. `numpy.all` is - the same function. + Check if all elements of input array are true. See Also -------- - numpy.all : equivalent function + numpy.all : Equivalent function; see for details. """ try: @@ -1227,7 +1270,7 @@ def alltrue (a, axis=None, out=None): def any(a,axis=None, out=None): """ - Test whether any elements of an array evaluate to true along a given axis. + Test whether any elements of an array evaluate to True along an axis. Parameters ---------- @@ -1278,7 +1321,7 @@ def any(a,axis=None, out=None): def all(a,axis=None, out=None): """ - Test whether all elements of an array evaluate to true along a given axis. + Returns True if all elements evaluate to True. Parameters ---------- @@ -1293,7 +1336,7 @@ def all(a,axis=None, out=None): Returns ------- - out : ndarray + out : ndarray, bool A logical AND is performed along `axis`, and the result placed in `out`. If `out` was not specified, a new output array is created. @@ -1333,7 +1376,7 @@ def cumsum (a, axis=None, dtype=None, out=None): Parameters ---------- - a : array-like + a : array_like Input array or object that can be converted to an array. axis : int, optional Axis along which the cumulative sum is computed. The default @@ -1403,7 +1446,9 @@ def cumproduct(a, axis=None, dtype=None, out=None): def ptp(a, axis=None, out=None): """ - Peak to peak (maximum - minimum) value along a given axis. + Range of values (maximum - minimum) along an axis. + + The name of the function comes from the acronym for 'peak to peak'. Parameters ---------- @@ -1526,7 +1571,7 @@ def amin(a, axis=None, out=None): def alen(a): """ - Return the length of an array_like as an array of at least 1 dimension. + Return the length of the first dimension of the input array. Parameters ---------- @@ -1538,12 +1583,16 @@ def alen(a): alen : int Length of the first dimension of `a`. + See Also + -------- + shape + Examples -------- - >>> z = np.zeros((7,4,5)) - >>> z.shape[0] + >>> a = np.zeros((7,4,5)) + >>> a.shape[0] 7 - >>> np.alen(z) + >>> np.alen(a) 7 """ @@ -1567,8 +1616,8 @@ def prod(a, axis=None, dtype=None, out=None): dtype : data-type, optional The data-type of the returned array, as well as of the accumulator in which the elements are multiplied. By default, if `a` is of - integer type, `dtype` is the default platform integer (note: if - the type of `a` is unsigned, then so is `dtype`). Otherwise, + integer type, `dtype` is the default platform integer. (Note: if + the type of `a` is unsigned, then so is `dtype`.) 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 @@ -1577,7 +1626,7 @@ def prod(a, axis=None, dtype=None, out=None): Returns ------- - product_along_axis : {ndarray, scalar}, see `dtype` parameter above. + product_along_axis : ndarray, see `dtype` parameter above. An array shaped as `a` but with the specified axis removed. Returns a reference to `out` if specified. @@ -1846,9 +1895,9 @@ def around(a, decimals=0, out=None): Returns ------- - rounded_array : {array} + rounded_array : ndarray An array of the same type as `a`, containing the rounded values. - Unless `a` was specified, a new array is created. A reference to + Unless `out` was specified, a new array is created. A reference to the result is returned. The real and imaginary parts of complex numbers are rounded diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index c27a0ea45..ff2eb6ca9 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -305,7 +305,7 @@ def asfortranarray(a, dtype=None): Parameters ---------- - a : array-like + a : array_like Input array. dtype : data-type, optional By default, the data-type is inferred from the input data. @@ -339,7 +339,7 @@ def require(a, dtype=None, requirements=None): Parameters ---------- - a : array-like + a : array_like The object to be converted to a type-and-requirement satisfying array dtype : data-type The required data-type (None is the default data-type -- float64) @@ -403,15 +403,42 @@ def isfortran(a): return a.flags.fnc def argwhere(a): - """Return a 2-d array of shape N x a.ndim where each row - is a sequence of indices into a. This sequence must be - converted to a tuple in order to be used to index into a. + """ + Find the indices of array elements that are non-zero, grouped by element. + + Parameters + ---------- + a : array_like + Input data. + + Returns + ------- + index_array : ndarray + Indices of elements that are non-zero. Indices are grouped by element. + + See Also + -------- + where, nonzero + + Notes + ----- + ``np.argwhere(a)`` is the same as ``np.transpose(np.nonzero(a))``. + + The output of ``argwhere`` is not suitable for indexing arrays. + For this purpose use ``where(a)`` instead. - >>> np.argwhere(np.ones((2, 2))) - array([[0, 0], - [0, 1], + Examples + -------- + >>> x = np.arange(6).reshape(2,3) + >>> x + array([[0, 1, 2], + [3, 4, 5]]) + >>> np.argwhere(x>1) + array([[0, 2], [1, 0], - [1, 1]]) + [1, 1], + [1, 2]]) + """ return asarray(a.nonzero()).T @@ -635,6 +662,13 @@ def vdot(a, b): dot(`a`, `b`). If the first argument is complex the complex conjugate of the first argument is used for the calculation of the dot product. + For 2-D arrays it is equivalent to matrix multiplication, and for 1-D + arrays to inner product of vectors (with complex conjugation of `a`). + For N dimensions it is a sum product over the last axis of `a` and + the second-to-last of `b`:: + + dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m]) + Parameters ---------- a : array_like @@ -645,7 +679,7 @@ def vdot(a, b): Returns ------- - output : scalar + output : ndarray Returns dot product of `a` and `b`. Can be an int, float, or complex depending on the types of `a` and `b`. @@ -726,7 +760,7 @@ except ImportError: def tensordot(a, b, axes=2): """ - Returns the tensor dot product for (ndim >= 1) arrays along specified axes. + Returns the tensor dot product for (ndim >= 1) arrays along an axes. The first element of the sequence determines the axis or axes in `a` to sum over, and the second element in `axes` argument sequence @@ -1109,40 +1143,52 @@ little_endian = (sys.byteorder == 'little') def indices(dimensions, dtype=int): """ - Return an array representing the coordinates of a grid. + Return an array representing the indices of a grid. + + Compute an array where the subarrays contain index values 0,1,... + varying only along the corresponding axis. Parameters ---------- - shape : (N,) tuple of ints + dimensions : sequence of ints + The shape of the grid. + dtype : optional + Data_type of the result. Returns ------- grid : ndarray - The output shape is ``(N,) + shape``. I.e., if `shape` is ``(2,4,5)``, - the output shape is ``(3, 2, 4, 5)``. Each subarray, ``grid[i,...]`` - contains values that vary only along the ``i-th`` axis. + The array of grid indices, + ``grid.shape = (len(dimensions),) + tuple(dimensions)``. - Examples + See Also -------- - >>> grid = np.indices((2,3)) + mgrid, meshgrid - The row-positions are given by: + Notes + ----- + The output shape is obtained by prepending the number of dimensions + in front of the tuple of dimensions, i.e. if `dimensions` is a tuple + ``(r0, ..., rN-1)`` of length ``N``, the output shape is + ``(N,r0,...,rN-1)``. - >>> grid[0] - array([[0, 0, 0], - [1, 1, 1]]) + The subarrays ``grid[k]`` contains the N-D array of indices along the + ``k-th`` axis. Explicitly:: - and the column-positions by + grid[k,i0,i1,...,iN-1] = ik - >>> grid[1] + Examples + -------- + >>> grid = np.indices((2,3)) + >>> grid.shape + (2,2,3) + >>> grid[0] # row indices + array([[0, 0, 0], + [1, 1, 1]]) + >>> grid[1] # column indices array([[0, 1, 2], [0, 1, 2]]) - - See Also - -------- - mgrid, meshgrid, ndindex - """ dimensions = tuple(dimensions) N = len(dimensions) @@ -1491,7 +1537,7 @@ def identity(n, dtype=None): def allclose(a, b, rtol=1.e-5, atol=1.e-8): """ - Returns True if all elements are equal subject to given tolerances. + Returns True if two arrays are element-wise equal within a tolerance. The tolerance values are positive, typically very small numbers. The relative difference (`rtol` * `b`) and the absolute difference (`atol`) @@ -1507,17 +1553,33 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8): atol : Absolute tolerance The absolute difference is equal to `atol`. + Returns + ------- + y : bool + Returns True if the two arrays are equal within the given + tolerance; False otherwise. If either array contains NaN, then + False is returned. + See Also -------- all, any, alltrue, sometrue + Notes + ----- + If the following equation is element-wise True, then allclose returns + True. + + absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`)) + Examples -------- - >>> allclose(array([1e10,1e-7]), array([1.00001e10,1e-8])) + >>> np.allclose([1e10,1e-7], [1.00001e10,1e-8]) False - >>> allclose(array([1e10,1e-8]), array([1.00001e10,1e-9])) + >>> np.allclose([1e10,1e-8], [1.00001e10,1e-9]) True - >>> allclose(array([1e10,1e-8]), array([1.0001e10,1e-9])) + >>> np.allclose([1e10,1e-8], [1.0001e10,1e-9]) + False + >>> np.allclose([1.0, np.nan], [1.0, np.nan]) False """ @@ -1540,9 +1602,9 @@ def array_equal(a1, a2): Parameters ---------- - a1 : array-like + a1 : array_like First input array. - a2 : array-like + a2 : array_like Second input array. Returns @@ -1571,9 +1633,32 @@ def array_equal(a1, a2): return bool(logical_and.reduce(equal(a1,a2).ravel())) def array_equiv(a1, a2): - """Returns True if a1 and a2 are shape consistent - (mutually broadcastable) and have all elements equal and False - otherwise. + """ + Returns True if input arrays are shape consistent and all elements equal. + + Parameters + ---------- + a1 : array_like + Input array. + a2 : array_like + Input array. + + Returns + ------- + out : bool + True if equivalent, False otherwise. + + Examples + -------- + >>> np.array_equiv([1,2],[1,2]) + >>> True + >>> np.array_equiv([1,2],[1,3]) + >>> False + >>> np.array_equiv([1,2], [[1,2],[1,2]]) + >>> True + >>> np.array_equiv([1,2], [[1,2],[1,3]]) + >>> False + """ try: a1, a2 = asarray(a1), asarray(a2) @@ -1598,31 +1683,73 @@ for key in _errdict.keys(): del key def seterr(all=None, divide=None, over=None, under=None, invalid=None): - """Set how floating-point errors are handled. - - Valid values for each type of error are the strings - "ignore", "warn", "raise", and "call". Returns the old settings. - If 'all' is specified, values that are not otherwise specified - will be set to 'all', otherwise they will retain their old - values. + """ + Set how floating-point errors are handled. Note that operations on integer scalar types (such as int16) are handled like floating point, and are affected by these settings. - Example: + Parameters + ---------- + all : {'ignore', 'warn', 'raise', 'call'}, optional + Set treatment for all types of floating-point errors at once: + + - ignore: Take no action when the exception occurs + - warn: Print a RuntimeWarning (via the Python `warnings` module) + - raise: Raise a FloatingPointError + - call: Call a function specified using the `seterrcall` function. + + The default is not to change the current behavior. + divide : {'ignore', 'warn', 'raise', 'call'}, optional + Treatment for division by zero. + over : {'ignore', 'warn', 'raise', 'call'}, optional + Treatment for floating-point overflow. + under : {'ignore', 'warn', 'raise', 'call'}, optional + Treatment for floating-point underflow. + invalid : {'ignore', 'warn', 'raise', 'call'}, optional + Treatment for invalid floating-point operation. + + Returns + ------- + old_settings : dict + Dictionary containing the old settings. + + See also + -------- + seterrcall : set a callback function for the 'call' mode. + geterr, geterrcall + + Notes + ----- + The floating-point exceptions are defined in the IEEE 754 standard [1]: + + - Division by zero: infinite result obtained from finite numbers. + - Overflow: result too large to be expressed. + - Underflow: result so close to zero that some precision + was lost. + - Invalid operation: result is not an expressible number, typically + indicates that a NaN was produced. + + .. [1] http://en.wikipedia.org/wiki/IEEE_754 + + Examples + -------- + + Set mode: >>> seterr(over='raise') # doctest: +SKIP - {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} + {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', + 'under': 'ignore'} - >>> seterr(all='warn', over='raise') # doctest: +SKIP - {'over': 'raise', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} + >>> old_settings = seterr(all='warn', over='raise') # doctest: +SKIP >>> int16(32000) * int16(3) # doctest: +SKIP Traceback (most recent call last): File "<stdin>", line 1, in ? FloatingPointError: overflow encountered in short_scalars >>> seterr(all='ignore') # doctest: +SKIP - {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} + {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', + 'under': 'ignore'} """ @@ -1665,7 +1792,14 @@ def geterr(): return res def setbufsize(size): - """Set the size of the buffer used in ufuncs. + """ + Set the size of the buffer used in ufuncs. + + Parameters + ---------- + size : int + Size of buffer. + """ if size > 10e6: raise ValueError, "Buffer size, %s, is too big." % size diff --git a/numpy/core/numerictypes.py b/numpy/core/numerictypes.py index 8a89f40c6..3d34ceb7f 100644 --- a/numpy/core/numerictypes.py +++ b/numpy/core/numerictypes.py @@ -662,7 +662,8 @@ def _find_common_coerce(a, b): def find_common_type(array_types, scalar_types): - """Determine common type following standard coercion rules + """ + Determine common type following standard coercion rules Parameters ---------- @@ -679,6 +680,11 @@ def find_common_type(array_types, scalar_types): is of a different kind. If the kinds is not understood, then None is returned. + + See Also + -------- + dtype + """ array_types = [dtype(x) for x in array_types] scalar_types = [dtype(x) for x in scalar_types] |