python 100_Numpy_exercises (2)

31. How to ignore all numpy warnings (not recommended)? (★☆☆)

# Suicide mode on
defaults = np.seterr(all="ignore")
Z = np.ones(1) / 0

# Back to sanity
_ = np.seterr(**defaults)

An equivalent way, with a context manager:

with np.errstate(divide='ignore'):
    Z = np.ones(1) / 0

32. Is the following expressions true? (★☆☆)

np.sqrt(-1) == np.emath.sqrt(-1)
import numpy as np
print (np.sqrt(-1))#实数
print (np.emath.sqrt(-1))#复数
nan
1j
D:\software\Anaconda\anaconda\lib\site-packages\ipykernel_launcher.py:2: RuntimeWarning: invalid value encountered in sqrt

33. How to get the dates of yesterday, today and tomorrow? (★☆☆)

yesterday = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
today     = np.datetime64('today', 'D')
tomorrow  = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
print (yesterday)
print (today)
print (tomorrow)
2019-03-06
2019-03-07
2019-03-09

34. How to get all the dates corresponding to the month of July 2016? (★★☆)

Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]')
print(Z)
['2016-07-01' '2016-07-02' '2016-07-03' '2016-07-04' '2016-07-05'
 '2016-07-06' '2016-07-07' '2016-07-08' '2016-07-09' '2016-07-10'
 '2016-07-11' '2016-07-12' '2016-07-13' '2016-07-14' '2016-07-15'
 '2016-07-16' '2016-07-17' '2016-07-18' '2016-07-19' '2016-07-20'
 '2016-07-21' '2016-07-22' '2016-07-23' '2016-07-24' '2016-07-25'
 '2016-07-26' '2016-07-27' '2016-07-28' '2016-07-29' '2016-07-30'
 '2016-07-31']

35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)

a = np.ones((3,3))
b = np.ones((3,3))*2
print (a)
print (b)
np.add(a,b,out = b)
# print (a)
print (b)
np.negative(np.divide(a,2,out = a),out = a)
np.multiply(b,a)
[[ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]]
[[ 2.  2.  2.]
 [ 2.  2.  2.]
 [ 2.  2.  2.]]
[[ 3.  3.  3.]
 [ 3.  3.  3.]
 [ 3.  3.  3.]]
array([[-1.5, -1.5, -1.5],
       [-1.5, -1.5, -1.5],
       [-1.5, -1.5, -1.5]])
import numpy as np
x1 = np.arange(9.0).reshape((3, 3))
print (x1)
x2 = np.arange(3.0)
print (x2)
np.add(x1, x2)
[[ 0.  1.  2.]
 [ 3.  4.  5.]
 [ 6.  7.  8.]]
[ 0.  1.  2.]
array([[  0.,   2.,   4.],
       [  3.,   5.,   7.],
       [  6.,   8.,  10.]])
import numpy as np
np.info(np.add)
add(x1, x2[, out])

Add arguments element-wise.

Parameters
----------
x1, x2 : array_like
    The arrays to be added.  If ``x1.shape != x2.shape``, they must be
    broadcastable to a common shape (which may be the shape of one or
    the other).

Returns
-------
add : ndarray or scalar
    The sum of `x1` and `x2`, element-wise.  Returns a scalar if
    both  `x1` and `x2` are scalars.

Notes
-----
Equivalent to `x1` + `x2` in terms of array broadcasting.

Examples
--------
>>> np.add(1.0, 4.0)
5.0
>>> x1 = np.arange(9.0).reshape((3, 3))
>>> x2 = np.arange(3.0)
>>> np.add(x1, x2)
array([[  0.,   2.,   4.],
       [  3.,   5.,   7.],
       [  6.,   8.,  10.]])

36. Extract the integer part of a random array using 5 different methods (★★☆)

import numpy as np
a = np.random.uniform(1,10,3)
print (a)
b = a-a%1
print (b)
[ 5.68428275  6.46149097  1.74833976]
[ 5.  6.  1.]
import numpy as np
a = np.random.uniform(1,10,3)
print (a)
b = np.ceil(a)-1
print (b)
[ 5.73062958  4.83969552  2.19314448]
[ 5.  4.  2.]
import numpy as np
a = np.random.uniform(1,10,3)
print (a)
b = np.floor(a)
print (b)
[ 9.71114723  5.91123853  1.34266563]
[ 9.  5.  1.]
import numpy as np
a = np.random.uniform(1,10,3)
print (a)
b = a.astype(int)
print (b)
[ 4.57905255  6.74753994  8.26644833]
[4 6 8]
import numpy as np
a = np.random.uniform(1,10,3)
print (a)
b = np.trunc(a)
print (b)
[ 4.04213929  2.44154839  2.88524378]
[ 4.  2.  2.]
np.info(np.trunc)
trunc(x[, out])

Return the truncated value of the input, element-wise.

The truncated value of the scalar `x` is the nearest integer `i` which
is closer to zero than `x` is. In short, the fractional part of the
signed number `x` is discarded.

Parameters
----------
x : array_like
    Input data.

Returns
-------
y : ndarray or scalar
    The truncated value of each element in `x`.

See Also
--------
ceil, floor, rint

Notes
-----
.. versionadded:: 1.3.0

Examples
--------
>>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0])
>>> np.trunc(a)
array([-1., -1., -0.,  0.,  1.,  1.,  2.])

37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)

a = np.random.uniform(0,4,(5,5))
print (a)
[[ 3.68059573  2.89217004  3.93373932  1.89988404  3.31816657]
 [ 3.12213533  0.07068453  0.18528237  1.6167759   0.82046869]
 [ 0.37539813  1.50022606  3.3097724   2.90741528  0.01809809]
 [ 3.70381829  0.75977331  1.75437137  1.53818723  3.51736614]
 [ 1.40856755  0.92131058  3.86188851  0.8925987   3.67647075]]
a = np.zeros((5,5))
a += range (0,5)
print (a)
[[ 0.  1.  2.  3.  4.]
 [ 0.  1.  2.  3.  4.]
 [ 0.  1.  2.  3.  4.]
 [ 0.  1.  2.  3.  4.]
 [ 0.  1.  2.  3.  4.]]

38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)

def func():
    for i in range(10):
        yield i
   
a = np.fromiter(func(),dtype=float, count=-1)
print(a)
[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.]
 np.info(np.fromiter)
fromiter(iterable, dtype, count=-1)

Create a new 1-dimensional array from an iterable object.

Parameters
----------
iterable : iterable object
    An iterable object providing data for the array.
dtype : data-type
    The data-type of the returned array.
count : int, optional
    The number of items to read from *iterable*.  The default is -1,
    which means all data is read.

Returns
-------
out : ndarray
    The output array.

Notes
-----
Specify `count` to improve performance.  It allows ``fromiter`` to
pre-allocate the output array, instead of resizing it on demand.

Examples
--------
>>> iterable = (x*x for x in range(5))
>>> np.fromiter(iterable, np.float)
array([  0.,   1.,   4.,   9.,  16.])

39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)

np.info(np.linspace)
 linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

Return evenly spaced numbers over a specified interval.

Returns `num` evenly spaced samples, calculated over the
interval [`start`, `stop`].

The endpoint of the interval can optionally be excluded.

Parameters
----------
start : scalar
    The starting value of the sequence.
stop : scalar
    The end value of the sequence, unless `endpoint` is set to False.
    In that case, the sequence consists of all but the last of ``num + 1``
    evenly spaced samples, so that `stop` is excluded.  Note that the step
    size changes when `endpoint` is False.
num : int, optional
    Number of samples to generate. Default is 50. Must be non-negative.
endpoint : bool, optional
    If True, `stop` is the last sample. Otherwise, it is not included.
    Default is True.
retstep : bool, optional
    If True, return (`samples`, `step`), where `step` is the spacing
    between samples.
dtype : dtype, optional
    The type of the output array.  If `dtype` is not given, infer the data
    type from the other input arguments.

    .. versionadded:: 1.9.0

Returns
-------
samples : ndarray
    There are `num` equally spaced samples in the closed interval
    ``[start, stop]`` or the half-open interval ``[start, stop)``
    (depending on whether `endpoint` is True or False).
step : float, optional
    Only returned if `retstep` is True

    Size of spacing between samples.


See Also
--------
arange : Similar to `linspace`, but uses a step size (instead of the
         number of samples).
logspace : Samples uniformly distributed in log space.

Examples
--------
>>> np.linspace(2.0, 3.0, num=5)
array([ 2.  ,  2.25,  2.5 ,  2.75,  3.  ])
>>> np.linspace(2.0, 3.0, num=5, endpoint=False)
array([ 2. ,  2.2,  2.4,  2.6,  2.8])
>>> np.linspace(2.0, 3.0, num=5, retstep=True)
(array([ 2.  ,  2.25,  2.5 ,  2.75,  3.  ]), 0.25)

Graphical illustration:

>>> import matplotlib.pyplot as plt
>>> N = 8
>>> y = np.zeros(N)
>>> x1 = np.linspace(0, 10, N, endpoint=True)
>>> x2 = np.linspace(0, 10, N, endpoint=False)
>>> plt.plot(x1, y, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.plot(x2, y + 0.5, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.ylim([-0.5, 1])
(-0.5, 1)
>>> plt.show()
a = np.linspace(0,1,num=11,endpoint=False)[1:]
print (a)
[ 0.09090909  0.18181818  0.27272727  0.36363636  0.45454545  0.54545455
  0.63636364  0.72727273  0.81818182  0.90909091]

40. Create a random vector of size 10 and sort it (★★☆)

a = np.random.rand(10)
print (a)
print (sorted(a))
print (a)
[ 0.12869995  0.97825072  0.06260481  0.10932202  0.40136214  0.9808369
  0.22498057  0.02908049  0.73547941  0.56994736]
[0.029080487074700012, 0.062604806619652731, 0.10932202350502584, 0.12869994535209672, 0.22498057120505621, 0.40136214089195832, 0.56994736490402698, 0.73547940896389297, 0.97825072255312717, 0.98083689547423358]
[ 0.12869995  0.97825072  0.06260481  0.10932202  0.40136214  0.9808369
  0.22498057  0.02908049  0.73547941  0.56994736]
import numpy as np
b = np.random.random(10)
print (b)
b.sort()
print (b)
[ 0.76820341  0.02707929  0.36731303  0.21244074  0.19710842  0.75782414
  0.59247559  0.12764781  0.64853382  0.75124953]
[ 0.02707929  0.12764781  0.19710842  0.21244074  0.36731303  0.59247559
  0.64853382  0.75124953  0.75782414  0.76820341]

41. How to sum a small array faster than np.sum? (★★☆)

a = np.random.random(10)
print (np.sum(a))
print (np.add.reduce(a))
6.18901918977
6.18901918977
np.info(np.add.reduce)
reduce(a, axis=0, dtype=None, out=None, keepdims=False)

Reduces `a`'s dimension by one, by applying ufunc along one axis.

Let :math:`a.shape = (N_0, ..., N_i, ..., N_{M-1})`.  Then
:math:`ufunc.reduce(a, axis=i)[k_0, ..,k_{i-1}, k_{i+1}, .., k_{M-1}]` =
the result of iterating `j` over :math:`range(N_i)`, cumulatively applying
ufunc to each :math:`a[k_0, ..,k_{i-1}, j, k_{i+1}, .., k_{M-1}]`.
For a one-dimensional array, reduce produces results equivalent to:
::

 r = op.identity # op = ufunc
 for i in range(len(A)):
   r = op(r, A[i])
 return r

For example, add.reduce() is equivalent to sum().

Parameters
----------
a : array_like
    The array to act on.
axis : None or int or tuple of ints, optional
    Axis or axes along which a reduction is performed.
    The default (`axis` = 0) is perform a reduction over the first
    dimension of the input array. `axis` may be negative, in
    which case it counts from the last to the first axis.

    .. versionadded:: 1.7.0

    If this is `None`, a reduction is performed over all the axes.
    If this is a tuple of ints, a reduction is performed on multiple
    axes, instead of a single axis or all the axes as before.

    For operations which are either not commutative or not associative,
    doing a reduction over multiple axes is not well-defined. The
    ufuncs do not currently raise an exception in this case, but will
    likely do so in the future.
dtype : data-type code, optional
    The type used to represent the intermediate results. Defaults
    to the data-type of the output array if this is provided, or
    the data-type of the input array if no output array is provided.
out : ndarray, optional
    A location into which the result is stored. If not provided, a
    freshly-allocated array is returned.
keepdims : bool, optional
    If this is set to True, the axes which are reduced are left
    in the result as dimensions with size one. With this option,
    the result will broadcast correctly against the original `arr`.

    .. versionadded:: 1.7.0

Returns
-------
r : ndarray
    The reduced array. If `out` was supplied, `r` is a reference to it.

Examples
--------
>>> np.multiply.reduce([2,3,5])
30

A multi-dimensional array example:

>>> X = np.arange(8).reshape((2,2,2))
>>> X
array([[[0, 1],
        [2, 3]],
       [[4, 5],
        [6, 7]]])
>>> np.add.reduce(X, 0)
array([[ 4,  6],
       [ 8, 10]])
>>> np.add.reduce(X) # confirm: default axis value is 0
array([[ 4,  6],
       [ 8, 10]])
>>> np.add.reduce(X, 1)
array([[ 2,  4],
       [10, 12]])
>>> np.add.reduce(X, 2)
array([[ 1,  5],
       [ 9, 13]])

42. Consider two random array A and B, check if they are equal (★★☆)

a = np.random.random(9)
b = np.random.random(10)
print (a == b)
print (a.all == b.all)
print (a.any == b.any)

# Assuming identical shape of the arrays and a tolerance for the comparison of values
equal = np.allclose(a,b)
print(equal)

# Checking both the shape and the element values, no tolerance (values have to be exactly equal)
equal = np.array_equal(a,b)
print(equal)
False
False
False
False
D:\software\Anaconda\anaconda\lib\site-packages\ipykernel_launcher.py:3: DeprecationWarning: elementwise == comparison failed; this will raise an error in the future.
  This is separate from the ipykernel package so we can avoid doing imports until
np.info(np.allclose)
 allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)

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` * abs(`b`)) and the absolute difference
`atol` are added together to compare against the absolute difference
between `a` and `b`.

If either array contains one or more NaNs, False is returned.
Infs are treated as equal if they are in the same place and of the same
sign in both arrays.

Parameters
----------
a, b : array_like
    Input arrays to compare.
rtol : float
    The relative tolerance parameter (see Notes).
atol : float
    The absolute tolerance parameter (see Notes).
equal_nan : bool
    Whether to compare NaN's as equal.  If True, NaN's in `a` will be
    considered equal to NaN's in `b` in the output array.

    .. versionadded:: 1.10.0

Returns
-------
allclose : bool
    Returns True if the two arrays are equal within the given
    tolerance; False otherwise.

See Also
--------
isclose, all, any

Notes
-----
If the following equation is element-wise True, then allclose returns
True.

 absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))

The above equation is not symmetric in `a` and `b`, so that
`allclose(a, b)` might be different from `allclose(b, a)` in
some rare cases.

Examples
--------
>>> np.allclose([1e10,1e-7], [1.00001e10,1e-8])
False
>>> np.allclose([1e10,1e-8], [1.00001e10,1e-9])
True
>>> np.allclose([1e10,1e-8], [1.0001e10,1e-9])
False
>>> np.allclose([1.0, np.nan], [1.0, np.nan])
False
>>> np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
True

43. Make an array immutable (read-only) (★★☆)

a = np.zeros(10)
print(a)
a[1]=10
print (a)
a.flags.writeable = False
a[1]=10
print (a)
[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
[  0.  10.   0.   0.   0.   0.   0.   0.   0.   0.]
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-26-1d00db5deb41> in <module>()
      4 print (a)
      5 a.flags.writeable = False
----> 6 a[1]=10
      7 print (a)


ValueError: assignment destination is read-only

44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)

a = np.random.random((10,2))
print (a)
x = a[:,0]
y = a[:,1]
r = np.sqrt(x**2,y**2)
t = np.arctan2(y,x)
print (r)
print (t)
[[ 0.93183414  0.18096337]
 [ 0.17387315  0.99035121]
 [ 0.74953991  0.44353838]
 [ 0.06894447  0.10457858]
 [ 0.72181864  0.78149792]
 [ 0.38915937  0.77454756]
 [ 0.5906974   0.07230065]
 [ 0.80032517  0.1491309 ]
 [ 0.1975315   0.75100206]
 [ 0.01342065  0.11582104]]
[ 0.93183414  0.17387315  0.74953991  0.06894447  0.72181864  0.38915937
  0.5906974   0.80032517  0.1975315   0.01342065]
[ 0.19181369  1.3970004   0.5343294   0.98793897  0.82507574  1.10520306
  0.12179299  0.18422507  1.31359792  1.45543676]

45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)

a = np.random.random(10)
print (a)
a[a.argmax()]=0
print (a)
[ 0.19294392  0.88312014  0.28297877  0.45038222  0.89854777  0.13456092
  0.97489591  0.81389236  0.19777349  0.55851379]
[ 0.19294392  0.88312014  0.28297877  0.45038222  0.89854777  0.13456092
  0.          0.81389236  0.19777349  0.55851379]
a = np.random.random((1,10))
print (a)
[[ 0.60636462  0.07999988  0.09233688  0.26772648  0.81560924  0.92450679
   0.36806385  0.11097715  0.70961291  0.52572634]]
a = np.random.random(10)
print (a)
a.max() 
[ 0.07676293  0.7411526   0.63484462  0.45547585  0.06211703  0.80376089
  0.4347154   0.24959182  0.01888837  0.21201277]
0.80376088518364786

46. Create a structured array with x and y coordinates covering the [0,1]x[0,1] area (★★☆)

a = np.zeros((5,5),dtype=[('x',float),('y',float)])
a['x'],a['y'] = np.meshgrid(np.linspace(0,1,5),np.linspace(0,1,5))
print (a)
[[( 0.  ,  0.  ) ( 0.25,  0.  ) ( 0.5 ,  0.  ) ( 0.75,  0.  )
  ( 1.  ,  0.  )]
 [( 0.  ,  0.25) ( 0.25,  0.25) ( 0.5 ,  0.25) ( 0.75,  0.25)
  ( 1.  ,  0.25)]
 [( 0.  ,  0.5 ) ( 0.25,  0.5 ) ( 0.5 ,  0.5 ) ( 0.75,  0.5 )
  ( 1.  ,  0.5 )]
 [( 0.  ,  0.75) ( 0.25,  0.75) ( 0.5 ,  0.75) ( 0.75,  0.75)
  ( 1.  ,  0.75)]
 [( 0.  ,  1.  ) ( 0.25,  1.  ) ( 0.5 ,  1.  ) ( 0.75,  1.  )
  ( 1.  ,  1.  )]]
help(np.meshgrid)
Help on function meshgrid in module numpy.lib.function_base:

meshgrid(*xi, **kwargs)
    Return coordinate matrices from coordinate vectors.
    
    Make N-D coordinate arrays for vectorized evaluations of
    N-D scalar/vector fields over N-D grids, given
    one-dimensional coordinate arrays x1, x2,..., xn.
    
    .. versionchanged:: 1.9
       1-D and 0-D cases are allowed.
    
    Parameters
    ----------
    x1, x2,..., xn : array_like
        1-D arrays representing the coordinates of a grid.
    indexing : {'xy', 'ij'}, optional
        Cartesian ('xy', default) or matrix ('ij') indexing of output.
        See Notes for more details.
    
        .. versionadded:: 1.7.0
    sparse : bool, optional
        If True a sparse grid is returned in order to conserve memory.
        Default is False.
    
        .. versionadded:: 1.7.0
    copy : bool, optional
        If False, a view into the original arrays are returned in order to
        conserve memory.  Default is True.  Please note that
        ``sparse=False, copy=False`` will likely return non-contiguous
        arrays.  Furthermore, more than one element of a broadcast array
        may refer to a single memory location.  If you need to write to the
        arrays, make copies first.
    
        .. versionadded:: 1.7.0
    
    Returns
    -------
    X1, X2,..., XN : ndarray
        For vectors `x1`, `x2`,..., 'xn' with lengths ``Ni=len(xi)`` ,
        return ``(N1, N2, N3,...Nn)`` shaped arrays if indexing='ij'
        or ``(N2, N1, N3,...Nn)`` shaped arrays if indexing='xy'
        with the elements of `xi` repeated to fill the matrix along
        the first dimension for `x1`, the second for `x2` and so on.
    
    Notes
    -----
    This function supports both indexing conventions through the indexing
    keyword argument.  Giving the string 'ij' returns a meshgrid with
    matrix indexing, while 'xy' returns a meshgrid with Cartesian indexing.
    In the 2-D case with inputs of length M and N, the outputs are of shape
    (N, M) for 'xy' indexing and (M, N) for 'ij' indexing.  In the 3-D case
    with inputs of length M, N and P, outputs are of shape (N, M, P) for
    'xy' indexing and (M, N, P) for 'ij' indexing.  The difference is
    illustrated by the following code snippet::
    
        xv, yv = meshgrid(x, y, sparse=False, indexing='ij')
        for i in range(nx):
            for j in range(ny):
                # treat xv[i,j], yv[i,j]
    
        xv, yv = meshgrid(x, y, sparse=False, indexing='xy')
        for i in range(nx):
            for j in range(ny):
                # treat xv[j,i], yv[j,i]
    
    In the 1-D and 0-D case, the indexing and sparse keywords have no effect.
    
    See Also
    --------
    index_tricks.mgrid : Construct a multi-dimensional "meshgrid"
                     using indexing notation.
    index_tricks.ogrid : Construct an open multi-dimensional "meshgrid"
                     using indexing notation.
    
    Examples
    --------
    >>> nx, ny = (3, 2)
    >>> x = np.linspace(0, 1, nx)
    >>> y = np.linspace(0, 1, ny)
    >>> xv, yv = meshgrid(x, y)
    >>> xv
    array([[ 0. ,  0.5,  1. ],
           [ 0. ,  0.5,  1. ]])
    >>> yv
    array([[ 0.,  0.,  0.],
           [ 1.,  1.,  1.]])
    >>> xv, yv = meshgrid(x, y, sparse=True)  # make sparse output arrays
    >>> xv
    array([[ 0. ,  0.5,  1. ]])
    >>> yv
    array([[ 0.],
           [ 1.]])
    
    `meshgrid` is very useful to evaluate functions on a grid.
    
    >>> x = np.arange(-5, 5, 0.1)
    >>> y = np.arange(-5, 5, 0.1)
    >>> xx, yy = meshgrid(x, y, sparse=True)
    >>> z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
    >>> h = plt.contourf(x,y,z)

47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj))

X = np.arange(8)
Y = X + 0.5
C = 1.0 / np.subtract.outer(X, Y)
print(np.linalg.det(C))
3638.16363712
np.info(np.subtract.outer)
outer(A, B, **kwargs)

Apply the ufunc `op` to all pairs (a, b) with a in `A` and b in `B`.

Let ``M = A.ndim``, ``N = B.ndim``. Then the result, `C`, of
``op.outer(A, B)`` is an array of dimension M + N such that:

.. math:: C[i_0, ..., i_{M-1}, j_0, ..., j_{N-1}] =
   op(A[i_0, ..., i_{M-1}], B[j_0, ..., j_{N-1}])

For `A` and `B` one-dimensional, this is equivalent to::

  r = empty(len(A),len(B))
  for i in range(len(A)):
      for j in range(len(B)):
          r[i,j] = op(A[i], B[j]) # op = ufunc in question

Parameters
----------
A : array_like
    First array
B : array_like
    Second array
kwargs : any
    Arguments to pass on to the ufunc. Typically `dtype` or `out`.

Returns
-------
r : ndarray
    Output array

See Also
--------
numpy.outer

Examples
--------
>>> np.multiply.outer([1, 2, 3], [4, 5, 6])
array([[ 4,  5,  6],
       [ 8, 10, 12],
       [12, 15, 18]])

A multi-dimensional example:

>>> A = np.array([[1, 2, 3], [4, 5, 6]])
>>> A.shape
(2, 3)
>>> B = np.array([[1, 2, 3, 4]])
>>> B.shape
(1, 4)
>>> C = np.multiply.outer(A, B)
>>> C.shape; C
(2, 3, 1, 4)
array([[[[ 1,  2,  3,  4]],
        [[ 2,  4,  6,  8]],
        [[ 3,  6,  9, 12]]],
       [[[ 4,  8, 12, 16]],
        [[ 5, 10, 15, 20]],
        [[ 6, 12, 18, 24]]]])

48. Print the minimum and maximum representable value for each numpy scalar type (★★☆)

for dtype in [np.int8, np.int32, np.int64]:
   print(np.iinfo(dtype).min)
   print(np.iinfo(dtype).max)
for dtype in [np.float32, np.float64]:
   print(np.finfo(dtype).min)
   print(np.finfo(dtype).max)
   print(np.finfo(dtype).eps)
-128
127
-2147483648
2147483647
-9223372036854775808
9223372036854775807
-3.40282e+38
3.40282e+38
1.19209e-07
-1.79769313486e+308
1.79769313486e+308
2.22044604925e-16
np.info(np.finfo)
 finfo()

finfo(dtype)

Machine limits for floating point types.

Attributes
----------
bits : int
    The number of bits occupied by the type.
eps : float
    The smallest representable positive number such that
    ``1.0 + eps != 1.0``.  Type of `eps` is an appropriate floating
    point type.
epsneg : floating point number of the appropriate type
    The smallest representable positive number such that
    ``1.0 - epsneg != 1.0``.
iexp : int
    The number of bits in the exponent portion of the floating point
    representation.
machar : MachAr
    The object which calculated these parameters and holds more
    detailed information.
machep : int
    The exponent that yields `eps`.
max : floating point number of the appropriate type
    The largest representable number.
maxexp : int
    The smallest positive power of the base (2) that causes overflow.
min : floating point number of the appropriate type
    The smallest representable number, typically ``-max``.
minexp : int
    The most negative power of the base (2) consistent with there
    being no leading 0's in the mantissa.
negep : int
    The exponent that yields `epsneg`.
nexp : int
    The number of bits in the exponent including its sign and bias.
nmant : int
    The number of bits in the mantissa.
precision : int
    The approximate number of decimal digits to which this kind of
    float is precise.
resolution : floating point number of the appropriate type
    The approximate decimal resolution of this type, i.e.,
    ``10**-precision``.
tiny : float
    The smallest positive usable number.  Type of `tiny` is an
    appropriate floating point type.

Parameters
----------
dtype : float, dtype, or instance
    Kind of floating point data-type about which to get information.

See Also
--------
MachAr : The implementation of the tests that produce this information.
iinfo : The equivalent for integer data types.

Notes
-----
For developers of NumPy: do not instantiate this at the module level.
The initial calculation of these parameters is expensive and negatively
impacts import times.  These objects are cached, so calling ``finfo()``
repeatedly inside your functions is not a problem.


Methods:

49. How to print all the values of an array? (★★☆)

import numpy as np
np.set_printoptions(threshold=np.nan)#设置打印时显示方式,threshold=np.nan意思是输出数组的时候完全输出,不需要省略号将中间数据省略
Z = np.ones((16,16))
print(Z)
[[ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
 [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]]
np.info(np.set_printoptions)
 set_printoptions(precision=None, threshold=None, edgeitems=None,
                  linewidth=None, suppress=None, nanstr=None, infstr=None,
                  formatter=None)

Set printing options.

These options determine the way floating point numbers, arrays and
other NumPy objects are displayed.

Parameters
----------
precision : int, optional
    Number of digits of precision for floating point output (default 8).
threshold : int, optional
    Total number of array elements which trigger summarization
    rather than full repr (default 1000).
edgeitems : int, optional
    Number of array items in summary at beginning and end of
    each dimension (default 3).
linewidth : int, optional
    The number of characters per line for the purpose of inserting
    line breaks (default 75).
suppress : bool, optional
    Whether or not suppress printing of small floating point values
    using scientific notation (default False).
nanstr : str, optional
    String representation of floating point not-a-number (default nan).
infstr : str, optional
    String representation of floating point infinity (default inf).
formatter : dict of callables, optional
    If not None, the keys should indicate the type(s) that the respective
    formatting function applies to.  Callables should return a string.
    Types that are not specified (by their corresponding keys) are handled
    by the default formatters.  Individual types for which a formatter
    can be set are::

        - 'bool'
        - 'int'
        - 'timedelta' : a `numpy.timedelta64`
        - 'datetime' : a `numpy.datetime64`
        - 'float'
        - 'longfloat' : 128-bit floats
        - 'complexfloat'
        - 'longcomplexfloat' : composed of two 128-bit floats
        - 'numpy_str' : types `numpy.string_` and `numpy.unicode_`
        - 'str' : all other strings

    Other keys that can be used to set a group of types at once are::

        - 'all' : sets all types
        - 'int_kind' : sets 'int'
        - 'float_kind' : sets 'float' and 'longfloat'
        - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
        - 'str_kind' : sets 'str' and 'numpystr'

See Also
--------
get_printoptions, set_string_function, array2string

Notes
-----
`formatter` is always reset with a call to `set_printoptions`.

Examples
--------
Floating point precision can be set:

>>> np.set_printoptions(precision=4)
>>> print(np.array([1.123456789]))
[ 1.1235]

Long arrays can be summarised:

>>> np.set_printoptions(threshold=5)
>>> print(np.arange(10))
[0 1 2 ..., 7 8 9]

Small results can be suppressed:

>>> eps = np.finfo(float).eps
>>> x = np.arange(4.)
>>> x**2 - (x + eps)**2
array([ -4.9304e-32,  -4.4409e-16,   0.0000e+00,   0.0000e+00])
>>> np.set_printoptions(suppress=True)
>>> x**2 - (x + eps)**2
array([-0., -0.,  0.,  0.])

A custom formatter can be used to display array elements as desired:

>>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)})
>>> x = np.arange(3)
>>> x
array([int: 0, int: -1, int: -2])
>>> np.set_printoptions()  # formatter gets reset
>>> x
array([0, 1, 2])

To put back the default options, you can use:

>>> np.set_printoptions(edgeitems=3,infstr='inf',
... linewidth=75, nanstr='nan', precision=8,
... suppress=False, threshold=1000, formatter=None)

50. How to find the closest value (to a given scalar) in a vector? (★★☆)

a = 10
b = np.random.random(10)
print (b)
print(b[(b-a).argmin()])
[ 0.98159799  0.21089639  0.13240754  0.54174442  0.24689817  0.30846572
  0.47209303  0.76273758  0.06892561  0.56515725]
0.0689256082123
Z = np.arange(100)
v = np.random.uniform(0,100)
index = (np.abs(Z-v)).argmin()
print(Z[index])
40

51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)

import numpy as np
a = np.zeros(10,[('positon',[('x',float,1),('y',float,1)]),('color',[('r',float,1),('g',float,1),('b',float,1)])])
print (a)
[(( 0.,  0.), ( 0.,  0.,  0.)) (( 0.,  0.), ( 0.,  0.,  0.))
 (( 0.,  0.), ( 0.,  0.,  0.)) (( 0.,  0.), ( 0.,  0.,  0.))
 (( 0.,  0.), ( 0.,  0.,  0.)) (( 0.,  0.), ( 0.,  0.,  0.))
 (( 0.,  0.), ( 0.,  0.,  0.)) (( 0.,  0.), ( 0.,  0.,  0.))
 (( 0.,  0.), ( 0.,  0.,  0.)) (( 0.,  0.), ( 0.,  0.,  0.))]
Z = np.zeros(10, [ ('position', [ ('x', float, 1),
                                  ('y', float, 1)]),
                   ('color',    [ ('r', float, 1),
                                  ('g', float, 1),
                                  ('b', float, 1)])])
print(Z)
[(( 0.,  0.), ( 0.,  0.,  0.)) (( 0.,  0.), ( 0.,  0.,  0.))
 (( 0.,  0.), ( 0.,  0.,  0.)) (( 0.,  0.), ( 0.,  0.,  0.))
 (( 0.,  0.), ( 0.,  0.,  0.)) (( 0.,  0.), ( 0.,  0.,  0.))
 (( 0.,  0.), ( 0.,  0.,  0.)) (( 0.,  0.), ( 0.,  0.,  0.))
 (( 0.,  0.), ( 0.,  0.,  0.)) (( 0.,  0.), ( 0.,  0.,  0.))]
help(np.zeros)
Help on built-in function zeros in module numpy.core.multiarray:

zeros(...)
    zeros(shape, dtype=float, order='C')
    
    Return a new array of given shape and type, filled with zeros.
    
    Parameters
    ----------
    shape : int or sequence of ints
        Shape of the new array, e.g., ``(2, 3)`` or ``2``.
    dtype : data-type, optional
        The desired data-type for the array, e.g., `numpy.int8`.  Default is
        `numpy.float64`.
    order : {'C', 'F'}, optional
        Whether to store multidimensional data in C- or Fortran-contiguous
        (row- or column-wise) order in memory.
    
    Returns
    -------
    out : ndarray
        Array of zeros with the given shape, dtype, and order.
    
    See Also
    --------
    zeros_like : Return an array of zeros with shape and type of input.
    ones_like : Return an array of ones with shape and type of input.
    empty_like : Return an empty array with shape and type of input.
    ones : Return a new array setting values to one.
    empty : Return a new uninitialized array.
    
    Examples
    --------
    >>> np.zeros(5)
    array([ 0.,  0.,  0.,  0.,  0.])
    
    >>> np.zeros((5,), dtype=np.int)
    array([0, 0, 0, 0, 0])
    
    >>> np.zeros((2, 1))
    array([[ 0.],
           [ 0.]])
    
    >>> s = (2,2)
    >>> np.zeros(s)
    array([[ 0.,  0.],
           [ 0.,  0.]])
    
    >>> np.zeros((2,), dtype=[('x', 'i4'), ('y', 'i4')]) # custom dtype
    array([(0, 0), (0, 0)],
          dtype=[('x', '<i4'), ('y', '<i4')])

52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)

Z = np.random.random((10,2))
X,Y = np.atleast_2d(Z[:,0], Z[:,1])#atleast_xd 支持将输入数据直接视为 x维。这里的 x 可以表示:1,2,3。
print (X)
print (Y)
D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
print(D)
[[ 0.44138907  0.29918868  0.23304832  0.26770122  0.41607465  0.00176153
   0.09544169  0.25789577  0.85804698  0.08941344]]
[[ 0.42708203  0.7270007   0.7988682   0.98668447  0.09908152  0.34126512
   0.66802988  0.3331608   0.92373453  0.07639324]]
[[ 0.          0.33192192  0.42618168  0.58593717  0.32897592  0.44792513
   0.42158683  0.20613342  0.64828044  0.4968596 ]
 [ 0.33192192  0.          0.09767028  0.26158578  0.63870559  0.48708813
   0.21210939  0.3959987   0.59247515  0.68359031]
 [ 0.42618168  0.09767028  0.          0.19098632  0.72332568  0.51273205
   0.18987957  0.46636979  0.63734993  0.73661458]
 [ 0.58593717  0.26158578  0.19098632  0.          0.8999187   0.69806164
   0.36223486  0.65359723  0.59369252  0.92758646]
 [ 0.32897592  0.63870559  0.72332568  0.8999187   0.          0.47990443
   0.6530756   0.28251313  0.93562393  0.32744817]
 [ 0.44792513  0.48708813  0.51273205  0.69806164  0.47990443  0.
   0.3399282   0.25626242  1.03561354  0.27899815]
 [ 0.42158683  0.21210939  0.18987957  0.36223486  0.6530756   0.3399282
   0.          0.37219435  0.80433308  0.59166735]
 [ 0.20613342  0.3959987   0.46636979  0.65359723  0.28251313  0.25626242
   0.37219435  0.          0.84199692  0.30710889]
 [ 0.64828044  0.59247515  0.63734993  0.59369252  0.93562393  1.03561354
   0.80433308  0.84199692  0.          1.14402132]
 [ 0.4968596   0.68359031  0.73661458  0.92758646  0.32744817  0.27899815
   0.59166735  0.30710889  1.14402132  0.        ]]
# Much faster with scipy
import scipy
# Thanks Gavin Heverly-Coulson (#issue 1)
import scipy.spatial

Z = np.random.random((10,2))
D = scipy.spatial.distance.cdist(Z,Z)
print(D)
[[ 0.          0.37355215  0.43101368  0.52312031  0.12892219  0.25040969
   0.27045939  0.48903912  0.37144876  0.5597968 ]
 [ 0.37355215  0.          0.71962441  0.84098307  0.49888232  0.40318557
   0.56444233  0.81230073  0.4731083   0.6893876 ]
 [ 0.43101368  0.71962441  0.          0.13587573  0.33809344  0.66703904
   0.16341824  0.6684223   0.33012293  0.31223928]
 [ 0.52312031  0.84098307  0.13587573  0.          0.41051874  0.73947493
   0.2765436   0.65715884  0.46587393  0.42218977]
 [ 0.12892219  0.49888232  0.33809344  0.41051874  0.          0.33104942
   0.19622664  0.42916353  0.38339477  0.53249381]
 [ 0.25040969  0.40318557  0.66703904  0.73947493  0.33104942  0.
   0.51346288  0.43471158  0.60943049  0.80798476]
 [ 0.27045939  0.56444233  0.16341824  0.2765436   0.19622664  0.51346288
   0.          0.59119599  0.25221398  0.34717448]
 [ 0.48903912  0.81230073  0.6684223   0.65715884  0.42916353  0.43471158
   0.59119599  0.          0.81170845  0.93767208]
 [ 0.37144876  0.4731083   0.33012293  0.46587393  0.38339477  0.60943049
   0.25221398  0.81170845  0.          0.21956949]
 [ 0.5597968   0.6893876   0.31223928  0.42218977  0.53249381  0.80798476
   0.34717448  0.93767208  0.21956949  0.        ]]
help(scipy.spatial.distance.cdist)
Help on function cdist in module scipy.spatial.distance:

cdist(XA, XB, metric='euclidean', p=None, V=None, VI=None, w=None)
    Computes distance between each pair of the two collections of inputs.
    
    See Notes for common calling conventions.
    
    Parameters
    ----------
    XA : ndarray
        An :math:`m_A` by :math:`n` array of :math:`m_A`
        original observations in an :math:`n`-dimensional space.
        Inputs are converted to float type.
    XB : ndarray
        An :math:`m_B` by :math:`n` array of :math:`m_B`
        original observations in an :math:`n`-dimensional space.
        Inputs are converted to float type.
    metric : str or callable, optional
        The distance metric to use.  If a string, the distance function can be
        'braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation',
        'cosine', 'dice', 'euclidean', 'hamming', 'jaccard', 'kulsinski',
        'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao',
        'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean',
        'wminkowski', 'yule'.
    p : double, optional
        The p-norm to apply
        Only for Minkowski, weighted and unweighted. Default: 2.
    w : ndarray, optional
        The weight vector.
        Only for weighted Minkowski. Mandatory
    V : ndarray, optional
        The variance vector
        Only for standardized Euclidean. Default: var(vstack([XA, XB]), axis=0, ddof=1)
    VI : ndarray, optional
        The inverse of the covariance matrix
        Only for Mahalanobis. Default: inv(cov(vstack([XA, XB]).T)).T
    
    Returns
    -------
    Y : ndarray
        A :math:`m_A` by :math:`m_B` distance matrix is returned.
        For each :math:`i` and :math:`j`, the metric
        ``dist(u=XA[i], v=XB[j])`` is computed and stored in the
        :math:`ij` th entry.
    
    Raises
    ------
    ValueError
        An exception is thrown if `XA` and `XB` do not have
        the same number of columns.
    
    Notes
    -----
    The following are common calling conventions:
    
    1. ``Y = cdist(XA, XB, 'euclidean')``
    
       Computes the distance between :math:`m` points using
       Euclidean distance (2-norm) as the distance metric between the
       points. The points are arranged as :math:`m`
       :math:`n`-dimensional row vectors in the matrix X.
    
    2. ``Y = cdist(XA, XB, 'minkowski', p)``
    
       Computes the distances using the Minkowski distance
       :math:`||u-v||_p` (:math:`p`-norm) where :math:`p \geq 1`.
    
    3. ``Y = cdist(XA, XB, 'cityblock')``
    
       Computes the city block or Manhattan distance between the
       points.
    
    4. ``Y = cdist(XA, XB, 'seuclidean', V=None)``
    
       Computes the standardized Euclidean distance. The standardized
       Euclidean distance between two n-vectors ``u`` and ``v`` is
    
       .. math::
    
          \sqrt{\sum {(u_i-v_i)^2 / V[x_i]}}.
    
       V is the variance vector; V[i] is the variance computed over all
       the i'th components of the points. If not passed, it is
       automatically computed.
    
    5. ``Y = cdist(XA, XB, 'sqeuclidean')``
    
       Computes the squared Euclidean distance :math:`||u-v||_2^2` between
       the vectors.
    
    6. ``Y = cdist(XA, XB, 'cosine')``
    
       Computes the cosine distance between vectors u and v,
    
       .. math::
    
          1 - \frac{u \cdot v}
                   {{||u||}_2 {||v||}_2}
    
       where :math:`||*||_2` is the 2-norm of its argument ``*``, and
       :math:`u \cdot v` is the dot product of :math:`u` and :math:`v`.
    
    7. ``Y = cdist(XA, XB, 'correlation')``
    
       Computes the correlation distance between vectors u and v. This is
    
       .. math::
    
          1 - \frac{(u - \bar{u}) \cdot (v - \bar{v})}
                   {{||(u - \bar{u})||}_2 {||(v - \bar{v})||}_2}
    
       where :math:`\bar{v}` is the mean of the elements of vector v,
       and :math:`x \cdot y` is the dot product of :math:`x` and :math:`y`.
    
    
    8. ``Y = cdist(XA, XB, 'hamming')``
    
       Computes the normalized Hamming distance, or the proportion of
       those vector elements between two n-vectors ``u`` and ``v``
       which disagree. To save memory, the matrix ``X`` can be of type
       boolean.
    
    9. ``Y = cdist(XA, XB, 'jaccard')``
    
       Computes the Jaccard distance between the points. Given two
       vectors, ``u`` and ``v``, the Jaccard distance is the
       proportion of those elements ``u[i]`` and ``v[i]`` that
       disagree where at least one of them is non-zero.
    
    10. ``Y = cdist(XA, XB, 'chebyshev')``
    
       Computes the Chebyshev distance between the points. The
       Chebyshev distance between two n-vectors ``u`` and ``v`` is the
       maximum norm-1 distance between their respective elements. More
       precisely, the distance is given by
    
       .. math::
    
          d(u,v) = \max_i {|u_i-v_i|}.
    
    11. ``Y = cdist(XA, XB, 'canberra')``
    
       Computes the Canberra distance between the points. The
       Canberra distance between two points ``u`` and ``v`` is
    
       .. math::
    
         d(u,v) = \sum_i \frac{|u_i-v_i|}
                              {|u_i|+|v_i|}.
    
    12. ``Y = cdist(XA, XB, 'braycurtis')``
    
       Computes the Bray-Curtis distance between the points. The
       Bray-Curtis distance between two points ``u`` and ``v`` is
    
    
       .. math::
    
            d(u,v) = \frac{\sum_i (|u_i-v_i|)}
                          {\sum_i (|u_i+v_i|)}
    
    13. ``Y = cdist(XA, XB, 'mahalanobis', VI=None)``
    
       Computes the Mahalanobis distance between the points. The
       Mahalanobis distance between two points ``u`` and ``v`` is
       :math:`\sqrt{(u-v)(1/V)(u-v)^T}` where :math:`(1/V)` (the ``VI``
       variable) is the inverse covariance. If ``VI`` is not None,
       ``VI`` will be used as the inverse covariance matrix.
    
    14. ``Y = cdist(XA, XB, 'yule')``
    
       Computes the Yule distance between the boolean
       vectors. (see `yule` function documentation)
    
    15. ``Y = cdist(XA, XB, 'matching')``
    
       Synonym for 'hamming'.
    
    16. ``Y = cdist(XA, XB, 'dice')``
    
       Computes the Dice distance between the boolean vectors. (see
       `dice` function documentation)
    
    17. ``Y = cdist(XA, XB, 'kulsinski')``
    
       Computes the Kulsinski distance between the boolean
       vectors. (see `kulsinski` function documentation)
    
    18. ``Y = cdist(XA, XB, 'rogerstanimoto')``
    
       Computes the Rogers-Tanimoto distance between the boolean
       vectors. (see `rogerstanimoto` function documentation)
    
    19. ``Y = cdist(XA, XB, 'russellrao')``
    
       Computes the Russell-Rao distance between the boolean
       vectors. (see `russellrao` function documentation)
    
    20. ``Y = cdist(XA, XB, 'sokalmichener')``
    
       Computes the Sokal-Michener distance between the boolean
       vectors. (see `sokalmichener` function documentation)
    
    21. ``Y = cdist(XA, XB, 'sokalsneath')``
    
       Computes the Sokal-Sneath distance between the vectors. (see
       `sokalsneath` function documentation)
    
    
    22. ``Y = cdist(XA, XB, 'wminkowski')``
    
       Computes the weighted Minkowski distance between the
       vectors. (see `wminkowski` function documentation)
    
    23. ``Y = cdist(XA, XB, f)``
    
       Computes the distance between all pairs of vectors in X
       using the user supplied 2-arity function f. For example,
       Euclidean distance between the vectors could be computed
       as follows::
    
         dm = cdist(XA, XB, lambda u, v: np.sqrt(((u-v)**2).sum()))
    
       Note that you should avoid passing a reference to one of
       the distance functions defined in this library. For example,::
    
         dm = cdist(XA, XB, sokalsneath)
    
       would calculate the pair-wise distances between the vectors in
       X using the Python function `sokalsneath`. This would result in
       sokalsneath being called :math:`{n \choose 2}` times, which
       is inefficient. Instead, the optimized C version is more
       efficient, and we call it using the following syntax::
    
         dm = cdist(XA, XB, 'sokalsneath')
    
    Examples
    --------
    Find the Euclidean distances between four 2-D coordinates:
    
    >>> from scipy.spatial import distance
    >>> coords = [(35.0456, -85.2672),
    ...           (35.1174, -89.9711),
    ...           (35.9728, -83.9422),
    ...           (36.1667, -86.7833)]
    >>> distance.cdist(coords, coords, 'euclidean')
    array([[ 0.    ,  4.7044,  1.6172,  1.8856],
           [ 4.7044,  0.    ,  6.0893,  3.3561],
           [ 1.6172,  6.0893,  0.    ,  2.8477],
           [ 1.8856,  3.3561,  2.8477,  0.    ]])
    
    
    Find the Manhattan distance from a 3-D point to the corners of the unit
    cube:
    
    >>> a = np.array([[0, 0, 0],
    ...               [0, 0, 1],
    ...               [0, 1, 0],
    ...               [0, 1, 1],
    ...               [1, 0, 0],
    ...               [1, 0, 1],
    ...               [1, 1, 0],
    ...               [1, 1, 1]])
    >>> b = np.array([[ 0.1,  0.2,  0.4]])
    >>> distance.cdist(a, b, 'cityblock')
    array([[ 0.7],
           [ 0.9],
           [ 1.3],
           [ 1.5],
           [ 1.5],
           [ 1.7],
           [ 2.1],
           [ 2.3]])
help(np.atleast_2d)
Help on function atleast_2d in module numpy.core.shape_base:

atleast_2d(*arys)
    View inputs as arrays with at least two dimensions.
    
    Parameters
    ----------
    arys1, arys2, ... : array_like
        One or more array-like sequences.  Non-array inputs are converted
        to arrays.  Arrays that already have two or more dimensions are
        preserved.
    
    Returns
    -------
    res, res2, ... : ndarray
        An array, or list of arrays, each with ``a.ndim >= 2``.
        Copies are avoided where possible, and views with two or more
        dimensions are returned.
    
    See Also
    --------
    atleast_1d, atleast_3d
    
    Examples
    --------
    >>> np.atleast_2d(3.0)
    array([[ 3.]])
    
    >>> x = np.arange(3.0)
    >>> np.atleast_2d(x)
    array([[ 0.,  1.,  2.]])
    >>> np.atleast_2d(x).base is x
    True
    
    >>> np.atleast_2d(1, [1, 2], [[1, 2]])
    [array([[1]]), array([[1, 2]]), array([[1, 2]])]

53. How to convert a float (32 bits) array into an integer (32 bits) in place?

a = np.arange(10,dtype = np.float32)
print (a)
b = a.astype(np.int32,copy = False)
# print (a)
print (b)
[ 0.  1.  2.  3.  4.  5.  6.  7.  8.  9.]
[0 1 2 3 4 5 6 7 8 9]

54. How to read the following file? (★★☆)

1, 2, 3, 4, 5
6,  ,  , 7, 8
 ,  , 9,10,11
help(np.genfromtxt)
Help on function genfromtxt in module numpy.lib.npyio:

genfromtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None, skip_header=0, skip_footer=0, converters=None, missing_values=None, filling_values=None, usecols=None, names=None, excludelist=None, deletechars=None, replace_space='_', autostrip=False, case_sensitive=True, defaultfmt='f%i', unpack=None, usemask=False, loose=True, invalid_raise=True, max_rows=None)
    Load data from a text file, with missing values handled as specified.
    
    Each line past the first `skip_header` lines is split at the `delimiter`
    character, and characters following the `comments` character are discarded.
    
    Parameters
    ----------
    fname : file, str, pathlib.Path, list of str, generator
        File, filename, list, or generator to read.  If the filename
        extension is `.gz` or `.bz2`, the file is first decompressed. Note
        that generators must return byte strings in Python 3k.  The strings
        in a list or produced by a generator are treated as lines.
    dtype : dtype, optional
        Data type of the resulting array.
        If None, the dtypes will be determined by the contents of each
        column, individually.
    comments : str, optional
        The character used to indicate the start of a comment.
        All the characters occurring on a line after a comment are discarded
    delimiter : str, int, or sequence, optional
        The string used to separate values.  By default, any consecutive
        whitespaces act as delimiter.  An integer or sequence of integers
        can also be provided as width(s) of each field.
    skiprows : int, optional
        `skiprows` was removed in numpy 1.10. Please use `skip_header` instead.
    skip_header : int, optional
        The number of lines to skip at the beginning of the file.
    skip_footer : int, optional
        The number of lines to skip at the end of the file.
    converters : variable, optional
        The set of functions that convert the data of a column to a value.
        The converters can also be used to provide a default value
        for missing data: ``converters = {3: lambda s: float(s or 0)}``.
    missing : variable, optional
        `missing` was removed in numpy 1.10. Please use `missing_values`
        instead.
    missing_values : variable, optional
        The set of strings corresponding to missing data.
    filling_values : variable, optional
        The set of values to be used as default when the data are missing.
    usecols : sequence, optional
        Which columns to read, with 0 being the first.  For example,
        ``usecols = (1, 4, 5)`` will extract the 2nd, 5th and 6th columns.
    names : {None, True, str, sequence}, optional
        If `names` is True, the field names are read from the first valid line
        after the first `skip_header` lines.
        If `names` is a sequence or a single-string of comma-separated names,
        the names will be used to define the field names in a structured dtype.
        If `names` is None, the names of the dtype fields will be used, if any.
    excludelist : sequence, optional
        A list of names to exclude. This list is appended to the default list
        ['return','file','print']. Excluded names are appended an underscore:
        for example, `file` would become `file_`.
    deletechars : str, optional
        A string combining invalid characters that must be deleted from the
        names.
    defaultfmt : str, optional
        A format used to define default field names, such as "f%i" or "f_%02i".
    autostrip : bool, optional
        Whether to automatically strip white spaces from the variables.
    replace_space : char, optional
        Character(s) used in replacement of white spaces in the variables
        names. By default, use a '_'.
    case_sensitive : {True, False, 'upper', 'lower'}, optional
        If True, field names are case sensitive.
        If False or 'upper', field names are converted to upper case.
        If 'lower', field names are converted to lower case.
    unpack : bool, optional
        If True, the returned array is transposed, so that arguments may be
        unpacked using ``x, y, z = loadtxt(...)``
    usemask : bool, optional
        If True, return a masked array.
        If False, return a regular array.
    loose : bool, optional
        If True, do not raise errors for invalid values.
    invalid_raise : bool, optional
        If True, an exception is raised if an inconsistency is detected in the
        number of columns.
        If False, a warning is emitted and the offending lines are skipped.
    max_rows : int,  optional
        The maximum number of rows to read. Must not be used with skip_footer
        at the same time.  If given, the value must be at least 1. Default is
        to read the entire file.
    
        .. versionadded:: 1.10.0
    
    Returns
    -------
    out : ndarray
        Data read from the text file. If `usemask` is True, this is a
        masked array.
    
    See Also
    --------
    numpy.loadtxt : equivalent function when no data is missing.
    
    Notes
    -----
    * When spaces are used as delimiters, or when no delimiter has been given
      as input, there should not be any missing data between two fields.
    * When the variables are named (either by a flexible dtype or with `names`,
      there must not be any header in the file (else a ValueError
      exception is raised).
    * Individual values are not stripped of spaces by default.
      When using a custom converter, make sure the function does remove spaces.
    
    References
    ----------
    .. [1] NumPy User Guide, section `I/O with NumPy
           <http://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html>`_.
    
    Examples
    ---------
    >>> from io import StringIO
    >>> import numpy as np
    
    Comma delimited file with mixed dtype
    
    >>> s = StringIO("1,1.3,abcde")
    >>> data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'),
    ... ('mystring','S5')], delimiter=",")
    >>> data
    array((1, 1.3, 'abcde'),
          dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')])
    
    Using dtype = None
    
    >>> s.seek(0) # needed for StringIO example only
    >>> data = np.genfromtxt(s, dtype=None,
    ... names = ['myint','myfloat','mystring'], delimiter=",")
    >>> data
    array((1, 1.3, 'abcde'),
          dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')])
    
    Specifying dtype and names
    
    >>> s.seek(0)
    >>> data = np.genfromtxt(s, dtype="i8,f8,S5",
    ... names=['myint','myfloat','mystring'], delimiter=",")
    >>> data
    array((1, 1.3, 'abcde'),
          dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', '|S5')])
    
    An example with fixed-width columns
    
    >>> s = StringIO("11.3abcde")
    >>> data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'],
    ...     delimiter=[1,3,5])
    >>> data
    array((1, 1.3, 'abcde'),
          dtype=[('intvar', '<i8'), ('fltvar', '<f8'), ('strvar', '|S5')])
from io import StringIO
import numpy as np
# Fake file 
s = StringIO()
s.write('''1, 2, 3, 4, 5\n6,  ,  , 7, 8\n,  , 9, 10, 11\n''')
print (s)
print (s.getvalue())
# Z = np.genfromtxt(s,delimiter=",", dtype=np.int)
# print(Z)
<_io.StringIO object at 0x0000027129367798>
1, 2, 3, 4, 5
6,  ,  , 7, 8
,  , 9, 10, 11
import io
s = io.StringIO()
s.write('Hello World\n')
print('this is a test\n', file = s)
print(s.getvalue())
Hello World
this is a test
help(StringIO)
Help on class StringIO in module io:

class StringIO(_TextIOBase)
 |  Text I/O implementation using an in-memory buffer.
 |  
 |  The initial_value argument sets the value of object.  The newline
 |  argument is like the one of TextIOWrapper's constructor.
 |  
 |  Method resolution order:
 |      StringIO
 |      _TextIOBase
 |      _IOBase
 |      builtins.object
 |  
 |  Methods defined here:
 |  
 |  __getstate__(...)
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __setstate__(...)
 |  
 |  close(self, /)
 |      Close the IO object.
 |      
 |      Attempting any further operation after the object is closed
 |      will raise a ValueError.
 |      
 |      This method has no effect if the file is already closed.
 |  
 |  getvalue(self, /)
 |      Retrieve the entire contents of the object.
 |  
 |  read(self, size=None, /)
 |      Read at most size characters, returned as a string.
 |      
 |      If the argument is negative or omitted, read until EOF
 |      is reached. Return an empty string at EOF.
 |  
 |  readable(self, /)
 |      Returns True if the IO object can be read.
 |  
 |  readline(self, size=None, /)
 |      Read until newline or EOF.
 |      
 |      Returns an empty string if EOF is hit immediately.
 |  
 |  seek(self, pos, whence=0, /)
 |      Change stream position.
 |      
 |      Seek to character offset pos relative to position indicated by whence:
 |          0  Start of stream (the default).  pos should be >= 0;
 |          1  Current position - pos must be 0;
 |          2  End of stream - pos must be 0.
 |      Returns the new absolute position.
 |  
 |  seekable(self, /)
 |      Returns True if the IO object can be seeked.
 |  
 |  tell(self, /)
 |      Tell the current file position.
 |  
 |  truncate(self, pos=None, /)
 |      Truncate size to pos.
 |      
 |      The pos argument defaults to the current file position, as
 |      returned by tell().  The current file position is unchanged.
 |      Returns the new absolute position.
 |  
 |  writable(self, /)
 |      Returns True if the IO object can be written.
 |  
 |  write(self, s, /)
 |      Write string to file.
 |      
 |      Returns the number of characters written, which is always equal to
 |      the length of the string.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  closed
 |  
 |  line_buffering
 |  
 |  newlines
 |      Line endings translated so far.
 |      
 |      Only line endings translated during reading are considered.
 |      
 |      Subclasses should override.
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from _TextIOBase:
 |  
 |  detach(...)
 |      Separate the underlying buffer from the TextIOBase and return it.
 |      
 |      After the underlying buffer has been detached, the TextIO is in an
 |      unusable state.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from _TextIOBase:
 |  
 |  encoding
 |      Encoding of the text stream.
 |      
 |      Subclasses should override.
 |  
 |  errors
 |      The error setting of the decoder or encoder.
 |      
 |      Subclasses should override.
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from _IOBase:
 |  
 |  __del__(...)
 |  
 |  __enter__(...)
 |  
 |  __exit__(...)
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  fileno(self, /)
 |      Returns underlying file descriptor if one exists.
 |      
 |      OSError is raised if the IO object does not use a file descriptor.
 |  
 |  flush(self, /)
 |      Flush write buffers, if applicable.
 |      
 |      This is not implemented for read-only and non-blocking streams.
 |  
 |  isatty(self, /)
 |      Return whether this is an 'interactive' stream.
 |      
 |      Return False if it can't be determined.
 |  
 |  readlines(self, hint=-1, /)
 |      Return a list of lines from the stream.
 |      
 |      hint can be specified to control the number of lines read: no more
 |      lines will be read if the total size (in bytes/characters) of all
 |      lines so far exceeds hint.
 |  
 |  writelines(self, lines, /)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from _IOBase:
 |  
 |  __dict__

55. What is the equivalent of enumerate for numpy arrays? (★★☆)

a = np.array([[1,2],[3,4]])
print (a)
for index,x in np.ndenumerate(a):
    print (index,x)
[[1 2]
 [3 4]]
(0, 0) 1
(0, 1) 2
(1, 0) 3
(1, 1) 4
a = np.array([[1,2],[3,4]])
print (a)
for index in np.ndindex(a.shape):
    print (index,a[index])
[[1 2]
 [3 4]]
(0, 0) 1
(0, 1) 2
(1, 0) 3
(1, 1) 4
help(np.ndindex)
Help on class ndindex in module numpy.lib.index_tricks:

class ndindex(builtins.object)
 |  An N-dimensional iterator object to index arrays.
 |  
 |  Given the shape of an array, an `ndindex` instance iterates over
 |  the N-dimensional index of the array. At each iteration a tuple
 |  of indices is returned, the last dimension is iterated over first.
 |  
 |  Parameters
 |  ----------
 |  `*args` : ints
 |    The size of each dimension of the array.
 |  
 |  See Also
 |  --------
 |  ndenumerate, flatiter
 |  
 |  Examples
 |  --------
 |  >>> for index in np.ndindex(3, 2, 1):
 |  ...     print(index)
 |  (0, 0, 0)
 |  (0, 1, 0)
 |  (1, 0, 0)
 |  (1, 1, 0)
 |  (2, 0, 0)
 |  (2, 1, 0)
 |  
 |  Methods defined here:
 |  
 |  __init__(self, *shape)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __iter__(self)
 |  
 |  __next__(self)
 |      Standard iterator method, updates the index and returns the index
 |      tuple.
 |      
 |      Returns
 |      -------
 |      val : tuple of ints
 |          Returns a tuple containing the indices of the current
 |          iteration.
 |  
 |  ndincr(self)
 |      Increment the multi-dimensional index by one.
 |      
 |      This method is for backward compatibility only: do not use.
 |  
 |  next = __next__(self)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

56. Generate a generic 2D Gaussian-like array (★★☆)

X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
D = np.sqrt(X*X+Y*Y)
sigma, mu = 1.0, 0.0
G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )
print(G)
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
m, n = (5, 3)
x = np.linspace(0, 1, m)
y = np.linspace(0, 1, n)
X, Y = np.meshgrid(x,y)
print (x)
print (y)
print (X)
print (Y)
plt.plot(X, Y, marker='.', color='blue', linestyle='none')
plt.show()
z = [i for i in zip(X.flat,Y.flat)]
print (z)
[ 0.    0.25  0.5   0.75  1.  ]
[ 0.   0.5  1. ]
[[ 0.    0.25  0.5   0.75  1.  ]
 [ 0.    0.25  0.5   0.75  1.  ]
 [ 0.    0.25  0.5   0.75  1.  ]]
[[ 0.   0.   0.   0.   0. ]
 [ 0.5  0.5  0.5  0.5  0.5]
 [ 1.   1.   1.   1.   1. ]]

png

[(0.0, 0.0), (0.25, 0.0), (0.5, 0.0), (0.75, 0.0), (1.0, 0.0), (0.0, 0.5), (0.25, 0.5), (0.5, 0.5), (0.75, 0.5), (1.0, 0.5), (0.0, 1.0), (0.25, 1.0), (0.5, 1.0), (0.75, 1.0), (1.0, 1.0)]
print (np.linspace(-1,1,10))
[-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
  0.33333333  0.55555556  0.77777778  1.        ]
X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
print(X)
print(Y)
[[-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]
 [-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]
 [-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]
 [-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]
 [-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]
 [-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]
 [-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]
 [-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]
 [-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]
 [-1.         -0.77777778 -0.55555556 -0.33333333 -0.11111111  0.11111111
   0.33333333  0.55555556  0.77777778  1.        ]]
[[-1.         -1.         -1.         -1.         -1.         -1.         -1.
  -1.         -1.         -1.        ]
 [-0.77777778 -0.77777778 -0.77777778 -0.77777778 -0.77777778 -0.77777778
  -0.77777778 -0.77777778 -0.77777778 -0.77777778]
 [-0.55555556 -0.55555556 -0.55555556 -0.55555556 -0.55555556 -0.55555556
  -0.55555556 -0.55555556 -0.55555556 -0.55555556]
 [-0.33333333 -0.33333333 -0.33333333 -0.33333333 -0.33333333 -0.33333333
  -0.33333333 -0.33333333 -0.33333333 -0.33333333]
 [-0.11111111 -0.11111111 -0.11111111 -0.11111111 -0.11111111 -0.11111111
  -0.11111111 -0.11111111 -0.11111111 -0.11111111]
 [ 0.11111111  0.11111111  0.11111111  0.11111111  0.11111111  0.11111111
   0.11111111  0.11111111  0.11111111  0.11111111]
 [ 0.33333333  0.33333333  0.33333333  0.33333333  0.33333333  0.33333333
   0.33333333  0.33333333  0.33333333  0.33333333]
 [ 0.55555556  0.55555556  0.55555556  0.55555556  0.55555556  0.55555556
   0.55555556  0.55555556  0.55555556  0.55555556]
 [ 0.77777778  0.77777778  0.77777778  0.77777778  0.77777778  0.77777778
   0.77777778  0.77777778  0.77777778  0.77777778]
 [ 1.          1.          1.          1.          1.          1.          1.
   1.          1.          1.        ]]

57. How to randomly place p elements in a 2D array? (★★☆)

n =10
p =3
a = np.zeros((n,n))
print (range(n*n))
np.put(a,np.random.choice(range(n*n), p, replace=False),1)
print(a)
range(0, 100)
[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  1.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  1.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  1.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]
n =10
p =3
a = np.zeros((n,n))
np.put(a,np.random.choice(n, p, replace=False),1)
print(a)
[[ 1.  0.  0.  0.  1.  0.  1.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]
help(np.random.choice)
Help on built-in function choice:

choice(...) method of mtrand.RandomState instance
    choice(a, size=None, replace=True, p=None)
    
    Generates a random sample from a given 1-D array
    
            .. versionadded:: 1.7.0
    
    Parameters
    -----------
    a : 1-D array-like or int
        If an ndarray, a random sample is generated from its elements.
        If an int, the random sample is generated as if a was np.arange(n)
    size : int or tuple of ints, optional
        Output shape.  If the given shape is, e.g., ``(m, n, k)``, then
        ``m * n * k`` samples are drawn.  Default is None, in which case a
        single value is returned.
    replace : boolean, optional
        Whether the sample is with or without replacement
    p : 1-D array-like, optional
        The probabilities associated with each entry in a.
        If not given the sample assumes a uniform distribution over all
        entries in a.
    
    Returns
    --------
    samples : 1-D ndarray, shape (size,)
        The generated random samples
    
    Raises
    -------
    ValueError
        If a is an int and less than zero, if a or p are not 1-dimensional,
        if a is an array-like of size 0, if p is not a vector of
        probabilities, if a and p have different lengths, or if
        replace=False and the sample size is greater than the population
        size
    
    See Also
    ---------
    randint, shuffle, permutation
    
    Examples
    ---------
    Generate a uniform random sample from np.arange(5) of size 3:
    
    >>> np.random.choice(5, 3)
    array([0, 3, 4])
    >>> #This is equivalent to np.random.randint(0,5,3)
    
    Generate a non-uniform random sample from np.arange(5) of size 3:
    
    >>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])
    array([3, 3, 0])
    
    Generate a uniform random sample from np.arange(5) of size 3 without
    replacement:
    
    >>> np.random.choice(5, 3, replace=False)
    array([3,1,0])
    >>> #This is equivalent to np.random.permutation(np.arange(5))[:3]
    
    Generate a non-uniform random sample from np.arange(5) of size
    3 without replacement:
    
    >>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])
    array([2, 3, 0])
    
    Any of the above can be repeated with an arbitrary array-like
    instead of just integers. For instance:
    
    >>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']
    >>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
    array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'],
          dtype='|S11')
