Summary of array usage in Numpy library of python foundation

  • 2021-11-24 02:06:44
  • OfStack

Why do you want to use the creation of numpy array in directory preface Generate uniformly distributed array: Generate special array to get the attribute array index of array, slice and assign array operation to output array summary

Preface

Numpy is a scientific computing library of Python, which provides the function of matrix operation, and is used as Scipy and matplotlib1. In fact, list already provides a matrix-like representation, but numpy provides us with more functions.

The NumPy array is a multidimensional array object called ndarray. The subscript of the array starts from 0, and all elements in the same NumPy array must be of the same type.


>>> import numpy as np

Why use numpy

The list container is provided in Python and can be used as an array. But the elements in the list can be any object, so what is stored in the list is a pointer to the object, so in order to store a simple list [1, 2, 3]. You need three pointers and three integer objects. For numerical operations, this structure is obviously not efficient enough.

Although array also provides array module, it only supports 1-dimensional arrays, but does not support multi-dimensional arrays (in TensorFlow, matrix understanding is preferred), and there are no various operation functions. Therefore, it is not suitable for numerical operation.

The emergence of NumPy makes up for these shortcomings.

Creation of arrays

Use the numpy. array method to convert tuple and list, array, or other sequential schema data to ndarray, creating a new ndarray by default.


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

>>> b = array( [ (1.5,2,3), 
                 (4,5,6)  ]  )     
array([[ 1.5,  2. ,  3. ],  
         [ 4. ,  5. ,  6. ]])  

>>> c = array( [ [1,2], [3,4] ], dtype=complex)  
# Specifies the type of elements in the array 
>>> c  
    array([[ 1.+0.j,  2.+0.j],  
           [ 3.+0.j,  4.+0.j]]) 

Generate uniformly distributed array:

arange (Minimum, Maximum, Step Size) (Left Closed and Right Open): Create Arithmetic Series

linspace (Minimum, Maximum, Number of Elements)

logspace (start value, end value, number of elements): Create geometric sequence


>>> np.arange(15)
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]

>>> np.arange(15).reshape(3,5)
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]

>>> np.arange( 0, 2, 0.3 )        
array([ 0. ,  0.3,  0.6,  0.9,  1.2,  1.5,  1.8])

>>> np.linspace(1,3,9)
[ 1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.  ]

Generate a special array

np. ones: Create an array with all elements of 1

np. zeros: Create an array with all zeros, similar to np. ones

np. empty creates an array whose contents are random and dependent on the state of memory.

np. eye: Creates a matrix with 1 diagonal and 0 others.

np. identity: Creates a square matrix with 1 main diagonal and 0 others.


>>> np.zeros((3,4))
[[ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]]

>>> np.ones((3,4))
[[ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]]

>>> np.eye(3)
[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]

Gets the properties of an array


>>> a = np.zeros((2,2,2))
>>> a.ndim   # Dimension of array 
3
>>> a.shape  # Array per 1 Dimension size 
(2, 2, 2)
>>> a.size   # Number of all elements of the array  
8
>>> a.dtype  # The type of element in the array 
float64
>>> print a.itemsize  # Number of bytes per element 
8

Array index, slicing, assignment

The '…' symbol indicates that all dimensions with no specified index are assigned as': '

''Represents all elements of the dimension in python


>>> a = np.array( [[2,3,4],[5,6,7]] )
>>> a
[[2 3 4]
 [5 6 7]]
>>> a[1,2]
7
>>> a[1,:]
[5 6 7]
>>> print a[1,1:2]
[6]
>>> a[1,:] = [8,9,10]
>>> a
[[ 2  3  4]
 [ 8  9 10]]
>>> c[1,...]                                   # same as c[1,:,:] or c[1]
array([[100, 101, 102],
       [110, 112, 113]])
>>> c[...,2]                                   # same as c[:,:,2]
array([[  2,  13],
       [102, 113]])
>>> def f(x,y):
...     return 10*x+y
...
>>> b = np.fromfunction(f,(5,4),dtype=int)    #
>>> b
array([[ 0,  1,  2,  3],
       [10, 11, 12, 13],
       [20, 21, 22, 23],
       [30, 31, 32, 33],
       [40, 41, 42, 43]]) 

Array operation


