Numpy initialization for python data analysis

The following all use numpy's standard "import numpy as np" 1. numpy
is a multi-dimensional container for homogeneous data, and homogeneous means the same data type
2. Initialization:

 2.1
 np.arange([start,] end [, step])#与list的range相似
 >>> np.arange(10)  
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])  
>>> np.arange(1, 10, 2)  
array([1, 3, 5, 7, 9])  

2.2
np.zeros(tupleA)# Generate a matrix of tupleA dimension, and the initial value is all 0

>>> np.zeros((4))  
array([ 0.,  0.,  0.,  0.])  
>>> np.zeros((4,2))  
array([[ 0.,  0.],  
       [ 0.,  0.],  
       [ 0.,  0.],  
       [ 0.,  0.]])  

2.3
np.ones(tupleA)# is similar to the above, except that the initialization is all 1

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

2.4
np.empty(tupleA)# is similar to the above, but the initialization value is undefined (not 0 as you think!!!)

>>> np.empty((4))  
array([  1.73154357e-316,   4.71627160e-317,   0.00000000e+000,  
         4.94065646e-324])  
>>> np.empty((3,2))  
array([[  0.00000000e+000,   0.00000000e+000],  
       [  6.94647584e-310,   6.94647586e-310],  
       [  6.94647586e-310,   6.94647586e-310],  

2.5
np.array(listA)# Convert listA to np, listA is just a general term, as long as it is serialized, it can also be other np

>>> np.array([[1, 2, 3], [4, 3, 2]])  
array([[1, 2, 3],  
       [4, 3, 2]])  
>>> npA = np.array([[1, 2, 3], [4, 3, 2]])  
>>> npA  
array([[1, 2, 3],  
       [4, 3, 2]])  
>>> npB = np.array([[1, 2, 3], [4, 3, 2.0]])  
>>> npB  
array([[ 1.,  2.,  3.],  
       [ 4.,  3.,  2.]])  
  np.array会自动找到最适合listA数据类型转给np:  
>>> npA.dtype  
dtype('int64')  
>>> npB.dtype  
dtype('float64')  

But in fact, np will be defaulted to float64 without special instructions during initialization, such as the first four.

2.6
其他:ones_like(npA);zeros_like(npA);empty_like(npA)

>>> npB = np.array([[1, 2, 3], [4, 3, 2.0]])  
>>> np.ones_like(npB)  
array([[ 1.,  1.,  1.],  
       [ 1.,  1.,  1.]])  
>>> np.zeros_like(npB)  
array([[ 0.,  0.,  0.],  
       [ 0.,  0.,  0.]])  
>>> np.empty_like(npB)  
array([[  0.00000000e+000,   0.00000000e+000,   1.56491143e-316],  
       [  6.94647850e-310,   6.94635322e-310,   1.72361006e-316]])  
>>> np.identity(3)  
array([[ 1.,  0.,  0.],  
       [ 0.,  1.,  0.],  
       [ 0.,  0.,  1.]])  
>>> np.eye(3, k = -1)#变化k的值试试看  
array([[ 0.,  0.,  0.],  
       [ 1.,  0.,  0.],  
       [ 0.,  1.,  0.]])  

Reprinted from: https://blog.csdn.net/u010668907/article/details/51429540

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325654031&siteId=291194637