Article series address
- NumPy array
- NumPy Tutorial (2) : Data types
- NumPy tutorial (3) : NDARray internals and advanced iterations
Numpy is the core library for scientific computation in Python. The word Numpy comes from the words Numerical and Python. It provides a high performance multi-dimensional array objects, as well as a large number of library functions and operations, can help programmers easily perform numerical calculations, widely used in machine learning models, image processing and computer graphics, mathematical tasks and other fields.
Numpy array: ndarray
The most important object defined in NumPy is an N-dimensional array type called Ndarray, which is a collection of elements describing the same type. Each element in NdarRay is an object of a data type object (DType). Each element in NDARray uses the same size block in memory.
numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)
Copy the code
parameter | describe |
---|---|
object | Any object that exposes an array interface method |
dtype | The data type |
copy | If True, the object object is copied, otherwise, only if__array__ Return a copy, object is a nested sequence, or if the copy is required to meet any other requirements (dType, order, etc.). |
order | Specifies the memory layout of the array. If object is not an array, the newly created array is arranged in rows (C) or columns (F) if specified. If object is an array, the following is true. C (by row), F (by column), A (original order), K (order in which elements appear in memory) |
subok | By default, the returned array is forced to be a base array. If True, the subclass is returned. |
ndmin | Returns the minimum dimension of the array |
Example 1: The simplest example
import numpy as np
a = [1.2.3]
b = np.array(a)
print(b)
print(type(b))
Copy the code
Output:
[1 2 3]
<class 'numpy.ndarray'>
Copy the code
Note: List prints as [1, 2, 3] while Ndarray prints as [1, 2, 3] without commas.
NumPy supports a wider variety of numeric types than Python
import numpy as np
a = [1.2.3]
b = np.array(a, dtype=np.float_)
# or
b = np.array(a, dtype=float)
print(b)
print(b.dtype)
print(type(b[0]))
Copy the code
Output:
(1. 2. 3.]float64
<class 'numpy.float64'>
Copy the code
Example 3: Usage of the copy parameter
import numpy as np
a = np.array([1.2.3])
b = np.array(a, copy=True)
a[0] = 0
print(a)
print(b)
Copy the code
Output:
[0 2 3]
[1 2 3]
Copy the code
You can see that the values of A and B are different, indicating that B is a copy of A, and the two are different objects.
import numpy as np
a = np.array([1.2.3])
b = np.array(a, copy=False)
a[0] = 0
print(a)
print(b)
Copy the code
Output:
[0 2 3]
[0 2 3]
Copy the code
A change in A also causes a change in B, indicating that a and B refer to the same object.
Example 4: Example of ndMIN parameter usage
import numpy as np
a = [1.2.3]
b = np.array(a, ndmin=2)
print(b)
Copy the code
Output:
[[1 2 3]]
Copy the code
You can see that the result has become a two-dimensional array.
Example 5: Subok parameter usage example
See the explanation is not very clear, look at the following example will understand a lot. Where matrix is the matrix, which will be introduced later.
import numpy as np
a = np.matrix('1 2 7; 3, 4, 8; 5 6 9 ')
print(type(a))
print(a)
at = np.array(a, subok=True)
af = np.array(a, subok=False)
print(type(at))
print(type(af))
Copy the code
Output:
<class 'numpy.matrix'>
[[1 2 7]
[3 4 8]
[5 6 9]]
<class 'numpy.matrix'>
<class 'numpy.ndarray'>
Copy the code
NumPy array properties
The dimensions of a NumPy array are called ranks, with the rank of a one-dimensional array being 1, the rank of a two-dimensional array being 2, and so on. In NumPy, each linear array is called an axis, also known as a dimension.
attribute | instructions |
---|---|
ndarray.ndim | Rank is the number of axes or the number of dimensions |
ndarray.shape | The dimensions of an array, for a matrix, n rows and m columns |
ndarray.size | The total number of elements in the array, equivalent to the n*m value in.shape |
ndarray.dtype | The element type of the ndarray object |
ndarray.itemsize | The size, in bytes, of each element in an ndarray object |
ndarray.flags | Memory information about an Ndarray object |
ndarray.real | The real part of the element ndarray (real part of the complex number) |
ndarray.imag | The imaginary part of the nDARray element (the imaginary part of the complex number) |
ndarray.data | Buffers containing the actual array elements, which are usually retrieved by an array index, are not required to use this attribute. |
1, ndarray. Shape
Returns a tuple containing the dimensions of an array. For a matrix, n rows and m columns, it can also be used to adjust the dimensions of an array. Example 1:
import numpy as np
a = np.array([[1.2.3], [4.5.6]])
print(a.shape)
Copy the code
Output:
(2, 3)
Copy the code
Example 2:
import numpy as np
a = np.array([[1.2.3], [4.5.6]])
a.shape = (3.2)
print(a)
Copy the code
Output:
[1 2] [3 4] [5 6]]Copy the code
NumPy also provides a 0 () function to shape the array dimensions. Only 0 0 () returns the adjusted dimension copy instead of changing the original Ndarray.
import numpy as np
a = np.array([[1.2.3], [4.5.6]])
b = a.reshape(3.2)
print(b) # a hasn't changed
Copy the code
Output:
[1 2] [3 4] [5 6]]Copy the code
2, ndarray. Ndim
Returns the dimension (rank) of the array. Example 1:
import numpy as np
a = np.arange(24)
print(a.ndim)
# Now resize it
b = a.reshape(2.4.3)
print(b.ndim)
Copy the code
Output:
1
3
Copy the code
3, ndarray. Flags
Flags returns memory information for the nDARray object, including the following attributes:
attribute | describe |
---|---|
C_CONTIGUOUS | The data is in a single C-style continuous segment |
F_CONTIGUOUS | The data is in a single Fortran-style contiguous segment |
OWNDATA | An array owns the memory it uses or borrows it from another object |
WRITEABLE | The data area can be written to. If this value is set to False, the data is read-only |
ALIGNED | Data and all elements are properly aligned to the hardware |
WRITEBACKIFCOPY | UPDATEIFCOPY deprecated and replaced with WRITEBACKIFCOPY; |
UPDATEIFCOPY | This array is a copy of another array, and when this array is released, the contents of the original array are updated |
import numpy as np
a = np.array([[1.2.3], [4.5.6]])
print(a.flags)
Copy the code
Output:
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
WRITEBACKIFCOPY : False
UPDATEIFCOPY : False
Copy the code
4, ndarray. Real
import numpy as np
x = np.sqrt([1+0j.0+1j])
print(x)
print(x.real)
print(x.real.dtype)
Copy the code
Output:
[1. +0.j 0.70710678+0.70710678j] [1.float64
Copy the code
Constants in NumPy
- Inf = Inf = infty = Infinity = PINF
- Negative infinity: NINF
- Is zero: PZERO
- Negative zero: NZERO
- Non-numeric: nan = nan = nan
- The natural numbers e: e
- PI: PI,
- Gamma: euler_gamma
- Alias for None: newaxis
Example:
print(np.inf)
print(np.NINF)
print(np.PZERO)
print(np.NZERO)
print(np.nan)
print(np.e)
print(np.pi)
print(np.euler_gamma)
print(np.newaxis)
Copy the code
Output:
inf
-inf
0.0
0.0
nan
2.718281828459045
3.141592653589793
0.5772156649015329
None
Copy the code
NumPy creates an array
1, numpy. Empty
This method creates an uninitialized array of dimensions (shape) and data type (dType).
numpy.empty(shape, dtype=float, order='C')
Copy the code
parameter | describe |
---|---|
shape | A tuple representing the dimensions of an array |
dtype | The data type |
order | There are two choices: “C” and “F” |
Example:
import numpy as np
x = np.empty([3.2], dtype=int)
print(x)
Copy the code
Output:
[0 1072693248] [0 1072693248]]Copy the code
The empty() method, unlike the zeros() method, does not set the array value to zero, so it may be slightly faster. On the other hand, it requires the user to manually set all the values in the array and should be used with caution.
2, numpy. Zeros
Creates a new array filled with 0 for the specified dimension.
numpy.zeros(shape, dtype=float, order='C')
Copy the code
Example:
import numpy as np
x = np.zeros(5)
print(x)
Copy the code
Output:
[0. 0. 0. 0.Copy the code
Note: The default is float
3, numpy. ‘ones
Creates a new array filled with 1 for the specified dimension.
numpy.ones(shape, dtype=float, order='C')
Copy the code
Example:
import numpy as np
x = np.ones(5)
print(x)
Copy the code
Output:
[1. 1. 1.Copy the code
4, numpy. Full
Returns a new array of the given dimension and type, filled with fill_value.
numpy.full(shape, fill_value, dtype=None, order='C')
Copy the code
parameter | describe |
---|---|
shape | Returns the dimension of the array |
fill_value | Filling it |
dtype | Returns the data type of the array. The default value None means:np.array(fill_value).dtype |
order | The order in which elements are stored in computer memory, only ‘C’ (by row), ‘F’ (by column) supported, default ‘C’ |
Example:
import numpy as np
a = np.full((2.3), 9)
print(a)
Copy the code
Output:
[[9 9 9]]Copy the code
NumPy creates arrays from numeric ranges
1, numpy. Arange
This function is equivalent to Python’s built-in range function, but returns an Ndarray instead of a list.
arange([start,] stop[, step,], dtype=None)
Copy the code
[] indicates optional parameters.
parameter | describe |
---|---|
start | Start value, default is 0 |
stop | Termination value (not included) |
step | Step size, default is 1 |
dtype | The data type of the created Ndarray, if not provided, will use the type of the input data. |
Example:
import numpy as np
a = np.arange(5)
b = np.arange(10.20.2)
print(a)
print(b)
Copy the code
Output:
[0 12 3 4] [10 12 14 16 18]Copy the code
2, numpy. Linspace
Create an array of one-dimensional arithmetic sequences, unlike arange, which has a fixed step size, and Linspace, which has a fixed number of elements.
linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
Copy the code
parameter | describe |
---|---|
start | The starting value of the sequence |
stop | The end value of the sequence, which is included in the sequence if endpoint is True |
num | Number of equal-step samples to generate, default is 50 |
endpoint | When this value is True, the stop value is included in the array; otherwise, it is not. The default value is True. |
retstep | Spacing is displayed in the generated array if True, and not otherwise. |
dtype | The data type of NDARRay |
Example 1: Usage of endpoint parameters
I chose the following verbose example to show the effect of the endpoint. If num = num + 1, the endpoint=False is set to True. Num = num; num = num; num = num;
import numpy as np
a = np.linspace(0.5.3, endpoint=False)
b = np.linspace(0.5.4, endpoint=True)
print(a)
print(b)
Copy the code
Output:
[0.1.66666667 3.3333333333] [0.1.66666667 3.33333333 5]Copy the code
Example 2: Usage of retstep parameter
Returns a tuple. The first element is numpy.ndarray and the second element is the step size.
import numpy as np
a = np.linspace(0.10.5, retstep=True)
print(a)
Copy the code
Output:
(array([0., 2.5, 5., 7.5, 10.]), 2.5)Copy the code
Example 3: dtype parameter
The dtype argument casts the result to the type specified by dtype. If float is converted to int, the final value may not be equal.
import numpy as np
a = np.linspace(0.10.5, dtype=int)
print(a)
Copy the code
Output:
[0 2 5 7 10]Copy the code
3, numpy. Logspace
The numpy.logspace function is used to create a geometric sequence.
Numpy. logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)Copy the code
parameter | describe |
---|---|
start | The starting value of the sequence is:base ** start (Power operation) |
stop | The termination value of the sequence is:base ** stop . If the endpoint is True, this value is included in the array |
num | Number of equal-step samples to generate, default is 50 |
endpoint | When this value is True, the stop value is included in the array; otherwise, it is not. The default value is True. |
base | Log the base of log. |
dtype | The data type of NDARRay |
Example:
There is nothing to say, except to note that the start parameter is not the actual starting value.
import numpy as np
a = np.logspace(1.4, num=4)
print(a)
Copy the code
Output:
[10.100.1000.10000]Copy the code
4, numpy. Geomspace
Create a one-dimensional geometric sequence.
numpy.geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0)
Copy the code
parameter | describe |
---|---|
start | The starting value of the sequence |
stop | The end value of the sequence, which is included in the sequence if endpoint is True |
num | Number of samples to generate, default is 50 |
endpoint | When this value is True, the stop value is included in the array; otherwise, it is not. The default value is True. |
dtype | The data type of NDARRay |
axis | 1.16.0 is a new feature, I don’t understand how to use it, there is not even an example on the official website, when the value is 0 and -1, the result is the same, other times the error. |
Example:
import numpy as np
a = np.geomspace(1.8, num=4)
print(a)
Copy the code
Output:
(1. 2. 4. 8.]Copy the code
NumPy creates an array from an existing array
1, numpy. Asarray
Numpy. asarray is similar to numpy.array, but numpy.asarray takes only three parameters.
numpy.asarray(a, dtype=None, order=None)
Copy the code
parameter | describe |
---|---|
a | Input data can be converted to any form of array. This includes lists, tuple lists, tuples, tuples, list tuples and Ndarray. |
dtype | The data type |
order | The order in which elements are stored in computer memory, only ‘C’ (by row), ‘F’ (by column) supported, default ‘C’ |
Example:
import numpy as np
a = np.asarray([1.2.3])
print(a)
Copy the code
Output:
[1, 2, 3]Copy the code
2, numpy. Frombuffer
Numpy. Frombuffer is used to implement dynamic arrays. Numpy. Frombuffer takes buffer input parameters and is read as a stream into an Ndarray object.
numpy.frombuffer(buffer, dtype=float, count=-1, offset=0)
Copy the code
parameter | describe |
---|---|
buffer | To achieve the__buffer__ Method object, (definitely not any object as described in the tutorial) |
dtype | Returns the data type of the array |
count | Number of data read, default is -1, read all data. |
offset | The starting position for reading, which defaults to 0. |
Example 1: When buffer is a string, Python3 defaults STR to Unicode, so replace STR with byteString and append b to STR.
import numpy as np
a = np.frombuffer(b'Hello World', dtype='S1')
print(a)
Copy the code
Output:
[b'H' b'e' b'l' b'l' b'o' b' ' b'W' b'o' b'r' b'l' b'd']
Copy the code
Example 2: After seeing the above example, it seems that “implementing dynamic array” does not feel very much, so let’s look at this example.
import numpy as np
import array
a = array.array('i'[1.2.3.4])
print(a)
na = np.frombuffer(a, dtype=np.int_)
print(na)
a[0] = 10
print(a)
print(na)
Copy the code
Output:
array('i', [1, 2, 3, 4])
[1 2 3 4]
array('i', [10, 2, 3, 4])
[10 2 3 4]
Copy the code
Array. array creates an array object that is contiguous in memory. ‘list’ object has no attribute ‘__buffer__’), numpy. Frombuffer creates an array from array.array. The value of numpy. Frombuffer will also change, as you can see.
Example 3:
Array. It is ok to change values in array, but not to add values.
import numpy as np
import array
a = array.array("i"[1.2.3.4])
na = np.frombuffer(a, dtype=int)
print(na)
a.append(5)
print(na)
Copy the code
Output:
[1 2 3 4]
[140896288 381 3 4]
Copy the code
3, numpy. Fromiter
The numpy.fromiter method builds an Ndarray object from an iterable and returns a one-dimensional array.
numpy.fromiter(iterable, dtype, count=-1)
Copy the code
parameter | describe |
---|---|
可迭代 | iterable |
dtype | Returns the data type of the array |
count | Number of data read, default is -1, read all data |
Example 1:
import numpy as np
iterable = (x * x for x in range(5))
a = np.fromiter(iterable, int)
print(a)
Copy the code
Output:
[0 1 4 9 16]Copy the code
Array looks a bit like numpy.array, where the array method passes in a list, whereas Fromiter can pass in an iterable.
Example 2: Try replacing the above example with array.
import numpy as np
iterable = (x * x for x in range(5))
a = np.array(iterable)
print(a)
Copy the code
Output:
<generator object <genexpr> at 0x000000001442DD00>
Copy the code
4, empty_like
Returns a new, uninitialized array of the same dimension and type as the given array.
numpy.empty_like(prototype, dtype=None, order='K', subok=True)
Copy the code
parameter | describe |
---|---|
prototype | Given array |
dtype | Overrides the resulting data type, new in version 1.6.0. |
order | Specifies the memory layout of the array. C (by row), F (by column), A (original order), K (order in which elements appear in memory) |
subok | By default, the returned array is forced to be a base array. If True, the subclass is returned. |
Example:
import numpy as np
a = np.empty_like([[1.2.3], [4.5.6]])
print(a)
Copy the code
Output: *
[[870 0 0] [0 0 0]Copy the code
5, zeros_like
numpy.zeros_like(a, dtype=None, order='K', subok=True)
Copy the code
Same as above.
Example:
import numpy as np
a = np.zeros_like([[1.0.2.0.3.0], [4.0.5.0.6.0]])
print(a)
Copy the code
Output: *
[0. 0.] [0. 0.]Copy the code
6, ones_like
numpy.ones_like(a, dtype=None, order='K', subok=True)
Copy the code
Same as above.
Example:
import numpy as np
a = np.ones_like([[1.2.3], [4.5.6]])
print(a)
Copy the code
Output: *
[[1 1 1]]Copy the code
7, numpy. Full_like
Returns an array of the same dimension and type as the given array and filled with fill_value.
numpy.full_like(a, fill_value, dtype=None, order='K', subok=True)
Copy the code
parameter | describe |
---|---|
a | Given array |
fill_value | Filling it |
dtype | Returns the data type of the array, default None, using the type of the given array |
order | Specifies the memory layout of the array. C (by row), F (by column), A (original order), K (order in which elements appear in memory) |
subok | By default, the returned array is forced to be a base array. If True, the subclass is returned. |
Zeros_like and ONES_LIKE are exceptions to this method.
Example:
import numpy as np
x = np.arange(6, dtype=int)
print(x)
print('-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --')
a = np.full_like(x, 1)
b = np.full_like(x, 0.1)
c = np.full_like(x, 0.1, dtype=np.double)
print(a)
print(b)
print(c)
Copy the code
Output:
[0 1 2 3 4 5] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -1 1 1 1 1 1]
[0 0 0 0 0 0]
[0.1 0.1 0.1 0.1 0.1 0.1]
Copy the code
The Path of Python for older code farmers