>>> a = np.ones((2,2))
>>> b = np.eye(2)
>>> print a
[[ 1.  1.]
 [ 1.  1.]]
>>> print b
[[ 1.  0.]
 [ 0.  1.]]

>>> print a > 2
[[False False]
 [False False]]
>>> print a+b             # Array addition, corresponding position addition 
[[ 2.  1.]
 [ 1.  2.]]
>>> print a-b             # Array subtraction, corresponding position subtraction 
[[ 0.  1.]
 [ 1.  0.]]
>>> print b*2             # The array is multiplied by a numeric value, and the corresponding position is multiplied 
[[ 2.  0.]
 [ 0.  2.]]
>>> print (a*2)*(b*2)     # Array multiplied by array, by position 1 Right 1 Multiplication 
[[ 4.  0.]
 [ 0.  4.]]
>>> print b/(a*2)          # Array is divided by array, by position 1 Right 1 Division 
[[ 0.5  0. ]
 [ 0.   0.5]]
>>> print a.dot(b)                    # matrix product Matrix multiplication 
>>> np.dot(a,a)                       # Matrix multiplication 
array([[ 2.,  2.],
       [ 2.,  2.]])
>>> print (a*2)**4
[[ 16.  16.]
 [ 16.  16.]]
>>> b = a              # Shallow copy 
>>> b is a
True
>>> c = a.copy()       # Deep copy 
>>> c is a
False

Built-in functions (min, max, sum) and you can use axis to specify which dimension to operate on:


 >>> a.sum()
4.0
>>> a.sum(axis=0)    # Calculate every 1 Column ( 2 A matrix-like column in a dimensional array 
array([ 2.,  2.])
>>> a.min()          # Array minimum value 
1.0
>>> a.max()          # Maximum value of array 
1.0

Use the method under numpy:


>>> np.sin(a)
array([[ 0.84147098,  0.84147098],
       [ 0.84147098,  0.84147098]])
>>> np.max(a)
1.0
>>> np.floor(a)  
array([[ 1.,  1.],
       [ 1.,  1.]])
>>> np.exp(a)               #e^x
array([[ 2.71828183,  2.71828183],
       [ 2.71828183,  2.71828183]])
>>> print np.vstack((a,b))   # Merge array 
[[ 1.  1.] 
 [ 1.  1.]
 [ 1.  0.]
 [ 0.  1.]]
>>> print np.hstack((a,b))   # Merge array 
[[ 1.  1.  1.  0.]
 [ 1.  1.  0.  1.]]
>>> print a.transpose()       # Transposition 

The numpy. linalg module has many methods for matrix operations:


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

>>> b = array( [ (1.5,2,3), 
                 (4,5,6)  ]  )     
array([[ 1.5,  2. ,  3. ],  
         [ 4. ,  5. ,  6. ]])  

>>> c = array( [ [1,2], [3,4] ], dtype=complex)  
# Specifies the type of elements in the array 
>>> c  
    array([[ 1.+0.j,  2.+0.j],  
           [ 3.+0.j,  4.+0.j]]) 
0

Basic data types in NumPy

名称 描述
bool 用1个字节存储的布尔类型(True或False)
inti 由所在平台决定其大小的整数(1般为int32或int64)
int8/16/32/64 整数,1/2/4/8个字节大小
uint8/16/32/64 无符号整数
float16/32/64 半/单/双精度浮点数,16/32/64位,指数、精度也不同
complex64/128 复数,分别用两个32/64位浮点数表示实部和虚部

Output array

When outputting 1 array, NumPy is displayed in a nested list-like form in a specific layout:

Line 1 outputs from left to right Each slice is separated from the next one by one blank line 1-dimensional arrays are printed into rows, 2-dimensional arrays form matrices, and 3-dimensional arrays form matrix lists. If one array is too long, NumPy automatically omits the middle part and prints only the data at both ends:

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

>>> b = array( [ (1.5,2,3), 
                 (4,5,6)  ]  )     
array([[ 1.5,  2. ,  3. ],  
         [ 4. ,  5. ,  6. ]])  

>>> c = array( [ [1,2], [3,4] ], dtype=complex)  
# Specifies the type of elements in the array 
>>> c  
    array([[ 1.+0.j,  2.+0.j],  
           [ 3.+0.j,  4.+0.j]]) 
1

Summarize


Related articles: