Python math library Numpy getting started creating arrays

Posted by djsl on Tue, 18 Jan 2022 02:43:59 +0100

install

c:\> pip install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple

Official Guide

NumPy quickstart — NumPy v1.22 Manualhttps://numpy.org/doc/stable/user/quickstart.html

>>> import numpy
>>> help(numpy)
Squeezed text(75939 lines).
>>> 

There are nearly 76000 lines of internal help documents. Choosing some to learn from is a glimpse of the leopard——
 

Basic introduction (I)

Create array

1- np.array()

There are many parameters. When learning, just pay attention to the basic usage.

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

Tuple, list conversion

>>> 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]])

Built in function 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]])

Array copy, open up a new memory to copy the original array

>>> 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]))

Main parameters:
dtype = data type of array element, optional
copy = whether the object needs to be copied, optional
order = the style of creating the array. C is the row direction, F is the column direction, and A is any direction (default)
subok = returns an array consistent with the base class type by default
ndmin = Specifies the minimum dimension of the generated array

>>> 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') #The collection can only be taken as a whole. The capital letter O is 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 - basic properties shape  . ndim .dtype .size, etc

>>> 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 #The constant is 0-dimensional
>>> 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 * rank, that is, the number of axes or dimensions
. shape = the dimension of the array. For the matrix, n rows and m columns
. size the total number of array elements, equivalent to Value of n*m in shape
The element type of the. dtype} object
The size, in bytes, of each element in the. itemsize. Object
Memory information of. flags , object
The real part of the. Real} element
Imaginary part of. imag} element
. data * buffer containing the actual array elements. Since the elements are generally obtained through the index of the array, this attribute is usually not required.  

2.2 - Method with the same name as attribute

Except itemsize .flags .data has a method with the same name, and the parameters of other methods are ndarray, except 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. Range () and np Array (range()) is similar, but the former allows floating-point numbers

>>> 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 - data type

In addition to the built-in int,float,complex, etc., the types corresponding to dtype can be NP bool_, np. int8, np. uint64:

bool_ Boolean data type (True or False)
int_ Default integer type (similar to long, int32 or int64 in C language)
intc is the same as the int type of C, usually int32 or int 64
intp = integer type used for index (similar to C's ssize_t, which is still int32 or int64 in general)
int8 bytes (- 128 to 127)
int16 integer (- 32768 to 32767)
int32 integer (- 2147483648 to 2147483647)
int64 - integer (- 9223372036854775808 to 9223372036854775807)
uint8# unsigned integer (0 to 255)
uint16# unsigned integer (0 to 65535)
uint32# unsigned integer (0 to 4294967295)
uint64# unsigned integer (0 to 18446744073709551615)
float_ Abbreviation for float64 type
float16 ¢ semi precision floating-point number, including 1 symbol bit, 5 finger digits and 10 trailing digits
float32 single precision floating-point number, including: 1 symbol bit, 8 finger digits and 23 trailing digits
float64 - double precision floating-point number, including 1 sign bit, 11 finger bits and 52 tail bits
complex_ Abbreviation of complex128 type, i.e. 128 bit complex number
complex64 ¢ complex number, representing double 32-bit floating-point number (real part and imaginary part)
complex128 complex number, representing double 64 bit floating-point number (real part and imaginary part)

Each built-in type has a unique character code that defines it:

b) Boolean
i (signed) integer
u) unsigned integer
f = floating point
c) complex floating point
m # timedelta (time interval)
M # datetime
O (Python) object
S. A (byte -) string
U    Unicode
V original data (void)

For example, string 'i1', 'i2','i4','i8' can be used instead of int8, int16, int32 and Int64

>>> 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]))

Note the difference between b=asarray(a) and b=array(a). The former two arrays point to the same memory address.

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)
#Note: array() cannot take out elements from the collection, but can only be used as a whole
>>> 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)
#Note: the difference between byte string b '' and string str

8- np.frombuffer()

Read in the form of stream is transformed into ndarray object, and it can also be read in batches.

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()

Create an array in an arithmetic sequence

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

The created interval can be a fully open interval or a front open and back closed interval.  

>>> 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() 

Create an array in a logarithmic sequence

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 - constant NP pi np. e np. nan np. Inf et al

>>> 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 - constant array zeros() ones()

>>> 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]])

To be continued  

Topics: Python numpy