Numpy(科学计算库)---小练习

1,打印当前Numpy版本
import numpy as np
print (np.__version__)
"""
1.22.3
"""
2,构造一个全零的矩阵,并打印其占用的内存大小
yy = np.zeros((3,3))
yy
"""
array([[0., 0., 0.],[0., 0., 0.],[0., 0., 0.]])
"""
print('%d bytes'%(yy.size * yy.itemsize))
"""
72 bytes
"""
3,打印一个函数的帮助文档,比如numpy.add
print(help(np.add))
"""
Help on ufunc object:add = class ufunc(builtins.object)|  Functions that operate element by element on whole arrays.|  |  To see the documentation for a specific ufunc, use `info`.  For|  example, ``np.info(np.sin)``.  Because ufuncs are written in C|  (for speed) and linked into Python with NumPy's ufunc facility,|  Python's help() function finds this page whenever help() is called|  on a ufunc.|  |  A detailed explanation of ufuncs can be found in the docs for :ref:`ufuncs`.|  |  **Calling ufuncs:** ``op(*x[, out], where=True, **kwargs)``|  |  Apply `op` to the arguments `*x` elementwise, broadcasting the arguments.|  |  The broadcasting rules are:|  |  * Dimensions of length 1 may be prepended to either array.|  * Arrays may be repeated along dimensions of length 1.|  |  Parameters|  ----------|  *x : array_like|      Input arrays.|  out : ndarray, None, or tuple of ndarray and None, optional|      Alternate array object(s) in which to put the result; if provided, it|      must have a shape that the inputs broadcast to. A tuple of arrays|      (possible only as a keyword argument) must have length equal to the|      number of outputs; use None for uninitialized outputs to be|      allocated by the ufunc.|  where : array_like, optional|      This condition is broadcast over the input. At locations where the|      condition is True, the `out` array will be set to the ufunc result.|      Elsewhere, the `out` array will retain its original value.|      Note that if an uninitialized `out` array is created via the default|      ``out=None``, locations within it where the condition is False will|      remain uninitialized.|  **kwargs|      For other keyword-only arguments, see the :ref:`ufunc docs <ufuncs.kwargs>`.|  |  Returns|  -------|  r : ndarray or tuple of ndarray|      `r` will have the shape that the arrays in `x` broadcast to; if `out` is|      provided, it will be returned. If not, `r` will be allocated and|      may contain uninitialized values. If the function has more than one|      output, then the result will be a tuple of arrays.|  |  Methods defined here:|  |  __call__(self, /, *args, **kwargs)|      Call self as a function.|  |  __repr__(self, /)|      Return repr(self).|  |  __str__(self, /)|      Return str(self).|  |  accumulate(...)|      accumulate(array, axis=0, dtype=None, out=None)|      |      Accumulate the result of applying the operator to all elements.|      |      For a one-dimensional array, accumulate produces results equivalent to::|      |        r = np.empty(len(A))|        t = op.identity        # op = the ufunc being applied to A's  elements|        for i in range(len(A)):|            t = op(t, A[i])|            r[i] = t|        return r|      |      For example, add.accumulate() is equivalent to np.cumsum().|      |      For a multi-dimensional array, accumulate is applied along only one|      axis (axis zero by default; see Examples below) so repeated use is|      necessary if one wants to accumulate over multiple axes.|      |      Parameters|      ----------|      array : array_like|          The array to act on.|      axis : int, optional|          The axis along which to apply the accumulation; default is zero.|      dtype : data-type code, optional|          The data-type used to represent the intermediate results. Defaults|          to the data-type of the output array if such is provided, or the|          the data-type of the input array if no output array is provided.|      out : ndarray, None, or tuple of ndarray and None, optional|          A location into which the result is stored. If not provided or None,|          a freshly-allocated array is returned. For consistency with|          ``ufunc.__call__``, if given as a keyword, this may be wrapped in a|          1-element tuple.|      |          .. versionchanged:: 1.13.0|             Tuples are allowed for keyword argument.|      |      Returns|      -------|      r : ndarray|          The accumulated values. If `out` was supplied, `r` is a reference to|          `out`.|      |      Examples|      --------|      1-D array examples:|      |      >>> np.add.accumulate([2, 3, 5])|      array([ 2,  5, 10])|      >>> np.multiply.accumulate([2, 3, 5])|      array([ 2,  6, 30])|      |      2-D array examples:|      |      >>> I = np.eye(2)|      >>> I|      array([[1.,  0.],|             [0.,  1.]])|      |      Accumulate along axis 0 (rows), down columns:|      |      >>> np.add.accumulate(I, 0)|      array([[1.,  0.],|             [1.,  1.]])|      >>> np.add.accumulate(I) # no axis specified = axis zero|      array([[1.,  0.],|             [1.,  1.]])|      |      Accumulate along axis 1 (columns), through rows:|      |      >>> np.add.accumulate(I, 1)|      array([[1.,  1.],|             [0.,  1.]])|  |  at(...)|      at(a, indices, b=None, /)|      |      Performs unbuffered in place operation on operand 'a' for elements|      specified by 'indices'. For addition ufunc, this method is equivalent to|      ``a[indices] += b``, except that results are accumulated for elements that|      are indexed more than once. For example, ``a[[0,0]] += 1`` will only|      increment the first element once because of buffering, whereas|      ``add.at(a, [0,0], 1)`` will increment the first element twice.|      |      .. versionadded:: 1.8.0|      |      Parameters|      ----------|      a : array_like|          The array to perform in place operation on.|      indices : array_like or tuple|          Array like index object or slice object for indexing into first|          operand. If first operand has multiple dimensions, indices can be a|          tuple of array like index objects or slice objects.|      b : array_like|          Second operand for ufuncs requiring two operands. Operand must be|          broadcastable over first operand after indexing or slicing.|      |      Examples|      --------|      Set items 0 and 1 to their negative values:|      |      >>> a = np.array([1, 2, 3, 4])|      >>> np.negative.at(a, [0, 1])|      >>> a|      array([-1, -2,  3,  4])|      |      Increment items 0 and 1, and increment item 2 twice:|      |      >>> a = np.array([1, 2, 3, 4])|      >>> np.add.at(a, [0, 1, 2, 2], 1)|      >>> a|      array([2, 3, 5, 4])|      |      Add items 0 and 1 in first array to second array,|      and store results in first array:|      |      >>> a = np.array([1, 2, 3, 4])|      >>> b = np.array([1, 2])|      >>> np.add.at(a, [0, 1], b)|      >>> a|      array([2, 4, 3, 4])|  |  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`.|          See `ufunc` for a comprehensive overview of all available arguments.|      |      Returns|      -------|      r : ndarray|          Output array|      |      See Also|      --------|      numpy.outer : A less powerful version of ``np.multiply.outer``|                    that `ravel`\ s all inputs to 1D. This exists|                    primarily for compatibility with old code.|      |      tensordot : ``np.tensordot(a, b, axes=((), ()))`` and|                  ``np.multiply.outer(a, b)`` behave same for all|                  dimensions of a and b.|      |      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]]]])|  |  reduce(...)|      reduce(array, axis=0, dtype=None, out=None, keepdims=False, initial=<no value>, where=True)|      |      Reduces `array`'s dimension by one, by applying ufunc along one axis.|      |      Let :math:`array.shape = (N_0, ..., N_i, ..., N_{M-1})`.  Then|      :math:`ufunc.reduce(array, 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:`array[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|      ----------|      array : 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, None, or tuple of ndarray and None, optional|          A location into which the result is stored. If not provided or None,|          a freshly-allocated array is returned. For consistency with|          ``ufunc.__call__``, if given as a keyword, this may be wrapped in a|          1-element tuple.|      |          .. versionchanged:: 1.13.0|             Tuples are allowed for keyword argument.|      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 `array`.|      |          .. versionadded:: 1.7.0|      initial : scalar, optional|          The value with which to start the reduction.|          If the ufunc has no identity or the dtype is object, this defaults|          to None - otherwise it defaults to ufunc.identity.|          If ``None`` is given, the first element of the reduction is used,|          and an error is thrown if the reduction is empty.|      |          .. versionadded:: 1.15.0|      |      where : array_like of bool, optional|          A boolean array which is broadcasted to match the dimensions|          of `array`, and selects elements to include in the reduction. Note|          that for ufuncs like ``minimum`` that do not have an identity|          defined, one has to pass in also ``initial``.|      |          .. versionadded:: 1.17.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]])|      |      You can use the ``initial`` keyword argument to initialize the reduction|      with a different value, and ``where`` to select specific elements to include:|      |      >>> np.add.reduce([10], initial=5)|      15|      >>> np.add.reduce(np.ones((2, 2, 2)), axis=(0, 2), initial=10)|      array([14., 14.])|      >>> a = np.array([10., np.nan, 10])|      >>> np.add.reduce(a, where=~np.isnan(a))|      20.0|      |      Allows reductions of empty arrays where they would normally fail, i.e.|      for ufuncs without an identity.|      |      >>> np.minimum.reduce([], initial=np.inf)|      inf|      >>> np.minimum.reduce([[1., 2.], [3., 4.]], initial=10., where=[True, False])|      array([ 1., 10.])|      >>> np.minimum.reduce([])|      Traceback (most recent call last):|          ...|      ValueError: zero-size array to reduction operation minimum which has no identity|  |  reduceat(...)|      reduceat(array, indices, axis=0, dtype=None, out=None)|      |      Performs a (local) reduce with specified slices over a single axis.|      |      For i in ``range(len(indices))``, `reduceat` computes|      ``ufunc.reduce(array[indices[i]:indices[i+1]])``, which becomes the i-th|      generalized "row" parallel to `axis` in the final result (i.e., in a|      2-D array, for example, if `axis = 0`, it becomes the i-th row, but if|      `axis = 1`, it becomes the i-th column).  There are three exceptions to this:|      |      * when ``i = len(indices) - 1`` (so for the last index),|        ``indices[i+1] = array.shape[axis]``.|      * if ``indices[i] >= indices[i + 1]``, the i-th generalized "row" is|        simply ``array[indices[i]]``.|      * if ``indices[i] >= len(array)`` or ``indices[i] < 0``, an error is raised.|      |      The shape of the output depends on the size of `indices`, and may be|      larger than `array` (this happens if ``len(indices) > array.shape[axis]``).|      |      Parameters|      ----------|      array : array_like|          The array to act on.|      indices : array_like|          Paired indices, comma separated (not colon), specifying slices to|          reduce.|      axis : int, optional|          The axis along which to apply the reduceat.|      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, None, or tuple of ndarray and None, optional|          A location into which the result is stored. If not provided or None,|          a freshly-allocated array is returned. For consistency with|          ``ufunc.__call__``, if given as a keyword, this may be wrapped in a|          1-element tuple.|      |          .. versionchanged:: 1.13.0|             Tuples are allowed for keyword argument.|      |      Returns|      -------|      r : ndarray|          The reduced values. If `out` was supplied, `r` is a reference to|          `out`.|      |      Notes|      -----|      A descriptive example:|      |      If `array` is 1-D, the function `ufunc.accumulate(array)` is the same as|      ``ufunc.reduceat(array, indices)[::2]`` where `indices` is|      ``range(len(array) - 1)`` with a zero placed|      in every other element:|      ``indices = zeros(2 * len(array) - 1)``,|      ``indices[1::2] = range(1, len(array))``.|      |      Don't be fooled by this attribute's name: `reduceat(array)` is not|      necessarily smaller than `array`.|      |      Examples|      --------|      To take the running sum of four successive values:|      |      >>> np.add.reduceat(np.arange(8),[0,4, 1,5, 2,6, 3,7])[::2]|      array([ 6, 10, 14, 18])|      |      A 2-D example:|      |      >>> x = np.linspace(0, 15, 16).reshape(4,4)|      >>> x|      array([[ 0.,   1.,   2.,   3.],|             [ 4.,   5.,   6.,   7.],|             [ 8.,   9.,  10.,  11.],|             [12.,  13.,  14.,  15.]])|      |      ::|      |       # reduce such that the result has the following five rows:|       # [row1 + row2 + row3]|       # [row4]|       # [row2]|       # [row3]|       # [row1 + row2 + row3 + row4]|      |      >>> np.add.reduceat(x, [0, 3, 1, 2, 0])|      array([[12.,  15.,  18.,  21.],|             [12.,  13.,  14.,  15.],|             [ 4.,   5.,   6.,   7.],|             [ 8.,   9.,  10.,  11.],|             [24.,  28.,  32.,  36.]])|      |      ::|      |       # reduce such that result has the following two columns:|       # [col1 * col2 * col3, col4]|      |      >>> np.multiply.reduceat(x, [0, 3], 1)|      array([[   0.,     3.],|             [ 120.,     7.],|             [ 720.,    11.],|             [2184.,    15.]])|  |  ----------------------------------------------------------------------|  Data descriptors defined here:|  |  identity|      The identity value.|      |      Data attribute containing the identity element for the ufunc, if it has one.|      If it does not, the attribute value is None.|      |      Examples|      --------|      >>> np.add.identity|      0|      >>> np.multiply.identity|      1|      >>> np.power.identity|      1|      >>> print(np.exp.identity)|      None|  |  nargs|      The number of arguments.|      |      Data attribute containing the number of arguments the ufunc takes, including|      optional ones.|      |      Notes|      -----|      Typically this value will be one more than what you might expect because all|      ufuncs take  the optional "out" argument.|      |      Examples|      --------|      >>> np.add.nargs|      3|      >>> np.multiply.nargs|      3|      >>> np.power.nargs|      3|      >>> np.exp.nargs|      2|  |  nin|      The number of inputs.|      |      Data attribute containing the number of arguments the ufunc treats as input.|      |      Examples|      --------|      >>> np.add.nin|      2|      >>> np.multiply.nin|      2|      >>> np.power.nin|      2|      >>> np.exp.nin|      1|  |  nout|      The number of outputs.|      |      Data attribute containing the number of arguments the ufunc treats as output.|      |      Notes|      -----|      Since all ufuncs can take output arguments, this will always be (at least) 1.|      |      Examples|      --------|      >>> np.add.nout|      1|      >>> np.multiply.nout|      1|      >>> np.power.nout|      1|      >>> np.exp.nout|      1|  |  ntypes|      The number of types.|      |      The number of numerical NumPy types - of which there are 18 total - on which|      the ufunc can operate.|      |      See Also|      --------|      numpy.ufunc.types|      |      Examples|      --------|      >>> np.add.ntypes|      18|      >>> np.multiply.ntypes|      18|      >>> np.power.ntypes|      17|      >>> np.exp.ntypes|      7|      >>> np.remainder.ntypes|      14|  |  signature|      Definition of the core elements a generalized ufunc operates on.|      |      The signature determines how the dimensions of each input/output array|      are split into core and loop dimensions:|      |      1. Each dimension in the signature is matched to a dimension of the|         corresponding passed-in array, starting from the end of the shape tuple.|      2. Core dimensions assigned to the same label in the signature must have|         exactly matching sizes, no broadcasting is performed.|      3. The core dimensions are removed from all inputs and the remaining|         dimensions are broadcast together, defining the loop dimensions.|      |      Notes|      -----|      Generalized ufuncs are used internally in many linalg functions, and in|      the testing suite; the examples below are taken from these.|      For ufuncs that operate on scalars, the signature is None, which is|      equivalent to '()' for every argument.|      |      Examples|      --------|      >>> np.core.umath_tests.matrix_multiply.signature|      '(m,n),(n,p)->(m,p)'|      >>> np.linalg._umath_linalg.det.signature|      '(m,m)->()'|      >>> np.add.signature is None|      True  # equivalent to '(),()->()'|  |  types|      Returns a list with types grouped input->output.|      |      Data attribute listing the data-type "Domain-Range" groupings the ufunc can|      deliver. The data-types are given using the character codes.|      |      See Also|      --------|      numpy.ufunc.ntypes|      |      Examples|      --------|      >>> np.add.types|      ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l',|      'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D',|      'GG->G', 'OO->O']|      |      >>> np.multiply.types|      ['??->?', 'bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l',|      'LL->L', 'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D',|      'GG->G', 'OO->O']|      |      >>> np.power.types|      ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L',|      'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'FF->F', 'DD->D', 'GG->G',|      'OO->O']|      |      >>> np.exp.types|      ['f->f', 'd->d', 'g->g', 'F->F', 'D->D', 'G->G', 'O->O']|      |      >>> np.remainder.types|      ['bb->b', 'BB->B', 'hh->h', 'HH->H', 'ii->i', 'II->I', 'll->l', 'LL->L',|      'qq->q', 'QQ->Q', 'ff->f', 'dd->d', 'gg->g', 'OO->O']None
"""
4,创建一个10-49的数组,并将其倒序排列
yy = np.arange(10,50,1)
yy
"""
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,44, 45, 46, 47, 48, 49])
"""
yy_trans = yy[::-1]
yy_trans
"""
array([49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33,32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16,15, 14, 13, 12, 11, 10])
"""
5,找到一个数组中不为0的索引
np.nonzero([5,22,10,14,0,2,0,45])
"""
(array([0, 1, 2, 3, 5, 7], dtype=int64),)
"""
6,随机构造一个3*3矩阵,并打印其中最大与最小值
yy = np.random.random((3,3))
yy
"""
array([[0.20370941, 0.43612091, 0.70595564],[0.24069372, 0.273715  , 0.25698803],[0.19907169, 0.21970853, 0.54037143]])
"""
yy.min()
"""
0.19907168900348726
"""
yy.max()
"""
0.7059556367657052
"""
7,构造一个5*5的矩阵,令其值都为1,并在最外层加上一圈0
yy = np.ones((5,5))
yy
"""
array([[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.]])
"""
yy_zero = np.pad(yy,pad_width=1,mode='constant',constant_values=0)
yy_zero
"""
array([[0., 0., 0., 0., 0., 0., 0.],[0., 1., 1., 1., 1., 1., 0.],[0., 1., 1., 1., 1., 1., 0.],[0., 1., 1., 1., 1., 1., 0.],[0., 1., 1., 1., 1., 1., 0.],[0., 1., 1., 1., 1., 1., 0.],[0., 0., 0., 0., 0., 0., 0.]])
"""
8,构建一个shape为(6,7,8)的矩阵,并找到第100个元素的索引值
np.unravel_index(100,(6,7,8))
"""
(1, 5, 4)
"""
9,对一个5*5的矩阵做归一化操作
yy = np.random.random((5,5))
yy
"""
array([[0.94940168, 0.65730346, 0.96278534, 0.75923461, 0.84884701],[0.76622936, 0.36055562, 0.92852778, 0.07413462, 0.49142217],[0.82448018, 0.8047853 , 0.83052986, 0.05108754, 0.9630701 ],[0.04363141, 0.78501252, 0.93953562, 0.47592529, 0.40644514],[0.30959323, 0.16236801, 0.71394387, 0.27592273, 0.99898129]])
"""
yy_max = yy.max()
yy_max
"""
0.9989812852483628
"""
yy_min = yy.min()
yy_min
"""
0.0436314121510083
"""
yy_arr = (yy-yy_min)/(yy_max-yy_min)
yy_arr
"""
array([[0.94810319, 0.6423532 , 0.96211237, 0.7490483 , 0.84284891],[0.75636996, 0.33173627, 0.92625371, 0.03192884, 0.46871912],[0.81734325, 0.79672789, 0.82367567, 0.00780461, 0.96241044],[0.        , 0.77603099, 0.93777603, 0.45249797, 0.37977053],[0.27839205, 0.12428598, 0.70164081, 0.2431479 , 1.        ]])
"""
10,找到两个数组中相同的值
y1 = np.random.randint(0,10,5)
y1
"""
array([0, 6, 0, 6, 1])
"""
y2 = np.random.randint(0,10,5)
y2
"""
array([9, 6, 9, 1, 7])
"""
y_same = np.intersect1d(y1,y2)
print(y_same)
"""
[1 6]
"""
11,得到今天 明天 昨天的日期
yesterday = np.datetime64('today','D') - np.timedelta64(1,'D')
today = np.datetime64('today','D')
tommorow = np.datetime64('today','D') + np.timedelta64(1,'D')
today
"""
numpy.datetime64('2022-05-01')
"""
tommorow
"""
numpy.datetime64('2022-05-02')
"""
yesterday
"""
numpy.datetime64('2022-04-30')
"""
12,得到一个月中所有的天
np.arange('2022-04','2022-05',dtype='datetime64[D]')
"""
array(['2022-04-01', '2022-04-02', '2022-04-03', '2022-04-04','2022-04-05', '2022-04-06', '2022-04-07', '2022-04-08','2022-04-09', '2022-04-10', '2022-04-11', '2022-04-12','2022-04-13', '2022-04-14', '2022-04-15', '2022-04-16','2022-04-17', '2022-04-18', '2022-04-19', '2022-04-20','2022-04-21', '2022-04-22', '2022-04-23', '2022-04-24','2022-04-25', '2022-04-26', '2022-04-27', '2022-04-28','2022-04-29', '2022-04-30'], dtype='datetime64[D]')
"""
13,得到一个数的整数部分
yy = np.random.uniform(0,10,5)
yy
"""
array([2.90503468, 3.99604344, 3.58371427, 7.85081037, 9.31731275])
"""
np.floor(yy)
"""
array([2., 3., 3., 7., 9.])
"""
14,构造一个数组,让它不能被改变
yy = np.zeros(3)
yy
"""
array([0., 0., 0.])
"""
yy.flags.writeable = False
yy[0] = 1
"""
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-43-a3f5f7b6aa0f> in <module>
----> 1 yy[0] = 1ValueError: assignment destination is read-only
"""
15,打印大数据的部分值,全部值
np.set_printoptions(threshold=5)
yy = np.zeros((15,15))
yy
"""
array([[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.]])
"""
16,找到在一个数组中,最接近一个数的索引
yy = np.arange(100)
yy
"""
array([ 0,  1,  2, ..., 97, 98, 99])
"""
sq = np.random.uniform(0,100)
sq
"""
89.87060277876606
"""
index = (np.abs(yy-sq)).argmin()
print(yy[index])
"""
90
"""
17,32位float类型和32位int类型转换
yy = np.arange(10,dtype=np.int32)
print(yy.dtype)
"""
int32
"""
yy = yy.astype(np.float32)
print(yy.dtype)
"""
float32
"""
18,打印数组元素位置坐标与数值
yy = np.arange(9).reshape(3,3)
yy
"""
array([[0, 1, 2],[3, 4, 5],[6, 7, 8]])
"""
for index,value in np.ndenumerate(yy):print(index,value)
"""
(0, 0) 0
(0, 1) 1
(0, 2) 2
(1, 0) 3
(1, 1) 4
(1, 2) 5
(2, 0) 6
(2, 1) 7
(2, 2) 8
"""
19,按照数组的某一列进行排序
yy = np.random.randint(0,10,(3,3))
yy
"""
array([[1, 6, 3],[4, 9, 2],[3, 3, 8]])
"""
yy_column = yy[yy[:,1].argsort()]
yy_column
"""
array([[3, 3, 8],[1, 6, 3],[4, 9, 2]])
"""
20,统计数组中每个数值出现的次数
yy = np.array([1,3,4,2,4,1,3,5,2,3,4,5])
np.bincount(yy)
"""
array([0, 2, 2, 3, 3, 2], dtype=int64)
"""
21,对一个四维数组的最后两维来求和
yy = np.random.randint(0,10,(4,4,4,4))
yy
"""
array([[[[8, 4, 6, 3],[2, 7, 6, 8],[6, 4, 4, 4],[2, 8, 1, 0]],[[2, 8, 8, 7],[9, 1, 3, 2],[0, 5, 3, 1],[2, 9, 4, 9]],[[5, 6, 0, 7],[1, 8, 4, 9],[2, 8, 3, 1],[3, 5, 0, 2]],[[9, 0, 1, 4],[4, 7, 7, 2],[7, 6, 3, 1],[5, 5, 3, 3]]],[[[3, 8, 5, 8],[5, 2, 1, 2],[7, 8, 0, 5],[0, 9, 4, 7]],[[8, 0, 6, 8],[7, 3, 4, 5],[7, 1, 5, 0],[8, 8, 5, 6]],[[0, 7, 5, 4],[4, 3, 4, 7],[7, 4, 7, 3],[8, 5, 8, 6]],[[7, 1, 5, 9],[5, 1, 3, 4],[5, 3, 1, 9],[3, 6, 3, 7]]],[[[6, 6, 8, 3],[5, 6, 1, 0],[7, 8, 5, 4],[7, 2, 8, 5]],[[1, 4, 7, 8],[9, 8, 2, 5],[2, 7, 3, 7],[7, 6, 0, 4]],[[2, 7, 6, 9],[4, 6, 0, 3],[0, 3, 2, 8],[4, 8, 4, 5]],[[1, 2, 7, 6],[4, 0, 5, 3],[5, 6, 0, 0],[2, 8, 3, 3]]],[[[7, 1, 8, 4],[7, 7, 1, 1],[1, 1, 6, 9],[0, 0, 8, 0]],[[1, 9, 8, 2],[5, 0, 5, 0],[1, 3, 8, 1],[6, 2, 2, 4]],[[0, 7, 2, 5],[1, 8, 5, 3],[4, 7, 5, 1],[0, 8, 4, 4]],[[3, 1, 0, 6],[3, 2, 3, 2],[5, 4, 8, 7],[8, 1, 7, 2]]]])
"""
sq = yy.sum(axis=(-2,-1))
sq
"""
array([[73, 73, 64, 67],[74, 81, 82, 72],[81, 80, 71, 55],[61, 57, 64, 62]])
"""
22,交换矩阵中的两行
yy = np.arange(30).reshape(5,6)
yy
"""
array([[ 0,  1,  2,  3,  4,  5],[ 6,  7,  8,  9, 10, 11],[12, 13, 14, 15, 16, 17],[18, 19, 20, 21, 22, 23],[24, 25, 26, 27, 28, 29]])
"""
yy[[0,1]] = yy[[1,0]]
yy
"""
array([[ 6,  7,  8,  9, 10, 11],[ 0,  1,  2,  3,  4,  5],[12, 13, 14, 15, 16, 17],[18, 19, 20, 21, 22, 23],[24, 25, 26, 27, 28, 29]])
"""
23,找到一个数组中最常出现的数字
yy = np.random.randint(0,20,5)
print(yy)
"""
[18 14 16  8 18]
"""
yy_often = np.bincount(yy).argmax()
yy_often
"""
18
"""
24,快速查找TOP K
yy = np.arange(10000)
yy
"""
array([   0,    1,    2, ..., 9997, 9998, 9999])
"""
np.random.shuffle(yy)
yy
"""
array([9434, 5915, 7866, ..., 7133, 5724, 2156])
"""
n = 5
yy_top = yy[np.argpartition(-yy,n)[:n]]
yy_top
"""
array([9999, 9997, 9998, 9996, 9995])
"""
25,去除掉一个数组中,所有元素都相同的数据
a = np.array([1,2,3,4])
b = np.array([1,2,3,5])
np.all(a == b)
"""
False
"""
np.any(a == b)
"""
True
"""

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/377800.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【转】Spark源码分析之-scheduler模块

