Detailed introduction to common numpy usage

高洛峰
Release: 2017-03-20 11:58:43
Original
1254 people have browsed it

numpy Introduction

The existence of numpy makes python have powerful matrix computing capabilities, no less than matlab.
Official documentation (https://docs.scipy.org/doc/numpy-dev/user/quickstart.html)

Introduction to various usages

The first is # in numpy ##Data type, ndarray type, is different from array.array in the standard library.

Some

properties of ndarray

ndarray.ndimthe number of axes (dimensions) of the array. In the Python world, the number of dimensions is referred to as rank.

ndarray.shapethe dimensions of the array. This is a tuple of integers indicating the size of the array in
each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the rank, or number of dimensions, ndim.
ndarray.sizethe total number of elements of the array. This is equal to the product of the elements of shape.

ndarray.dtypean object describing the type of the elements in the array. One can create or specify dtype's using standard Python types. Additionally NumPy provides types of its own. numpy.int32, numpy.int16, and numpy.
float64 are some examples.
ndarray.itemsizethe size in bytes of each element of the array. For example, an array of elements of type float64 has itemsize 8 (=64/8),
while one of type complex32 has itemsize 4 (=32/8). It is equivalent to ndarray.dtype.itemsize.
ndarray.datathe buffer containing the actual elements of the array. Normally, we won't need to use this attribute because we will access the elements in an array using indexing facilities.

Creation of ndarray

>>> import numpy as np>>> a = np.array([2,3,4])>>> a
array([2, 3, 4])>>> a.dtype
dtype('int64')>>> b = np.array([1.2, 3.5, 5.1])>>> b.dtype
dtype('float64')
Copy after login

two-dimensional

array

>>> b = np.array([(1.5,2,3), (4,5,6)])>>> b
array([[ 1.5,  2. ,  3. ],
       [ 4. ,  5. ,  6. ]])
Copy after login
Specify the type when creating

>>> c = np.array( [ [1,2], [3,4] ], dtype=complex )>>> c
array([[ 1.+0.j,  2.+0.j],
       [ 3.+0.j,  4.+0.j]])
Copy after login
Create some special matrices

>>> np.zeros( (3,4) )
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
>>> np.ones( (2,3,4), dtype=np.int16 )                # dtype can also be specified
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]]], dtype=int16)
>>> np.empty( (2,3) )                                 # uninitialized, output may vary
array([[  3.73603959e-262,   6.02658058e-154,   6.55490914e-260],
       [  5.30498948e-313,   3.14673309e-307,   1.00000000e+000]])
Copy after login

Create some matrices with specific rules

>>> np.arange( 10, 30, 5 )
array([10, 15, 20, 25])
>>> np.arange( 0, 2, 0.3 )                 # it accepts float arguments
array([ 0. ,  0.3,  0.6,  0.9,  1.2,  1.5,  1.8])

>>> from numpy import pi
>>> np.linspace( 0, 2, 9 )                 # 9 numbers from 0 to 2
array([ 0.  ,  0.25,  0.5 ,  0.75,  1.  ,  1.25,  1.5 ,  1.75,  2.  ])
>>> x = np.linspace( 0, 2*pi, 100 )        # useful to evaluate function at lots of points
>>> f = np.sin(x)
Copy after login

Some basic operations

Addition, subtraction, multiplication and division triangle

FunctionLogical operation

>>> a = np.array( [20,30,40,50] )
>>> b = np.arange( 4 )
>>> b
array([0, 1, 2, 3])
>>> c = a-b
>>> c
array([20, 29, 38, 47])
>>> b**2
array([0, 1, 4, 9])
>>> 10*np.sin(a)
array([ 9.12945251, -9.88031624,  7.4511316 , -2.62374854])
>>> a<35
array([ True, True, False, False], dtype=bool)
Copy after login

Matrix operation

There are .*,./ etc. in matlab
But in numpy, if you use +, -, ×,/The priority is to perform addition, subtraction, multiplication and division between each point
If two matrices (square matrices) can both perform operations between elements and perform matrix operations, the operations between elements will be performed first