print (np.random.choice(4, 3))
[1 3 2]
help(np.put)
Help on function put in module numpy.core.fromnumeric:

put(a, ind, v, mode='raise')
    Replaces specified elements of an array with given values.
    
    The indexing works on the flattened target array. `put` is roughly
    equivalent to:
    
    ::
    
        a.flat[ind] = v
    
    Parameters
    ----------
    a : ndarray
        Target array.
    ind : array_like
        Target indices, interpreted as integers.
    v : array_like
        Values to place in `a` at target indices. If `v` is shorter than
        `ind` it will be repeated as necessary.
    mode : {'raise', 'wrap', 'clip'}, optional
        Specifies how out-of-bounds indices will behave.
    
        * 'raise' -- raise an error (default)
        * 'wrap' -- wrap around
        * 'clip' -- clip to the range
    
        'clip' mode means that all indices that are too large are replaced
        by the index that addresses the last element along that axis. Note
        that this disables indexing with negative numbers.
    
    See Also
    --------
    putmask, place
    
    Examples
    --------
    >>> a = np.arange(5)
    >>> np.put(a, [0, 2], [-44, -55])
    >>> a
    array([-44,   1, -55,   3,   4])
    
    >>> a = np.arange(5)
    >>> np.put(a, 22, -5, mode='clip')
    >>> a
    array([ 0,  1,  2,  3, -5])