原文地址&#xff1a;http://jerryshao.me/architecture/2013/04/21/Spark%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%E4%B9%8B-scheduler%E6%A8%A1%E5%9D%97/ Background Spark在资源管理和调度方式上采用了类似于Hadoop YARN的方式&#xff0c;最上层是资源调度器&#xff0c;它负…

【C++grammar】析构、友元、拷贝构造函数、深浅拷贝

目录1、Destructor&#xff08;析构函数&#xff09;在堆和栈(函数作用域与内嵌作用域)上分别创建Employee对象&#xff0c;观察析构函数的行为2、Friend&#xff08;友元&#xff09;1、为何需要友元2、友元函数和友元类3、关于友元的一些问题3、Copy Constructor&#xff08;…

用mstsc /console 强行“踢”掉其它在线的用户

由于公司有很多windows服务器&#xff0c;而且有很大一部分不在国内&#xff0c;所以经常需要使用远程桌面进行连接&#xff0c;这其中&#xff0c;就会经常遇到因为超出了最大连接数&#xff0c;而不能连接的事情&#xff0c;其中最头痛的就是&#xff0c;在连接国外的服务器时…

set vector_Java Vector set()方法与示例

set vector向量类set()方法 (Vector Class set() method) set() method is available in java.util package. set()方法在java.util包中可用。 set() method is used to replace the old element with the given element (ele) when it exists otherwise it sets the given ele…

