国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Python Numpy入門基礎(chǔ)(一)創(chuàng)建數(shù)組

這篇具有很好參考價值的文章主要介紹了Python Numpy入門基礎(chǔ)(一)創(chuàng)建數(shù)組。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報違法"按鈕提交疑問。

Python Numpy入門基礎(chǔ)(一)創(chuàng)建數(shù)組,Python,python,numpy,開發(fā)語言

入門基礎(chǔ)(一)

創(chuàng)建數(shù)組

1- np.array()

參數(shù)眾多,初學(xué)時只要關(guān)注基本用法。

array(...)
    array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0,
          like=None)
    
    Create an array.
    
    Parameters
    ----------
    object : array_like
        An array, any object exposing the array interface, an object whose
        __array__ method returns an array, or any (nested) sequence.
    dtype : data-type, optional
        The desired data-type for the array.  If not given, then the type will
        be determined as the minimum type required to hold the objects in the
        sequence.
    copy : bool, optional
        If true (default), then the object is copied.  Otherwise, a copy will
        only be made if __array__ returns a copy, if obj is a nested sequence,
        or if a copy is needed to satisfy any of the other requirements
        (`dtype`, `order`, etc.).
    order : {'K', 'A', 'C', 'F'}, optional
        Specify the memory layout of the array. If object is not an array, the
        newly created array will be in C order (row major) unless 'F' is
        specified, in which case it will be in Fortran order (column major).
        If object is an array the following holds.
    
        ===== ========= ===================================================
        order  no copy                     copy=True
        ===== ========= ===================================================
        'K'   unchanged F & C order preserved, otherwise most similar order
        'A'   unchanged F order if input is F and not C, otherwise C order
        'C'   C order   C order
        'F'   F order   F order
        ===== ========= ===================================================
    
        When ``copy=False`` and a copy is made for other reasons, the result is
        the same as if ``copy=True``, with some exceptions for 'A', see the
        Notes section. The default order is 'K'.
    subok : bool, optional
        If True, then sub-classes will be passed-through, otherwise
        the returned array will be forced to be a base-class array (default).
    ndmin : int, optional
        Specifies the minimum number of dimensions that the resulting
        array should have.  Ones will be pre-pended to the shape as
        needed to meet this requirement.
    like : array_like
        Reference object to allow the creation of arrays which are not
        NumPy arrays. If an array-like passed in as ``like`` supports
        the ``__array_function__`` protocol, the result will be defined
        by it. In this case, it ensures the creation of an array object
        compatible with that passed in via this argument.
    
        .. versionadded:: 1.20.0

元組、列表轉(zhuǎn)換

>>> import numpy as np
>>> np.array((1,2,3))
array([1, 2, 3])
>>> np.array([3,2,3])
array([3, 2, 3])
>>> np.array([[3,2,3],[4,5,6]])
array([[3, 2, 3],
       [4, 5, 6]])

內(nèi)置函數(shù) range()

>>> import numpy as np
>>> np.array(range(5))
array([0, 1, 2, 3, 4])
>>> np.array(range(2,11,2))
array([ 2,  4,  6,  8, 10])
>>> np.array([range(1,5),range(5,9)])
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])

數(shù)組副本copy,開辟一塊新內(nèi)存復(fù)制原數(shù)組

>>> import numpy as np
>>> a = np.array([1,2,3])
>>> b = np.array(a)
>>> b
array([1, 2, 3])
>>> a[0] = 3
>>> a,b
(array([3, 2, 3]), array([1, 2, 3]))

主要參數(shù):
dtype=? ? ?數(shù)組元素的數(shù)據(jù)類型,可選
copy=? ? ? 對象是否需要復(fù)制,可選
order=? ? ?創(chuàng)建數(shù)組的樣式,C為行方向,F(xiàn)為列方向,A為任意方向(默認(rèn))
subok=? ? 默認(rèn)返回一個與基類類型一致的數(shù)組
ndmin=? ? 指定生成數(shù)組的最小維度

>>> import numpy as np
>>> np.array([[1, 2, 3, 4]], dtype=float)
array([[1., 2., 3., 4.]])
>>> np.array([[1, 2], [3, 4]], dtype=complex)
array([[1.+0.j, 2.+0.j],
       [3.+0.j, 4.+0.j]])