>>> import numpy as np>>> A = np.arange(10,20)>>> B = np.arange(20,30)>>> A + B
array([30, 32, 34, 36, 38, 40, 42, 44, 46, 48])>>> A * B
array([200, 231, 264, 299, 336, 375, 416, 459, 504, 551])>>> A / B
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])>>> B / A
array([2, 1, 1, 1, 1, 1, 1, 1, 1, 1])
Copy after login

If you need to perform a matrix operation, it is usually a matrix multiplication operation

>>> A = np.array([1,1,1,1])
>>> B = np.array([2,2,2,2])
>>> A.reshape(2,2)
array([[1, 1],
       [1, 1]])
>>> B.reshape(2,2)
array([[2, 2],
       [2, 2]])
>>> A * B
array([2, 2, 2, 2])
>>> np.dot(A,B)
8
>>> A.dot(B)
8
Copy after login

Some commonly used

global functions

>>> B = np.arange(3)
>>> B
array([0, 1, 2])
>>> np.exp(B)
array([ 1.        ,  2.71828183,  7.3890561 ])
>>> np.sqrt(B)
array([ 0.        ,  1.        ,  1.41421356])
>>> C = np.array([2., -1., 4.])
>>> np.add(B, C)
array([ 2.,  0.,  6.])
Copy after login

Matrix index slice traversal

>>> a = np.arange(10)**3
>>> a
array([  0,   1,   8,  27,  64, 125, 216, 343, 512, 729])
>>> a[2]
8
>>> a[2:5]
array([ 8, 27, 64])
>>> a[:6:2] = -1000    # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000
>>> a
array([-1000,     1, -1000,    27, -1000,   125,   216,   343,   512,   729])
>>> a[ : :-1]                                 # reversed a
array([  729,   512,   343,   216,   125, -1000,    27, -1000,     1, -1000])
>>> for i in a:
...     print(i**(1/3.))
...
nan
1.0
nan
3.0
nan
5.0
6.0
7.0
8.0
9.0
Copy after login

Traversal of matrices

>>> import numpy as np
>>> b = np.arange(16).reshape(4, 4)
>>> for row in b:
...  print(row)
... 
[0 1 2 3]
[4 5 6 7]
[ 8  9 10 11]
[12 13 14 15]
>>> for node in b.flat:
...  print(node)
... 
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Copy after login

Special operations of matrices

Change the shape of the matrix--reshape

>>> a = np.floor(10 * np.random.random((3,4)))
>>> a
array([[ 6.,  5.,  1.,  5.],
       [ 5.,  5.,  8.,  9.],
       [ 5.,  5.,  9.,  7.]])
>>> a.ravel()
array([ 6.,  5.,  1.,  5.,  5.,  5.,  8.,  9.,  5.,  5.,  9.,  7.])
>>> a
array([[ 6.,  5.,  1.,  5.],
       [ 5.,  5.,  8.,  9.],
       [ 5.,  5.,  9.,  7.]])
Copy after login

The difference between resize and reshape


resize will change the original matrix, reshape will not

>>> a
array([[ 6.,  5.,  1.,  5.],
       [ 5.,  5.,  8.,  9.],
       [ 5.,  5.,  9.,  7.]])
>>> a.reshape(2,-1)
array([[ 6.,  5.,  1.,  5.,  5.,  5.],
       [ 8.,  9.,  5.,  5.,  9.,  7.]])
>>> a
array([[ 6.,  5.,  1.,  5.],
       [ 5.,  5.,  8.,  9.],
       [ 5.,  5.,  9.,  7.]])
>>> a.resize(2,6)
>>> a
array([[ 6.,  5.,  1.,  5.,  5.,  5.],
       [ 8.,  9.,  5.,  5.,  9.,  7.]])
Copy after login

Merger of matrices

>>> a = np.floor(10*np.random.random((2,2)))>>> a
array([[ 8.,  8.],
       [ 0.,  0.]])>>> b = np.floor(10*np.random.random((2,2)))>>> b
array([[ 1.,  8.],
       [ 0.,  4.]])>>> np.vstack((a,b))
array([[ 8.,  8.],
       [ 0.,  0.],
       [ 1.,  8.],
       [ 0.,  4.]])>>> np.hstack((a,b))
array([[ 8.,  8.,  1.,  8.],
       [ 0.,  0.,  0.,  4.]])
Copy after login

The above is the detailed content of Detailed introduction to common numpy usage. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template