58. Subtract the mean of each row of a matrix (★★☆)

a = np.random.random((2,10))
print (a)
print (a.mean(axis=1, keepdims=True))
print (a - a.mean(axis=1, keepdims=True))
[[ 0.33574705  0.86742737  0.43875947  0.55345915  0.75932351  0.65919551
   0.13323911  0.94333164  0.90745265  0.86964945]
 [ 0.35962061  0.79331782  0.89986659  0.26816597  0.2548298   0.85259611
   0.77185145  0.08909965  0.98696177  0.89578304]]
[[ 0.64675849]
 [ 0.61720928]]
[[-0.31101144  0.22066888 -0.20799902 -0.09329934  0.11256502  0.01243701
  -0.51351939  0.29657315  0.26069416  0.22289096]
 [-0.25758867  0.17610854  0.28265731 -0.34904331 -0.36237949  0.23538683
   0.15464217 -0.52810963  0.36975249  0.27857376]]

59. How to sort an array by the nth column? (★★☆)

a = np.random.random((1,10))
print (sorted(a))
[array([ 0.07667464,  0.88212456,  0.14078942,  0.98586235,  0.91639138,
        0.74885809,  0.3930249 ,  0.76793524,  0.31083368,  0.29235793])]
a = np.random.randint(0,10,(3,3))
print(a)
print (a[:,1])
print(a[a[:,1].argsort()])#argsort()函数是将x中的元素从小到大排列,提取其对应的index(索引),然后输出到y
[[0 8 4]
 [8 1 0]
 [9 8 9]]
[8 1 8]
[[8 1 0]
 [0 8 4]
 [9 8 9]]

60. How to tell if a given 2D array has null columns? (★★☆)

Z = np.random.randint(0,3,(3,10))
print (Z)
print (Z.any(axis=0))
print((~Z.any(axis=0)).any())
[[2 2 0 0 1 0 1 1 2 1]
 [0 0 1 2 1 0 0 0 2 2]
 [2 1 0 1 1 0 1 0 0 2]]
[ True  True  True  True  True False  True  True  True  True]
True

猜你喜欢

转载自blog.csdn.net/weixin_43763724/article/details/88525491
今日推荐