>>> np.array([[1, 2, 3, 4]], dtype=np.int64)
array([[1, 2, 3, 4]], dtype=int64)
>>> np.array({1, 2, 3, 4})
array({1, 2, 3, 4}, dtype=object)
>>> np.array({1, 2, 3, 4}).dtype
dtype('O') #集合只能作一個整體,大寫字母O,即object
>>> np.array([[1, 2, 3, 4]], dtype=np.int64).dtype
dtype('int64')
>>> np.array([[1, 2], [3, 4, 5]])
array([list([1, 2]), list([3, 4, 5])], dtype=object)
>>> np.array([[1, 2], [3, 4, 5]]).dtype
dtype('O')
>>> 

>>> np.array([1, 2, 3, 4, 5], ndmin =  1)
array([1, 2, 3, 4, 5])
>>> np.array([1, 2, 3, 4, 5], ndmin =  2)
array([[1, 2, 3, 4, 5]])
>>> np.array([1, 2, 3, 4, 5], ndmin =  3)
array([[[1, 2, 3, 4, 5]]])
>>>

2.1- 基本屬性 .shape? .ndim .dtype .size等

>>> a = np.array(range(2,11,2))
>>> b = np.array([range(1,5),range(5,9)])
>>> a.shape
(5,)
>>> b.shape
(2, 4)
>>> a.ndim, b.ndim
(1, 2)
>>> np.array(1)
array(1)
>>> np.array(1).ndim
0 #常數(shù)為0維
>>> a.dtype.name, b.dtype.name
('int32', 'int32')
>>> a.size, b.size
(5, 8)
>>> type(a), type(b)
(<class 'numpy.ndarray'>, <class 'numpy.ndarray'>)
>>> a
array([ 2,  4,  6,  8, 10])
>>> b
array([[1, 2, 3, 4],
       [5, 6, 7, 8]])
>>> print(a)
[ 2  4  6  8 10]
>>> print(b)
[[1 2 3 4]
 [5 6 7 8]]

.ndim? ? ? 秩,即軸的數(shù)量或維度的數(shù)量
.shape?? ?數(shù)組的維度,對于矩陣,n 行 m 列
.size? ? ? ?數(shù)組元素的總個數(shù),相當(dāng)于 .shape 中 n*m 的值
.dtype?? ? 對象的元素類型
.itemsize?? ? 對象中每個元素的大小,以字節(jié)為單位
.flags? ? ? 對象的內(nèi)存信息
.real? ? ? ?元素的實(shí)部
.imag?? ? 元素的虛部
.data? ? ? 包含實(shí)際數(shù)組元素的緩沖區(qū),由于一般通過數(shù)組的索引獲取元素,所以通常不需要使用這個屬性。?

2.2- 與屬性同名的方法

除.itemsize .flags .data外者有同名方法,其它有方法的參數(shù)都為ndarray,dtype()除外。

>>> a = np.array([*range(5)],dtype=complex)
>>> np.ndim(a)
1
>>> np.shape(a)
(5,)
>>> np.size(a)
5
>>> np.real(a)
array([0., 1., 2., 3., 4.])
>>> np.imag(a)
array([0., 0., 0., 0., 0.])
>>> np.dtype(int)
dtype('int32')
>>> np.dtype(complex)
dtype('complex128')
>>> np.dtype(float)
dtype('float64')
>>> a.itemsize
16
>>> a.flags
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  WRITEBACKIFCOPY : False
  UPDATEIFCOPY : False

>>> a.data
<memory at 0x0000000002D79DC0>

3- np.arange()

arange(...)
    arange([start,] stop[, step,], dtype=None, *, like=None)
    
    Return evenly spaced values within a given interval.
    
    Values are generated within the half-open interval ``[start, stop)``
    (in other words, the interval including `start` but excluding `stop`).
    For integer arguments the function is equivalent to the Python built-in
    `range` function, but returns an ndarray rather than a list.
    
    When using a non-integer step, such as 0.1, the results will often not
    be consistent.  It is better to use `numpy.linspace` for these cases.
    
    Parameters
    ----------
    start : integer or real, optional
        Start of interval.  The interval includes this value.  The default
        start value is 0.
    stop : integer or real
        End of interval.  The interval does not include this value, except
        in some cases where `step` is not an integer and floating point
        round-off affects the length of `out`.
    step : integer or real, optional
        Spacing between values.  For any output `out`, this is the distance
        between two adjacent values, ``out[i+1] - out[i]``.  The default
        step size is 1.  If `step` is specified as a position argument,
        `start` must also be given.
    dtype : dtype
        The type of the output array.  If `dtype` is not given, infer the data
        type from the other input arguments.
    like : array_like
        Reference object to allow the creation of arrays which are not
        NumPy arrays. If an array-like passed in as ``like`` supports
        the ``__array_function__`` protocol, the result will be defined
        by it. In this case, it ensures the creation of an array object
        compatible with that passed in via this argument.
    
        .. versionadded:: 1.20.0