Android PreferenceActivity 使用

我想大家对于android的系统配置界面应该不会陌生吧&#xff0c;即便陌生&#xff0c;那么下面的界面应该似曾相识吧&#xff0c;假若还是不认识&#xff0c;那么也没有关系&#xff0c;我们这一节主要就是介绍并讲解android 中系统配置界面的使用&#xff0c;相信大家看完本节后…

Pandas(数据分析处理库)---讲解

本内容来自《跟着迪哥学Python数据分析与机器学习实战》&#xff0c;该篇博客将其内容进行了整理&#xff0c;加上了自己的理解&#xff0c;所做小笔记。若有侵权&#xff0c;联系立删。 迪哥说以下的许多函数方法都不用死记硬背&#xff0c;多查API多看文档&#xff0c;确实&a…

hdu 1141

地址&#xff1a;http://acm.hdu.edu.cn/showproblem.php?pid1141 题意&#xff1a;atmel公司1960年发布4bits的处理器&#xff0c;每10年翻一番。给一个年份&#xff0c;问最近一次发布的处理器能运算的n!最大的n是多少。 mark&#xff1a;最大的处理器位数是2160年的4194304…

leetcode 78. 子集 思考分析

题目 给定一组不含重复元素的整数数组 nums&#xff0c;返回该数组所有可能的子集&#xff08;幂集&#xff09;。 说明&#xff1a;解集不能包含重复的子集。 思考分析 画出解空间树。 我们可以发现我们所需要的结果是解空间的所有结点。而我们之前组合问题和分割问题都是…

