当前位置:网站首页>Common operations of ndarray in numpy
Common operations of ndarray in numpy
2022-07-26 20:41:00 【Yi Lanjun】
NumPy(Numerical Python) yes Python An open source numerical computing extension . This tool can be used to store and process large matrices , Than Python Its own nested list (nested list structure) The structure is much more efficient ( This structure can also be used to represent matrix (matrix)), Support a large number of dimension arrays and matrix operations , In addition, it also provides a large number of mathematical function libraries for array operation .
Numpy Medium main use ndarray To deal with it N Dimension group ,Numpy Most of the properties and methods in ndarray Service , So master Numpy in ndarray Common operations of are very necessary !
0 Numpy Basic knowledge of
NumPy The main object of is isomorphic multidimensional array . It's a list of elements ( It's usually numbers ), All types are the same , Indexed by nonnegative integer tuples . stay NumPy Called axis in dimension .
In the example shown below , Array has 2 Axes . The length of the first shaft is 2, The length of the second axis is 3.
[[ 1., 0., 0.],
[ 0., 1., 2.]]
1 ndarray Properties of
1.1 Output ndarray Common properties of
- ndarray.ndim : Axis of array ( dimension ) The number of . stay Python In the world , The number of dimensions is called rank.
- ndarray.shape : Dimension of array . This is a tuple of integers , Represents the size of the array in each dimension . For having n Row sum m Columns of the matrix ,shape It will be (n,m). therefore ,shape The length of a tuple is rank Or the number of dimensions ndim.
- ndarray.size : The total number of array elements . This is equal to shape The product of the elements of .
- ndarray.dtype : An object that describes the type of elements in an array . You can use standard Python Type create or specify dtype. in addition NumPy Provide its own type . for example numpy.int32、numpy.int16 and numpy.float64.
- ndarray.itemsize : The byte size of each element in the array . for example , Element is float64 Of an array of type itemsize by 8(=64/8), and complex32 Of an array of type itemsize by 4(=32/8). It's equal to ndarray.dtype.itemsize .
>>> import numpy as np
>>> a = np.arange(15).reshape(3, 5)
>>> a
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
>>> a.shape
(3, 5)
>>> a.ndim
2
>>> a.dtype.name
'int64'
>>> a.itemsize
8
>>> a.size
15
>>> type(a)
<type 'numpy.ndarray'>
>>> b = np.array([6, 7, 8])
>>> b
array([6, 7, 8])
>>> type(b)
<type 'numpy.ndarray'>
2 ndarray Data type of
In the same ndarray in , It stores the same type of data ,ndarray Common data types include :
| name | description |
|---|---|
| np.bool | Boolean type stored in one byte (True or False) |
| np.int8 | One byte size ,-128 to 127 |
| np.int16 | Integers ,-32768 to 32767 |
| np.int32 | Integers ,-2 Of 32 Power -1 To 2 Of 32 Power -1 |
| np.int64 | Integers ,-2 Of 63 Power -1 To 2 Of 63 Power -1 |
| np.uint8 | Unsigned integer ,0 to 255 |
| np.uint16 | Unsigned integer ,0 to 65535 |
| np.uint32 | Unsigned integer ,0 to 2^32-1 |
| np.uint64 | Unsigned integer ,0 to 2^64-1 |
| np.float16 | 16 Bit half precision floating-point number , The sign 1 position , Index 5 position , precision 10 position |
| np.float32 | 32 Bit single precision floating point number , The sign 1 position , Index 8 position , precision 23 position |
| np.float64 | 64 Bit double precision floating point number , The sign 1 position , Index 11 position , precision 52 position |
| np.object_ | python object type |
| np.string_ | String type |
| np.unicode_ | unicode type |
3 modify ndarray Shape and data type
3.1 View and modify ndarray The shape of the
## ndarray reshape operation
array_a = np.array([[1, 2, 3], [4, 5, 6]])
print(array_a, array_a.shape)
array_a_1 = array_a.reshape((3, 2))
print(array_a_1, array_a_1.shape)
# note: reshape Can't change ndarray The number of elements in , for example reshape For before (2,3),reshape For after (3,2)/(1,6)...
## ndarray Transposition
array_a_2 = array_a.T
print(array_a_2, array_a_2.shape)
## ndarray ravel operation : take ndarray Flattening
a.ravel() # returns the array, flattened
array([ 1, 2, 3, 4, 5, 6 ])
Output :
[[1 2 3]
[4 5 6]] (2, 3)
[[1 2]
[3 4]
[5 6]] (3, 2)
[[1 4]
[2 5]
[3 6]] (3, 2)
3.2 View and modify ndarray Data type of
astype(dtype[, order, casting, subok, copy]): modify ndarray Data types in . Pass in the data type to be modified , Other keyword parameters can be ignored .
array_a = np.array([[1, 2, 3], [4, 5, 6]])
print(array_a, array_a.dtype)
array_a_1 = array_a.astype(np.int64)
print(array_a_1, array_a_1.dtype)
Output :
[[1 2 3]
[4 5 6]] int32
[[1 2 3]
[4 5 6]] int64
4 ndarray Array creation
NumPy Mainly through np.array() Function to create ndarray Array .
>>> 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')
You can also explicitly specify the type of array 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]])
You can also use np.random.random Function to create random ndarray Array .
>>> a = np.random.random((2,3))
>>> a
array([[ 0.18626021, 0.34556073, 0.39676747],
[ 0.53881673, 0.41919451, 0.6852195 ]])
Usually , The elements of the array are initially unknown , But its size is known . therefore ,NumPy Several functions are provided to Create an array with initial placeholder content . This reduces the need for array growth , Because the operation of array growth costs a lot .
function zeros Create a by 0 Array of components , function ones Create a complete array , function empty Create an array , Its initial content is random , Depends on the state of the memory . By default , Of the array created dtype yes float64 Type of .
>>> 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]])
To create an array of numbers ,NumPy Provides a similar to range Function of , This function returns an array instead of a list .
>>> 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])
5 ndarray Common operations of arrays
Unlike many matrix languages , Product operator * stay NumPy Operation by element in array . Matrix products can be used @ Operator ( stay python> = 3.5 in ) or dot Function or method execution :
>>> A = np.array( [[1,1],
... [0,1]] )
>>> B = np.array( [[2,0],
... [3,4]] )
>>> A * B # elementwise product
array([[2, 0],
[0, 4]])
>>> A @ B # matrix product
array([[5, 4],
[3, 4]])
>>> A.dot(B) # another matrix product
array([[5, 4],
[3, 4]])
Some operations ( for example += and *=) The matrix array being manipulated will be changed more directly without creating a new matrix array .
>>> a = np.ones((2,3), dtype=int)
>>> b = np.random.random((2,3))
>>> a *= 3
>>> a
array([[3, 3, 3],
[3, 3, 3]])
>>> b += a
>>> b
array([[ 3.417022 , 3.72032449, 3.00011437],
[ 3.30233257, 3.14675589, 3.09233859]])
>>> a += b # b is not automatically converted to integer type
Traceback (most recent call last):
...
TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('int64') with casting rule 'same_kind'
When operating with different types of arrays , The type of the result array corresponds to a more general or precise array ( It's called the behavior of upward conversion ).
>>> a = np.ones(3, dtype=np.int32)
>>> b = np.linspace(0,pi,3)
>>> b.dtype.name
'float64'
>>> c = a+b
>>> c
array([ 1. , 2.57079633, 4.14159265])
>>> c.dtype.name
'float64'
>>> d = np.exp(c*1j)
>>> d
array([ 0.54030231+0.84147098j, -0.84147098+0.54030231j,
-0.54030231-0.84147098j])
>>> d.dtype.name
'complex128'
Many unary operations , For example, calculate the sum of all elements in the array , Are as ndarray Class implementation of the method .
>>> a = np.random.random((2,3))
>>> a
array([[ 0.18626021, 0.34556073, 0.39676747],
[ 0.53881673, 0.41919451, 0.6852195 ]])
>>> a.sum()
2.5718191614547998
>>> a.min()
0.1862602113776709
>>> a.max()
0.6852195003967595
By default , These operations apply to arrays , Just like it's a list of numbers , Whatever its shape . however , By designation axis Parameters , You can apply operations along the specified axis of the array :
>>> b = np.arange(12).reshape(3,4)
>>> b
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>>
>>> b.sum(axis=0) # Calculate the sum of each column
array([12, 15, 18, 21])
>>>
>>> b.min(axis=1) # Calculate the sum of each line
array([0, 4, 8])
>>>
>>> b.cumsum(axis=1) # cumulative sum along each row
array([[ 0, 1, 3, 6],
[ 4, 9, 15, 22],
[ 8, 17, 27, 38]])
explain : Take the first act ,0=0,1=1+0,3=2+1+0,6=3+2+1+0
6 ndarray Index of array 、 Slicing and iteration
A one-dimensional The array can be indexed 、 Slicing and iterative operations , Like lists and other Python The sequence type is the same .
>>> 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 0 To 6 The location of , Every other one is set to -1000
>>> a
array([-1000, 1, -1000, 27, -1000, 125, fan 216, 343, 512, 729])
>>> a[ : :-1] # take a reverse
array([ 729, 512, 343, 216, 125, -1000, 27, -1000, 1, -1000])
Multidimensional Each axis of the array can have an index . These indexes are marked with commas Separated tuples give :
>>> b
array([[ 0, 1, 2, 3],
[10, 11, 12, 13],
[20, 21, 22, 23],
[30, 31, 32, 33],
[40, 41, 42, 43]])
>>> b[2,3]
23
>>> b[0:5, 1] # each row in the second column of b
array([ 1, 11, 21, 31, 41])
>>> b[ : ,1] # equivalent to the previous example
array([ 1, 11, 21, 31, 41])
>>> b[1:3, : ] # each column in the second and third row of b
array([[10, 11, 12, 13],
[20, 21, 22, 23]])
>>> b[-1] # the last row. Equivalent to b[-1,:]
array([40, 41, 42, 43])
7 ndarray Stack of arrays 、 Split
Several arrays can be stacked together along different axes , for example :np.vstack() Functions and np.hstack() function
>>> 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.]])
column_stack() Function will 1D Stack arrays as columns to 2D Array .
>>> from numpy import newaxis
>>> a = np.array([4.,2.])
>>> b = np.array([3.,8.])
>>> np.column_stack((a,b)) # returns a 2D array
array([[ 4., 3.],
[ 2., 8.]])
>>> np.hstack((a,b)) # the result is different
array([ 4., 2., 3., 8.])
>>> a[:,newaxis] # this allows to have a 2D columns vector
array([[ 4.],
[ 2.]])
>>> np.column_stack((a[:,newaxis],b[:,newaxis]))
array([[ 4., 3.],
[ 2., 8.]])
>>> np.hstack((a[:,newaxis],b[:,newaxis])) # the result is the same
array([[ 4., 3.],
[ 2., 8.]])
Use hsplit(), You can split the array along its horizontal axis , The method is to specify the number of arrays with equal shapes to be returned , Or specify the column that should be split after it :
Empathy , Use vsplit(), You can split the array along its vertical axis , Method is the same as above. .
################### np.hsplit ###################
>>> a = np.floor(10*np.random.random((2,12)))
>>> a
array([[ 9., 5., 6., 3., 6., 8., 0., 7., 9., 7., 2., 7.],
[ 1., 4., 9., 2., 2., 1., 0., 6., 2., 2., 4., 0.]])
>>> np.hsplit(a,3) # Split a into 3
[array([[ 9., 5., 6., 3.],
[ 1., 4., 9., 2.]]), array([[ 6., 8., 0., 7.],
[ 2., 1., 0., 6.]]), array([[ 9., 7., 2., 7.],
[ 2., 2., 4., 0.]])]
>>> np.hsplit(a,(3,4)) # Split a after the third and the fourth column
[array([[ 9., 5., 6.],
[ 1., 4., 9.]]), array([[ 3.],
[ 2.]]), array([[ 6., 8., 0., 7., 9., 7., 2., 7.],
[ 2., 1., 0., 6., 2., 2., 4., 0.]])]
>>> x = np.arange(8.0).reshape(2, 2, 2)
>>> x
array([[[0., 1.],
[2., 3.]],
[[4., 5.],
[6., 7.]]])
################### np.vsplit ###################
>>> np.vsplit(x, 2)
[array([[[0., 1.],
[2., 3.]]]), array([[[4., 5.],
[6., 7.]]])]
边栏推荐
- How to assemble a registry?
- 如何组装一个注册中心?
- Applied materials announced that it would acquire international electric with us $2.2 billion in cash
- Where are the single dogs in the evening of 5.20?
- 韩国计划每年砸1万亿韩元,研发半导体材料及设备
- Fitting the new direction of curriculum standards, ape guidance, creating a characteristic new concept content system
- Houdini 求中点,点连成线
- APP自动化测试框架搭建(八)--ATX Server2多设备集群环境搭建
- NVIDIA Canvas 初体验~
- QT驾校科目考试系统——从实现到发布
猜你喜欢
随机推荐
BGP的路由黑洞和防环
gospel! Wechat personal official account can be renamed!
Correct the classpath of your application so that it contains compatible versions of the classes com
BGP routing black hole and anti ring
Do employees have to compensate the company for losses when they resign? The 34 year old captain resigned and was claimed 10.66 million yuan by the company
数字化工厂有哪些关键技术
BUU刷题记2
Quick start to connection pooling
一文读懂 Kubernetes的四种服务类型!
Bean injection and lifecycle
Basic configuration and aggregation of BGP
【Delphi】FMX Form的BorderStyles不同平台说明
Depthwiseseparableconvolution: depthwise convolution and pointwise convolution
美国应用材料公司宣布将以22亿美元现金收购国际电气
How to obtain Cu block partition information in HM and draw with MATLAB
Small scenes bring great improvement! Baidu PaddlePaddle easydl helps AI upgrade of manufacturing assembly line
实验6 BGP联邦综合实验
LCP 11. 期望个数统计
打字比赛圆满结束!
Pandonia spirit voxedit creation competition








![[experiment sharing] CCIE BGP routing black hole experiment]](/img/c8/7ccb879ad7c739d3573637fd14f4e1.png)