np.arange() 與 np.array(range()) 類似,但前者允許用浮點(diǎn)數(shù)

>>> np.arange(12)
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
>>> np.arange(0,1.1,0.1)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
>>> np.arange(2,5,0.3)
array([2. , 2.3, 2.6, 2.9, 3.2, 3.5, 3.8, 4.1, 4.4, 4.7])

4- np.reshape()

reshape(a, newshape, order='C')
    Gives a new shape to an array without changing its data.
    
    Parameters
    ----------
    a : array_like
        Array to be reshaped.
    newshape : int or tuple of ints
        The new shape should be compatible with the original shape. If
        an integer, then the result will be a 1-D array of that length.
        One shape dimension can be -1. In this case, the value is
        inferred from the length of the array and remaining dimensions.
    order : {'C', 'F', 'A'}, optional
        Read the elements of `a` using this index order, and place the
        elements into the reshaped array using this index order.  'C'
        means to read / write the elements using C-like index order,
        with the last axis index changing fastest, back to the first
        axis index changing slowest. 'F' means to read / write the
        elements using Fortran-like index order, with the first index
        changing fastest, and the last index changing slowest. Note that
        the 'C' and 'F' options take no account of the memory layout of
        the underlying array, and only refer to the order of indexing.
        'A' means to read / write the elements in Fortran-like index
        order if `a` is Fortran *contiguous* in memory, C-like order
        otherwise.
    
    Returns
    -------
    reshaped_array : ndarray
        This will be a new view object if possible; otherwise, it will
        be a copy.  Note there is no guarantee of the *memory layout* (C- or
        Fortran- contiguous) of the returned array.
>>> a = np.arange(8)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7])
>>> np.reshape(a,(2,4))
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
>>> np.reshape(a,(4,2))
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7]])
>>> np.reshape(a,(8,1))
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5],
       [6],
       [7]])
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7])
>>> a.reshape(2,4)
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7])
>>> a.reshape(4,2)
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7]])
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7])

5- 數(shù)據(jù)類型

dtype對應(yīng)的類型除了內(nèi)置的int,float,complex等,可以用 np.bool_, np.int8, np.uint64:

bool_?? ?布爾型數(shù)據(jù)類型(True 或者 False)
int_?? ?默認(rèn)的整數(shù)類型(類似于 C 語言中的 long,int32 或 int64)
intc?? ?與 C 的 int 類型一樣,一般是 int32 或 int 64
intp?? ?用于索引的整數(shù)類型(類似于 C 的 ssize_t,一般情況下仍然是 int32 或 int64)
int8?? ?字節(jié)(-128 to 127)
int16?? ?整數(shù)(-32768 to 32767)
int32?? ?整數(shù)(-2147483648 to 2147483647)
int64?? ?整數(shù)(-9223372036854775808 to 9223372036854775807)
uint8?? ?無符號整數(shù)(0 to 255)
uint16?? ?無符號整數(shù)(0 to 65535)
uint32?? ?無符號整數(shù)(0 to 4294967295)
uint64?? ?無符號整數(shù)(0 to 18446744073709551615)
float_?? ?float64 類型的簡寫
float16?? ?半精度浮點(diǎn)數(shù),包括:1 個符號位,5 個指數(shù)位,10 個尾數(shù)位
float32?? ?單精度浮點(diǎn)數(shù),包括:1 個符號位,8 個指數(shù)位,23 個尾數(shù)位
float64?? ?雙精度浮點(diǎn)數(shù),包括:1 個符號位,11 個指數(shù)位,52 個尾數(shù)位
complex_?? ?complex128 類型的簡寫,即 128 位復(fù)數(shù)
complex64?? ?復(fù)數(shù),表示雙 32 位浮點(diǎn)數(shù)(實(shí)數(shù)部分和虛數(shù)部分)
complex128?? ?復(fù)數(shù),表示雙 64 位浮點(diǎn)數(shù)(實(shí)數(shù)部分和虛數(shù)部分)

每個內(nèi)建類型都有一個唯一定義它的字符代碼:

b?? ?布爾型
i?? ?(有符號) 整型
u?? ?無符號整型 integer
f?? ?浮點(diǎn)型
c?? ?復(fù)數(shù)浮點(diǎn)型
m?? ?timedelta(時間間隔)
M?? ?datetime(日期時間)
O?? ?(Python) 對象
S, a?? ?(byte-)字符串
U?? ?Unicode
V?? ?原始數(shù)據(jù) (void)

