python ndarray Array Object Characteristics and Instance Sharing
- 2021-12-05 06:31:46
- OfStack
1. numpy arrays are homogeneous arrays, that is, all elements must have the same data type.
2. ndarray Array 1 generally requires that all elements have the same data type, the subscript starts from 0, and the subscript of the last element is the array length minus 1.
Instances
import numpy as np
a = np.arange(0, 5, 1)
print(a)
b = np.arange(0, 10, 2)
print(b)
Expansion of knowledge points:
Defining Array
>>> import numpy as np
>>> m = np.array([[1,2,3], [2,3,4]]) # Defines a matrix, int64
>>> m
array([[1, 2, 3],
[2, 3, 4]])
>>> m = np.array([[1,2,3], [2,3,4]], dtype=np.float) # Definition Matrix ,float64
>>> m
array([[1., 2., 3.],
[2., 3., 4.]])
>>> print(m.dtype) # Data type
float64
>>> print(m.shape) # Shape 2 Row 3 Column
(2, 3)
>>> print(m.ndim) # Dimension
2
>>> print(m.size) # Number of elements
6
>>> print(type(m))
<class 'numpy.ndarray'>
There are also one special way to define a matrix
>>> m = np.zeros((2,2)) # All 0
>>> m
array([[0., 0.],
[0., 0.]])
>>> print(type(m)) # Also ndarray Type
<class 'numpy.ndarray'>
>>> m = np.ones((2,2,3)) # All 1
>>> m = np.full((3,4), 7) # All for 7
>>> np.eye(3) # Unity matrix
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
>>> np.arange(20).reshape(4,5) # Generate 1 A 4 Row 5 Array of columns
>>>
>>> np.random.random((2,3)) #[0,1) Random number
array([[0.51123127, 0.40852721, 0.26159126],
[0.42450279, 0.34763668, 0.06167501]])
>>> np.random.randint(1,10,(2,3)) #[1,10) Of random integers 2 Row 3 Column array
array([[5, 4, 9],
[2, 5, 7]])
>>> np.random.randn(2,3) # Normal random distribution
array([[-0.29538656, -0.50370707, -2.05627716],
[-1.50126655, 0.41884067, 0.67306605]])
>>> np.random.choice([10,20,30], (2,3)) # Random selection
array([[10, 20, 10],
[30, 10, 20]])
>>> np.random.beta(1,10,(2,3)) # Beta distribution
array([[0.01588963, 0.12635485, 0.22279098],
[0.08950147, 0.02244569, 0.00953366]])
Operational array
>>> from numpy import *
>>> a1=array([1,1,1]) # Definition 1 Array of numbers
>>> a2=array([2,2,2])
>>> a1+a2 # For addition of elements
array([3, 3, 3])
>>> a1*2 # Multiplication 1 Number
array([2, 2, 2])
##
>>> a1=np.array([1,2,3])
>>> a1
array([1, 2, 3])
>>> a1**3 # Indicates doing cubes for each number in an array
array([ 1, 8, 27])
## Value, notice that it is based on the 0 Is the starting coordinate, no matlab Different
>>> a1[1]
2
## Defining multidimensional arrays
>>> a3=np.array([[1,2,3],[4,5,6]])
>>> a3
array([[1, 2, 3],
[4, 5, 6]])
>>> a3[0] # Take out the diaphragm 1 Row data
array([1, 2, 3])
>>> a3[0,0] # No. 1 1 Line number 1 Data
1
>>> a3[0][0] # It can also be used in this way
1
>>> a3
array([[1, 2, 3],
[4, 5, 6]])
>>> a3.sum(axis=0) # Add by row, the columns remain unchanged
array([5, 7, 9])
>>> a3.sum(axis=1) # Add by column, row unchanged
array([ 6, 15])