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.pswp.cn/news/377800.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/377800.shtml
英文地址,請注明出處:http://en.pswp.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"…