int8, int16, int32, int64 -- i1, i2, i4, i8
uint8,uint16,uint32,uint64 -- u1, u2, u4, u8
float16,float32,float64,float128 -- f2, f4, f8, f16
或: float32,float64,float128 -- f, d, g
complex64,complex128,complex256 -- c8,c16,c32
bool -- ?

>>> import numpy as np
>>> np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')])
dtype([('name', 'S20'), ('age', 'i1'), ('marks', '<f4')])
>>> import numpy as np
>>> student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')])
>>> student
dtype([('name', 'S20'), ('age', 'i1'), ('marks', '<f4')])
>>> np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student)
array([(b'abc', 21, 50.), (b'xyz', 18, 75.)],
      dtype=[('name', 'S20'), ('age', 'i1'), ('marks', '<f4')])
>>> a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student)
>>> print(a)
[(b'abc', 21, 50.) (b'xyz', 18, 75.)]

6- np.asarray()

asarray(...)
    asarray(a, dtype=None, order=None, *, like=None)
    
    Convert the input to an array.
    
    Parameters
    ----------
    a : array_like
        Input data, in any form that can be converted to an array.  This
        includes lists, lists of tuples, tuples, tuples of tuples, tuples
        of lists and ndarrays.
    dtype : data-type, optional
        By default, the data-type is inferred from the input data.
    order : {'C', 'F', 'A', 'K'}, optional
        Memory layout.  'A' and 'K' depend on the order of input array a.
        'C' row-major (C-style),
        'F' column-major (Fortran-style) memory representation.
        'A' (any) means 'F' if `a` is Fortran contiguous, 'C' otherwise
        'K' (keep) preserve input order
        Defaults to 'C'.
    like : array_like
        Reference object to allow the creation of arrays which are not
        NumPy arrays. If an array-like passed in as ``like`` supports
        the ``__array_function__`` protocol, the result will be defined
        by it. In this case, it ensures the creation of an array object
        compatible with that passed in via this argument.
    
        .. versionadded:: 1.20.0
>>> import numpy as np
>>> a = np.array([1,2,3])
>>> b = np.asarray(a)
>>> a,b
(array([1, 2, 3]), array([1, 2, 3]))
>>> a[0]=3
>>> a,b
(array([3, 2, 3]), array([3, 2, 3]))

注意 b=asarray(a)??與?b=array(a) 的區(qū)別,前者兩數(shù)組指向同一內(nèi)存地址。

7- np.fromiter()

fromiter(...)
    fromiter(iter, dtype, count=-1, *, like=None)
    
    Create a new 1-dimensional array from an iterable object.
    
    Parameters
    ----------
    iter : 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.
    like : array_like
        Reference object to allow the creation of arrays which are not
        NumPy arrays. If an array-like passed in as ``like`` supports
        the ``__array_function__`` protocol, the result will be defined
        by it. In this case, it ensures the creation of an array object
        compatible with that passed in via this argument.
    
        .. versionadded:: 1.20.0
    
    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.
>>> import numpy as np
>>> np.fromiter(range(5),dtype=int)
array([0, 1, 2, 3, 4])
>>> np.fromiter(range(5),dtype=float)
array([0., 1., 2., 3., 4.])
>>> iterable = (x*x for x in range(5))
>>> np.fromiter(iterable, float)
array([ 0.,  1.,  4.,  9., 16.])
>>> np.fromiter({1,2,3,4}, float)
array([1., 2., 3., 4.])
>>> np.array({1,2,3,4})
array({1, 2, 3, 4}, dtype=object)
#注意:array()不能從集合中取出元素,只能作為一個整體
>>> np.fromiter('Hann Yang',dtype='S1')
array([b'H', b'a', b'n', b'n', b' ', b'Y', b'a', b'n', b'g'], dtype='|S1')
>>> np.fromiter(b'Hann Yang',dtype=np.uint8)
array([ 72,  97, 110, 110,  32,  89,  97, 110, 103], dtype=uint8)
#注意:字節(jié)串b''與字符串str的區(qū)別

8- np.frombuffer()

流的形式讀入轉(zhuǎn)化成 ndarray 對象,還可以分批讀入。