PHP checkdate()函数与示例

PHP checkdate()函数 (PHP checkdate() function) checkdate() function is used to check the valid Gregorian dates. It accepts the date and returns Boolean values (True/False) based on the date values. checkdate()函数用于检查有效的公历日期。 它接受日期&#xf…

设计模式读书笔记-----备忘录模式

个人比较喜欢玩单机游戏&#xff0c;什么仙剑、古剑、鬼泣、使命召唤、三国无双等等一系列的游戏我都玩过(现在期待凡人修仙传)&#xff0c;对于这些游戏除了剧情好、场面大、爽快之外&#xff0c;还可以随时存档&#xff0c;等到下次想玩了又可以从刚开始的位置玩起(貌似现在的…

【C++grammar】vector类和字符串字面量

C的vector类 用数组存放数据时&#xff0c;容量大小不可变&#xff0c;vector对象容量可自动增大。 vector的操作&#xff1a; 调用push_back函数时&#xff0c;vector对象的容量可能会增大。 观察下列操作对vector的影响&#xff1a; #include <vector> #include <…

除去数组中的空字符元素array_filter

<?php$str1_arrayarray(电影,,http://www,,1654,);$str1_arrayarray_filter($str1_array);print_r($str1_array); ?>显示结果&#xff1a;Array( [0] > 电影 [2] > http://www [4] > 1654) 转载于:https://www.cnblogs.com/skillCoding/archive/20…

date.after方法_Java Date after()方法与示例

date.after方法日期类after()方法 (Date Class after() method) after() method is available in java.util package. after()方法在java.util包中可用。 after() method is used to check whether this date is after the given date (d) or not. after()方法用于检查此日期是…

Matplotlib(数据可视化库)---讲解

本内容来自《跟着迪哥学Python数据分析与机器学习实战》&#xff0c;该篇博客将其内容进行了整理&#xff0c;加上了自己的理解&#xff0c;所做小笔记。若有侵权&#xff0c;联系立删。 迪哥说以下的许多函数方法都不用死记硬背&#xff0c;多查API多看文档&#xff0c;确实&a…

找min和max

看到的貌似是阿里的笔试题&#xff0c;题意是一组数&#xff0c;要找到min和max&#xff0c;同时要求时间复杂度&#xff08;比较次数&#xff09;小于2n&#xff08;2n的办法都想得到&#xff09;。 别人的思路&#xff1a;n个数的数组里看作每两个一组&#xff0c;若n是奇数&…

Shader Compiler 界面进展1

先从模仿Composer的界面开始. 目前的进展:不用不知道,虽然wxweidgets有很多界面工具如DialogBlocks(DB), 但仍然不好使. 我使用wxAui界面, DialogBlocks并不支持输出其xrc格式, 我猜是wx本身就没有解析wxAui的xrc格式.像wxAuiToolBar或其他wxToolBar, DB工具也不能独立输出xrc.…

leetcode 90. 子集 II 思考分析

与本题相关联的题目解析&#xff1a; leetcode 78. 子集 思考分析 leetcode 40. 组合总和 II思考分析 题目 给定一个可能包含重复元素的整数数组 nums&#xff0c;返回该数组所有可能的子集&#xff08;幂集&#xff09;。 说明&#xff1a;解集不能包含重复的子集。 思考 …

java bitset_Java BitSet and()方法与示例

java bitsetBitSet类和()方法 (BitSet Class and() method) and() method is available in java.util package. and()方法在java.util包中可用。 and() method is used to perform logical AND between two Bitset. This bit set is updated so that every bit holds the value…

Redis-主从复制

一、Redis的Replication&#xff1a; 这里首先需要说明的是&#xff0c;在Redis中配置Master-Slave模式真是太简单了。相信在阅读完这篇Blog之后你也可以轻松做到。这里我们还是先列出一些理论性的知识&#xff0c;后面给出实际操作的案例。 下面的列表清楚的解释了Redis…

.wav音乐文件转换为.fft.npy频谱格式文件

需要修改的地方 十个文件夹&#xff0c;每个文件夹下都有100首.au格式的音乐&#xff0c;这里举个例子&#xff0c;那其中5个类别进行转换 genre_list ["classical", "jazz", "country", "pop", "rock", "metal"…