frombuffer(...)
    frombuffer(buffer, dtype=float, count=-1, offset=0, *, like=None)
    
    Interpret a buffer as a 1-dimensional array.
    
    Parameters
    ----------
    buffer : buffer_like
        An object that exposes the buffer interface.
    dtype : data-type, optional
        Data-type of the returned array; default: float.
    count : int, optional
        Number of items to read. ``-1`` means all data in the buffer.
    offset : int, optional
        Start reading the buffer from this offset (in bytes); default: 0.
    like : array_like
        Reference object to allow the creation of arrays which are not
        NumPy arrays. If an array-like passed in as ``like`` supports
        the ``__array_function__`` protocol, the result will be defined
        by it. In this case, it ensures the creation of an array object
        compatible with that passed in via this argument.
    
        .. versionadded:: 1.20.0
>>> np.frombuffer('Hann Yang',dtype='S1')
Traceback (most recent call last):
  File "<pyshell#68>", line 1, in <module>
    np.frombuffer('Hann Yang',dtype='S1')
TypeError: a bytes-like object is required, not 'str'
>>> np.frombuffer(b'Hann Yang',dtype='S1')
array([b'H', b'a', b'n', b'n', b' ', b'Y', b'a', b'n', b'g'], dtype='|S1')
>>> np.frombuffer(b'Hann Yang',dtype=int)
Traceback (most recent call last):
  File "<pyshell#70>", line 1, in <module>
    np.frombuffer(b'Hann Yang',dtype=int)
ValueError: buffer size must be a multiple of element size
>>> np.frombuffer(b'Hann Yang',dtype=np.uint8)
array([ 72,  97, 110, 110,  32,  89,  97, 110, 103], dtype=uint8)
>>> np.frombuffer(b'Hann Yang',dtype='S1')
array([b'H', b'a', b'n', b'n', b' ', b'Y', b'a', b'n', b'g'], dtype='|S1')
>>> np.frombuffer(b'Hann Yang',dtype=np.uint8)
array([ 72,  97, 110, 110,  32,  89,  97, 110, 103], dtype=uint8)
>>> np.frombuffer(b'Hann Yang',dtype=np.uint8,count=4)
array([ 72,  97, 110, 110], dtype=uint8)
>>> np.frombuffer(b'Hann Yang',dtype=np.uint8,count=4,offset=4)
array([ 32,  89,  97, 110], dtype=uint8)
>>> np.frombuffer(b'Hann Yang',dtype=np.uint8,count=-1,offset=8)
array([103], dtype=uint8)

9.1- np.linspace()

以等差數(shù)列創(chuàng)建數(shù)組

linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
    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.
    
    .. versionchanged:: 1.16.0
        Non-scalar `start` and `stop` are now supported.
    
    .. versionchanged:: 1.20.0
        Values are rounded towards ``-inf`` instead of ``0`` when an
        integer ``dtype`` is specified. The old behavior can
        still be obtained with ``np.linspace(start, stop, num).astype(int)``
    
    Parameters
    ----------
    start : array_like
        The starting value of the sequence.
    stop : array_like
        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, the data type
        is inferred from `start` and `stop`. The inferred dtype will never be
        an integer; `float` is chosen even if the arguments would produce an
        array of integers.
    
        .. versionadded:: 1.9.0
    
    axis : int, optional
        The axis in the result to store the samples.  Relevant only if start
        or stop are array-like.  By default (0), the samples will be along a
        new axis inserted at the beginning. Use -1 to get an axis at the end.
    
        .. versionadded:: 1.16.0

創(chuàng)建區(qū)間可以是全開區(qū)間,也可以前開后閉區(qū)間。?

>>> 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)
>>> np.linspace(1, 1, 10, dtype=int)
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])

9.2- np.logspace()?

以對數(shù)數(shù)列創(chuàng)建數(shù)組

logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0)
    Return numbers spaced evenly on a log scale.
    
    In linear space, the sequence starts at ``base ** start``
    (`base` to the power of `start`) and ends with ``base ** stop``
    (see `endpoint` below).
    
    .. versionchanged:: 1.16.0
        Non-scalar `start` and `stop` are now supported.
    
    Parameters
    ----------
    start : array_like
        ``base ** start`` is the starting value of the sequence.
    stop : array_like
        ``base ** stop`` is the final value of the sequence, unless `endpoint`
        is False.  In that case, ``num + 1`` values are spaced over the
        interval in log-space, of which all but the last (a sequence of
        length `num`) are returned.
    num : integer, optional
        Number of samples to generate.  Default is 50.
    endpoint : boolean, optional
        If true, `stop` is the last sample. Otherwise, it is not included.
        Default is True.
    base : array_like, optional
        The base of the log space. The step size between the elements in
        ``ln(samples) / ln(base)`` (or ``log_base(samples)``) is uniform.
        Default is 10.0.
    dtype : dtype
        The type of the output array.  If `dtype` is not given, the data type
        is inferred from `start` and `stop`. The inferred type will never be
        an integer; `float` is chosen even if the arguments would produce an
        array of integers.
    axis : int, optional
        The axis in the result to store the samples.  Relevant only if start
        or stop are array-like.  By default (0), the samples will be along a
        new axis inserted at the beginning. Use -1 to get an axis at the end.
    
        .. versionadded:: 1.16.0
>>> np.logspace(2.0, 3.0, num=4)
array([ 100.        ,  215.443469  ,  464.15888336, 1000.        ])
>>> np.logspace(2.0, 3.0, num=4, endpoint=False)
array([100.        ,  177.827941  ,  316.22776602,  562.34132519])
>>> np.logspace(2.0, 3.0, num=4, base=2.0)
array([4.        ,  5.0396842 ,  6.34960421,  8.        ])

9.3- np.geomspace()?

geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0)
    Return numbers spaced evenly on a log scale (a geometric progression).
    
    This is similar to `logspace`, but with endpoints specified directly.
    Each output sample is a constant multiple of the previous.
    
    .. versionchanged:: 1.16.0
        Non-scalar `start` and `stop` are now supported.
    
    Parameters
    ----------
    start : array_like
        The starting value of the sequence.
    stop : array_like
        The final value of the sequence, unless `endpoint` is False.
        In that case, ``num + 1`` values are spaced over the
        interval in log-space, of which all but the last (a sequence of
        length `num`) are returned.
    num : integer, optional
        Number of samples to generate.  Default is 50.
    endpoint : boolean, optional
        If true, `stop` is the last sample. Otherwise, it is not included.
        Default is True.
    dtype : dtype
        The type of the output array.  If `dtype` is not given, the data type
        is inferred from `start` and `stop`. The inferred dtype will never be
        an integer; `float` is chosen even if the arguments would produce an
        array of integers.
    axis : int, optional
        The axis in the result to store the samples.  Relevant only if start
        or stop are array-like.  By default (0), the samples will be along a
        new axis inserted at the beginning. Use -1 to get an axis at the end.
    
        .. versionadded:: 1.16.0
>>> np.geomspace(1, 1000, num=4)
array([    1.,    10.,   100.,  1000.])
>>> np.geomspace(1, 1000, num=3, endpoint=False)
array([   1.,   10.,  100.])
>>> np.geomspace(1, 1000, num=4, endpoint=False)
array([   1.        ,    5.62341325,   31.6227766 ,  177.827941  ])
>>> np.geomspace(1, 256, num=9)
array([   1.,    2.,    4.,    8.,   16.,   32.,   64.,  128.,  256.])
    
#Note that the above may not produce exact integers:
    
>>> np.geomspace(1, 256, num=9, dtype=int)
array([  1,   2,   4,   7,  16,  32,  63, 127, 256])
>>> np.around(np.geomspace(1, 256, num=9)).astype(int)
array([  1,   2,   4,   8,  16,  32,  64, 128, 256])
    
#Negative, decreasing, and complex inputs are allowed:
    
>>> np.geomspace(1000, 1, num=4)
array([1000.,  100.,   10.,    1.])
>>> np.geomspace(-1000, -1, num=4)
array([-1000.,  -100.,   -10.,    -1.])
>>> np.geomspace(1j, 1000j, num=4)  # Straight line
array([0.   +1.j, 0.  +10.j, 0. +100.j, 0.+1000.j])
>>> np.geomspace(-1+0j, 1+0j, num=5)  # Circle
array([-1.00000000e+00+1.22464680e-16j, -7.07106781e-01+7.07106781e-01j,
            6.12323400e-17+1.00000000e+00j,  7.07106781e-01+7.07106781e-01j,
            1.00000000e+00+0.00000000e+00j])

10.1- 常量np.pi np.e np.nan np.inf 等

>>> np.pi
3.141592653589793
>>> np.e
2.718281828459045
>>> np.nan
nan
>>> np.inf
inf
>>> np.Inf
inf
>>> np.Infinity
inf
>>> np.PINF
inf
>>> np.NINF
-inf
>>> np.PZERO
0.0
>>> np.NZERO
-0.0

10.2- 常量數(shù)組 zeros() ones() empty()

>>> np.zeros((2,5))
array([[0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.]])
>>> np.zeros((2,5),dtype=int)
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])
>>> np.linspace(0, 0, 10, dtype=int).reshape((2,5))
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])
>>> 
>>> np.ones((3,4))
array([[1., 1., 1., 1.],
       [1., 1., 1., 1.],
       [1., 1., 1., 1.]])
>>> np.ones((3,4),dtype=int)
array([[1, 1, 1, 1],
       [1, 1, 1, 1],
       [1, 1, 1, 1]])
>>> np.linspace(1, 1, 12, dtype=int).reshape((3,4))
array([[1, 1, 1, 1],
       [1, 1, 1, 1],
       [1, 1, 1, 1]])
>>>
>>> np.linspace(1, 1, 12, dtype=int).reshape((3,4))*3
array([[3, 3, 3, 3],
       [3, 3, 3, 3],
       [3, 3, 3, 3]])
>>> np.linspace(1, 1, 12, dtype=int).reshape((3,4))*np.pi
array([[3.14159265, 3.14159265, 3.14159265, 3.14159265],
       [3.14159265, 3.14159265, 3.14159265, 3.14159265],
       [3.14159265, 3.14159265, 3.14159265, 3.14159265]])

10.3- 常量數(shù)組 zeros_like() ones_like() empty_like()

>>> arr = np.ones((3,4))
>>> np.zeros_like(arr)
array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.]])

10.4- 單位矩陣?np.eye() 或 np.identity()?對角線為1,其余為0

>>> np.eye(4)
array([[1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 0., 1.]])
>>> np.identity(4, dtype=int)
array([[1, 0, 0, 0],
       [0, 1, 0, 0],
       [0, 0, 1, 0],
       [0, 0, 0, 1]])

Python Numpy入門基礎(chǔ)(一)創(chuàng)建數(shù)組,Python,python,numpy,開發(fā)語言文章來源地址http://www.zghlxwxcb.cn/news/detail-621579.html

到了這里,關(guān)于Python Numpy入門基礎(chǔ)(一)創(chuàng)建數(shù)組的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 【Python入門知識】NumPy 數(shù)組搜索,案例+理論講解

    【Python入門知識】NumPy 數(shù)組搜索,案例+理論講解

    前言 嗨嘍~大家好呀,這里是魔王吶 ? ~! 搜索數(shù)組 可以在數(shù)組中搜索(檢索)某個值,然后返回獲得匹配的索引。 要搜索數(shù)組,請使用 where() 方法。 實(shí)例 查找值為 4 的索引: 運(yùn)行實(shí)例 更多python資料、源碼、教程: 點(diǎn)擊此處跳轉(zhuǎn)文末名片獲取 上例會返回一個元組:(array([

    2024年02月03日
    瀏覽(27)
  • 【Python 零基礎(chǔ)入門】 Numpy

    【Python 零基礎(chǔ)入門】 Numpy

    在眾多 Python 的數(shù)據(jù)處理庫中, Numpy 是一個非常強(qiáng)大的存在. Numpy 為我們提供了高性能的多維數(shù)組, 以及這些數(shù)組對象上的各種操作. 但是, 作為一個剛?cè)腴T Python 的新手, 你可能會問: \\\"為什么我需要 Numpy, 而不是直接使用Python 的內(nèi)置列表?\\\"在這篇文章的開篇, 我們就來探討這個問

    2024年02月08日
    瀏覽(32)
  • 【Python】數(shù)據(jù)科學(xué)工具(Numpy Pandas np.array() 創(chuàng)建訪問數(shù)組 向量與矩陣 Series DataFrame)

    1.Numpy numpy是Python中一個非常重要的科學(xué)計算庫,其最基礎(chǔ)的功能就是N維數(shù)組對象——ndarray。 1.1 數(shù)組的創(chuàng)建 1)np.array() 用 np.array() 函數(shù)可以將Python的序列對象(如列表、元組)轉(zhuǎn)換為ndarray數(shù)組。 2)arange、linspace、logspace np.arange(start, stop, step) :創(chuàng)建一個一維數(shù)組,其中的值

    2024年02月10日
    瀏覽(20)
  • 【Python 零基礎(chǔ)入門】Numpy 常用函數(shù) 通用函數(shù) & 保存加載

    【Python 零基礎(chǔ)入門】Numpy 常用函數(shù) 通用函數(shù) & 保存加載

    Numpy (Numerical Python) 是 Python 編程語言的一個擴(kuò)展程序庫, 支持大量的維度數(shù)組與矩陣運(yùn)算, 并提供了大量的數(shù)學(xué)函數(shù)庫. Numpy 利用了多線程數(shù)組來存儲和處理大型數(shù)據(jù)集, 從而提供了一個高效的方式來進(jìn)行數(shù)值計算, 特別是對于矩陣預(yù)算和線性代數(shù). 通用函數(shù) (Ufuncs) 是 numpy 的核

    2024年02月05日
    瀏覽(19)
  • 【Python Numpy】廣播、數(shù)組的迭代

    【Python Numpy】廣播、數(shù)組的迭代

    在Python的科學(xué)計算領(lǐng)域,NumPy是一個強(qiáng)大的工具,它提供了用于操作多維數(shù)組的功能。廣播(Broadcasting)是NumPy中的一個重要概念,它使得不同形狀的數(shù)組之間的計算變得非常靈活和便捷。本文將介紹廣播是什么,以及如何在NumPy中使用廣播來進(jìn)行數(shù)組計算。 在Python的科學(xué)計算

    2024年02月06日
    瀏覽(24)
  • Python numpy - 數(shù)組與矩陣的運(yùn)算

    Python numpy - 數(shù)組與矩陣的運(yùn)算

    目錄 ?數(shù)組array 一 數(shù)組的函數(shù) unique函數(shù) ?sum函數(shù) ?max函數(shù) 二 數(shù)組的加減 三 數(shù)組的乘除 ?矩陣matrix 一 矩陣的生成 二 矩陣的加減 三? 矩陣的乘法 創(chuàng)建數(shù)組a和b用來運(yùn)算(至少兩個) 數(shù)組常用函數(shù) 函數(shù) 作用 unique() 求數(shù)組里的唯一值,輸出從小到大排列 sum() 對數(shù)組整

    2024年02月11日
    瀏覽(25)
  • 【深度學(xué)習(xí)】 Python 和 NumPy 系列教程(十二):NumPy詳解:4、數(shù)組廣播;5、排序操作

    【深度學(xué)習(xí)】 Python 和 NumPy 系列教程(十二):NumPy詳解:4、數(shù)組廣播;5、排序操作

    目錄 一、前言 二、實(shí)驗(yàn)環(huán)境 三、NumPy 0、多維數(shù)組對象(ndarray) 多維數(shù)組的屬性 1、創(chuàng)建數(shù)組 2、數(shù)組操作 3、數(shù)組數(shù)學(xué) 4、數(shù)組廣播 5、排序操作 1. np.sort()?函數(shù) 2. np.argsort()?函數(shù) 3. ndarray.sort()?方法 4. 按列或行排序 5. np.lexsort()?函數(shù) 6. np.partition()?函數(shù) 7. np.argpartition()?函

    2024年02月08日
    瀏覽(31)
  • 【python】使用numpy創(chuàng)建同心矩陣

    【python】使用numpy創(chuàng)建同心矩陣

    輸入一個正奇數(shù)N,創(chuàng)建一個N*N的矩陣滿足: 1. 矩陣中心的元素為N,其外層被N-1包圍; 2. N-1的外層被N-2包圍; 3. 依次循環(huán),直到形成一個N*N的矩陣。 很容易可以計算得出,矩陣元素從內(nèi)到外遞減,最外層的元素為(N+1)/2. 我們可以使用numpy從外向內(nèi)地填充矩陣;首先生成一個

    2024年02月13日
    瀏覽(21)
  • 【Python入門第四十六天】Python丨NumPy 數(shù)組重塑

    【Python入門第四十六天】Python丨NumPy 數(shù)組重塑

    重塑意味著更改數(shù)組的形狀。 數(shù)組的形狀是每個維中元素的數(shù)量。 通過重塑,我們可以添加或刪除維度或更改每個維度中的元素數(shù)量。 實(shí)例 將以下具有 12 個元素的 1-D 數(shù)組轉(zhuǎn)換為 2-D 數(shù)組。 最外面的維度將有 4 個數(shù)組,每個數(shù)組包含 3 個元素: 運(yùn)行實(shí)例 從 1-D 重塑為 3-D

    2023年04月08日
    瀏覽(32)
  • python實(shí)戰(zhàn)應(yīng)用講解-【numpy數(shù)組篇】常用函數(shù)(八)(附python示例代碼)

    目錄 Python Numpy MaskedArray.cumprod()函數(shù) Python Numpy MaskedArray.cumsum()函數(shù) Python Numpy MaskedArray.default_fill_value()函數(shù) Python Numpy MaskedArray.flatten()函數(shù) Python Numpy MaskedArray.masked_equal()函數(shù) numpy.MaskedArray.cumprod() 返回在給定軸上被屏蔽的數(shù)組元素的累積乘積。在計算過程中,被屏蔽的值在內(nèi)部

    2024年02月02日
    瀏覽(35)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包