栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【Python】Numpy Learning Notes

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Python】Numpy Learning Notes

文章目录

Brief Introduction to NumpyWhat is an array in Numpy?Differences between a Python list & Numpy arraySome basic attributes of Numpy arrayArrays Creation

array( )Typical errors caused by array( )arange( ) & reshape( )linspace( )random.randint( )zeros( ) & ones( )eye( ) Print Arrays to the ScreenBasic Operations

Addition & Substraction & Scalar Multiplication & Logic JudgmentMatrix MultiplicationUnary Operations with Method( )

Sum( )& Cumulative Sum( )Max( ) & Min( ) Universal function

exp( ) & sqrt( ) & add( ) Indexing & Slicing & Iterating

1-D Arrayn-D Arrays Shape Manipulation

Changing the Shape of An ArrayStacking together different arrays Splitting one array into several smaller onesCopies and Views

No copies at allCorrect way to copy an array Advanced indexing and index tricks¶

Indexing with Arrays of IndicesIndexing with Boolean ArraysIndexing with ix_ function(Cartesian product) References

Brief Introduction to Numpy

NumPy (Numerical Python) is an open source Python library that’s used in almost every field of science and engineering. It’s the universal standard for working with numerical data in Python, and it’s at the core of the scientific Python and PyData ecosystems. NumPy users include everyone from beginning coders to experienced researchers doing state-of-the-art scientific and industrial research and development. The NumPy API is used extensively in Pandas, SciPy,Matplotlib, scikit-learn, scikit-image and most other data science and scientific Python packages.
The NumPy library contains multidimensional array and matrix data structures (you’ll find more information about this in later sections). It provides ndarray, a homogeneous n-dimensional array object, with methods to efficiently operate on it. NumPy can be used to perform a wide variety of mathematical operations on arrays. It adds powerful data structures to Python that guarantee efficient calculations with arrays and matrices and it supplies an enormous library of high-level mathematical functions that operate on these arrays and matrices.

What is an array in Numpy?

An array is a central data structure of the NumPy library. An array is a grid of values and it contains information about the raw data, how to locate an element, and how to interpret an element. It has a grid of elements that can be indexed in various ways. The elements are all of the same type, referred to as the array dtype.
An array can be indexed by a tuple of nonnegative integers, by booleans, by another array, or by integers. The rank of the array is the number of dimensions. The shape of the array is a tuple of integers giving the size of the array along each dimension.

You might occasionally hear an array referred to as a “ndarray,” which is shorthand for “N-dimensional array.” An N-dimensional array is simply an array with any number of dimensions. You might also hear 1-D, or one-dimensional array, 2-D, or two-dimensional array, and so on. The NumPy ndarray class is used to represent both matrices and vectors. A vector is an array with a single dimension (there’s no difference between row and column vectors), while a matrix refers to an array with two dimensions. For 3-D or higher dimensional arrays, the term tensor is also commonly used.

Differences between a Python list & Numpy array

NumPy gives you an enormous range of fast and efficient ways of creating arrays and manipulating numerical data inside them. While a Python list can contain different data types within a single list, all of the elements in a NumPy array should be homogeneous. The mathematical operations that are meant to be performed on arrays would be extremely inefficient if the arrays weren’t homogeneous.
NumPy arrays are faster and more compact than Python lists. An array consumes less memory and is convenient to use. NumPy uses much less memory to store data and it provides a mechanism of specifying the data types. This allows the code to be optimized even further.

Some basic attributes of Numpy array
import numpy as np
a = np.arange(1,13).reshape(2,6)
print('Original Matrix:n{}'.format(a))

print('ntype(a):n{}'.format(type(a)))       #return the type of a -> 'numpy.ndarray'
print('na.ndim:n{}'.format(a.ndim))         #return a number of axes (dimensions) of the array
print('na.shape:n{}'.format(a.shape))       #return a tuple of integers indicating the size of the array in each dimension
print('na.size:n{}'.format(a.size))         #return the total number of elements of the array
print('na.dtype:n{}'.format(a.dtype))       #return the type of elements of the array
print('na.itemsize:n{}'.format(a.itemsize)) #return the the size in bytes of each element of the array

Original Matrix:
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]

type(a):

a.ndim:
2

a.shape:
(2, 6)

a.size:
12

a.dtype:
int32

a.itemsize:
4

Arrays Creation array( )
import numpy as np    
a = np.array([1,2,3,4])  #array() helps to transform a Python list to Numpy arrary
b = np.array([[2.1,3.4],[3.7,4.2]])
c = np.array([1,2,3],dtype=complex) #'dtype' can specify the type of the elements
print('An array with int type elements:n{}'.format(a))
print('nAn array with float type elements:n{}'.format(b))
print('nAn array with complex type elements:n{}'.format(c))

An array with int type elements:
[1 2 3 4]

An array with float type elements:
[[2.1 3.4]
[3.7 4.2]]

An array with complex type elements:
[1.+0.j 2.+0.j 3.+0.j]

Typical errors caused by array( )
a = np.array(1,2,3,4)   #Wrong Version
a = np.array([1,2,3,4]) #Right Version

b = np.array([1.6,13.4],[2.1,3.6])   #Wrong Version
b = np.array([[1.6,13.4],[2.1,3.6]]) #Right Version
TypeError                                 Traceback (most recent call last)

~AppDataLocalTemp/ipykernel_15416/3711612825.py in 
----> 1 a = np.array(1,2,3,4)   #Wrong Version
      2 a = np.array([1,2,3,4]) #Right Version
      3 
      4 b = np.array([1.6,13.4],[2.1,3.6])   #Wrong Version
      5 b = np.array([[1.6,13.4],[2.1,3.6]]) #Correct Version
      
TypeError: array() takes from 1 to 2 positional arguments but 4 were given
arange( ) & reshape( )
a = np.arange(10,30,5)                #arange(start,end,step) => [start,end)
print('An array begins at 10 & ends up at 25 by the step of 5:n{}'.format(a))
b = np.arange(10,40,5).reshape(2,3)   #reshape((size of 0 axis,size of 1 axis))
print('nAn array begins at 10 & ends up at 35 by the step of 5 & reshape into a 2*3 Matrix:n{}'.format(b))
c = np.arange(15).reshape(3,5)
print('nAn array begins at 0 & ends up at 14 by the step of 1 & reshape into a 3*5 Matrix:n{}'.format(c))

An array begins at 10 & ends up at 25 by the step of 5:
[10 15 20 25]

An array begins at 10 & ends up at 35 by the step of 5 & reshape into a 2*3 Matrix:
[[10 15 20]
[25 30 35]]

An array begins at 0 & ends up at 14 by the step of 1 & reshape into a 3*5 Matrix:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]

linspace( )
#linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
a = np.linspace(0,10)         #Returns num(default value = 50) evenly spaced samples, calculated over the interval [start, stop].
print('Without assigning "num":n{}'.format(a))
b = np.linspace(0, 10, num=5) 
print("nAssign 'num' to 5:n{}".format(b))

Without assigning “num”:
[ 0. 0.20408163 0.40816327 0.6122449 0.81632653 1.02040816
1.2244898 1.42857143 1.63265306 1.83673469 2.04081633 2.24489796
2.44897959 2.65306122 2.85714286 3.06122449 3.26530612 3.46938776
3.67346939 3.87755102 4.08163265 4.28571429 4.48979592 4.69387755
4.89795918 5.10204082 5.30612245 5.51020408 5.71428571 5.91836735
6.12244898 6.32653061 6.53061224 6.73469388 6.93877551 7.14285714
7.34693878 7.55102041 7.75510204 7.95918367 8.16326531 8.36734694
8.57142857 8.7755102 8.97959184 9.18367347 9.3877551 9.59183673
9.79591837 10. ]

Assign ‘num’ to 5:
[ 0. 2.5 5. 7.5 10. ]

random.randint( )
a = np.random.randint(1,10,(2,5))  #random.randint(start,end,(size of 0 axis,size of 1 axis))
print('An 2*5 random array:n{}'.format(a))
b = np.random.randint(1,5,(4,2))   #random.randint creates a matrix filled with random value between [start,end)
print('nAn 4*2 random array:n{}'.format(a))

An 2*5 random array:
[[2 7 8 7 5]
[9 4 8 8 9]]

An 4*2 random array:
[[2 7 8 7 5]
[9 4 8 8 9]]

zeros( ) & ones( )
a = np.zeros((2,2))   #zeros(tuple)
print('An array filled with 0's:n{}'.format(a))
b = np.ones((2,5))    #ones(tuple)
print('nAn array filled with 1's:n{}'.format(b))

An array filled with 0’s:
[[0. 0.]
[0. 0.]]

An array filled with 1’s:
[[1. 1. 1. 1. 1.]
[1. 1. 1. 1. 1.]]

eye( )
a = np.eye(5)  #eye(size) => a identity matrix(normally square matrix)
print('An 5*5 identity array:n{}'.format(a))

An 5*5 identity array:
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]

Print Arrays to the Screen
a = np.arange(6) 
print('1-D:n{}n'.format(a))

b= np.arange(12).reshape((3,4))
print('2-D:n{}n'.format(b))

c = np.arange(24).reshape(2,2,3,2)
print('3-D:n{}n'.format(c))

a = np.arange(10000)
print(a)

b = np.arange(10000).reshape(100,100)
print(b)

1-D:
[0 1 2 3 4 5]

2-D:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]

3-D:
[[[[ 0 1]
[ 2 3]
[ 4 5]]

[[ 6 7]
[ 8 9]
[10 11]]]

[[[12 13]
[14 15]
[16 17]]

[[18 19]
[20 21]
[22 23]]]]

[ 0 1 2 … 9997 9998 9999]

[[ 0 1 2 … 97 98 99]
[ 100 101 102 … 197 198 199]
[ 200 201 202 … 297 298 299]

[9700 9701 9702 … 9797 9798 9799]
[9800 9801 9802 … 9897 9898 9899]
[9900 9901 9902 … 9997 9998 9999]]

Basic Operations Addition & Substraction & Scalar Multiplication & Logic Judgment
a = np.arange(6)
b = np.arange(2,8)
print('Original Matrix:n{}n{}n'.format(a,b))
print('Addition:n{}n'.format(a+b))
print('Substraction:n{}n'.format(a-b))
print('Scalar Multiplication:n{}'.format(a*10))
print(a**3)
print('nLogic Judgment:n{}'.format(a<3))

Original Matrix:
[0 1 2 3 4 5]
[2 3 4 5 6 7]

Addition:
[ 2 4 6 8 10 12]

Substraction:
[-2 -2 -2 -2 -2 -2]

Scalar Multiplication:
[ 0 10 20 30 40 50]
[ 0 1 8 27 64 125]

Logic Judgment:
[ True True True False False False]

Matrix Multiplication
a = np.arange(1,11).reshape(5,2)
b = np.arange(5,15).reshape(2,5)
print('Original Matrix A:n{}'.format(a))
print('Original Matrix B:n{}'.format(b))
print('nA*B:')
print(a@b)               #a@b is equal to a.dot(b)
print(a.dot(b))

Original Matrix A:
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]]
Original Matrix B:
[[ 5 6 7 8 9]
[10 11 12 13 14]]

A*B:
[[ 25 28 31 34 37]
[ 55 62 69 76 83]
[ 85 96 107 118 129]
[115 130 145 160 175]
[145 164 183 202 221]]
[[ 25 28 31 34 37]
[ 55 62 69 76 83]
[ 85 96 107 118 129]
[115 130 145 160 175]
[145 164 183 202 221]]

Unary Operations with Method( ) Sum( )& Cumulative Sum( )
a = np.random.randint(5,10,(3,5))
print('Original Matrix:n{}'.format(a))

print('nSum:')
print(a.sum())
print(a.sum(axis=0))    #sum of each column
print(a.sum(axis=1))    #sum of each row

print('nCumulative Sum:')
print(a.cumsum(axis=0)) #cumulative sum along each column
print(a.cumsum(axis=1)) #cumulative sum along each row

Original Matrix:
[[5 7 6 9 5]
[6 9 5 8 9]
[7 6 8 9 8]]

Sum:
107
[18 22 19 26 22]
[32 37 38]

Cumulative Sum:
[[ 5 7 6 9 5]
[11 16 11 17 14]
[18 22 19 26 22]]
[[ 5 12 18 27 32]
[ 6 15 20 28 37]
[ 7 13 21 30 38]]

Max( ) & Min( )
a = np.random.randint(10,20,(4,2))
print('Original Matrix:n{}'.format(a))

print('nMax:')
print(a.max())
print(a.max(axis=0))    #max of each column
print(a.max(axis=1))    #max of each row

print('nMin:')
print(a.min())
print(a.min(axis=0))    #min of each column
print(a.max(axis=1))    #min of each row

Original Matrix:
[[16 18]
[14 14]
[11 18]
[10 16]]

Max:
18
[16 18]
[18 14 18 16]

Min:
10
[10 14]
[18 14 18 16]

Universal function exp( ) & sqrt( ) & add( )
import numpy as np
a = np.arange(1,11).reshape(2,5)
b = np.arange(1,11).reshape(2,5)
print('Original Matrix:n{}'.format(a))
print('nExp():n{}'.format(np.exp(a)))
print('nSqrt():n{}'.format(np.sqrt(a)))
print('nAdd():n{}'.format(np.add(a,b)))

Original Matrix:
[[ 1 2 3 4 5]
[ 6 7 8 9 10]]

Exp():
[[2.71828183e+00 7.38905610e+00 2.00855369e+01 5.45981500e+01
1.48413159e+02]
[4.03428793e+02 1.09663316e+03 2.98095799e+03 8.10308393e+03
2.20264658e+04]]

Sqrt():
[[1. 1.41421356 1.73205081 2. 2.23606798]
[2.44948974 2.64575131 2.82842712 3. 3.16227766]]

Add():
[[ 2 4 6 8 10]
[12 14 16 18 20]]

Indexing & Slicing & Iterating 1-D Array
a = np.arange(10)**3
print('Original Matrix:n{}'.format(a))

print('na[2]:n{}'.format(a[2]))        #Indexing
print('na[:6:2]:n{}'.format(a[:6:2]))  #Slicing      a[start:end:step]

a[4::2] = 1000
print('nModified Matrix:n{}'.format(a))

print('nReversed Matrix:n{}'.format(a[::-1]))

Original Matrix:
[ 0 1 8 27 64 125 216 343 512 729]

a[2]:
8

a[:6:2]:
[ 0 8 64]

Modified Matrix:
[ 0 1 8 27 1000 125 1000 343 1000 729]

Reversed Matrix:
[ 729 1000 343 1000 125 1000 27 8 1 0]

n-D Arrays
a = np.random.randint(1,20,(4,5))
print('Original Matrix:n{}'.format(a))

print('na[3,4]:n{}'.format(a[3,4]))

print('na[1:3,2:]:n{}'.format(a[1:3,2:]))

print('na[:,0]:n{}'.format(a[:,0]))

print('na[-1]:n{}'.format(a[-1]))   # the last row. Equivalent to a[-1, :]

print('nIterating:')
for row in a:
    print(row)
    
for element in a.flat:   #a.flat
    print(element)

Original Matrix:
[[19 4 18 6 5]
[ 4 16 18 4 10]
[18 4 17 11 6]
[ 7 18 12 6 16]]

a[3,4]:
16

a[1:3,2:]:
[[18 4 10]
[17 11 6]]

a[:,0]:
[19 4 18 7]

a[-1]:
[ 7 18 12 6 16]

Iterating:
[19 4 18 6 5]
[ 4 16 18 4 10]
[18 4 17 11 6]
[ 7 18 12 6 16]
19
4
18
6
5
4
16
18
4
10
18
4
17
11
6
7
18
12
6
16

Shape Manipulation Changing the Shape of An Array
a = np.random.randint(1,10,(3,4))
print('Original Matrix:n{}'.format(a))

print('na.shape:n{}'.format(a.shape))

print('na.ravel():n{}'.format(a.ravel()))  #a.ravel() does not change the original matrix
print('nCurrent a:n{}'.format(a))

print('na.reshape(4,3):n{}'.format(a.reshape(4,3)))  #a.reshape() does not change the original matrix
print('nCurrent a:n{}'.format(a))

#If a dimension is given as -1 in a reshaping operation, the other dimensions are automatically calculated
print('na.reshape(4,-1):n{}'.format(a.reshape(4,-1))) 
print('nCurrent a:n{}'.format(a))


print('na.T:n{}'.format(a.T))  #a.T() does not change the original matrix
print('nCurrent a:n{}'.format(a))

print('na.resize():n{}'.format(a.resize((2,6))))  #a.resize() does change the original matrix
print('nCurrent a:n{}'.format(a))

Original Matrix:
[[2 5 6 7]
[3 5 1 3]
[7 3 2 3]]

a.shape:
(3, 4)

a.ravel():
[2 5 6 7 3 5 1 3 7 3 2 3]

Current a:
[[2 5 6 7]
[3 5 1 3]
[7 3 2 3]]

a.reshape(4,3):
[[2 5 6]
[7 3 5]
[1 3 7]
[3 2 3]]

Current a:
[[2 5 6 7]
[3 5 1 3]
[7 3 2 3]]

a.reshape(4,-1):
[[2 5 6]
[7 3 5]
[1 3 7]
[3 2 3]]

Current a:
[[2 5 6 7]
[3 5 1 3]
[7 3 2 3]]

a.T:
[[2 3 7]
[5 5 3]
[6 1 2]
[7 3 3]]

Current a:
[[2 5 6 7]
[3 5 1 3]
[7 3 2 3]]

a.resize():
None

Current a:
[[2 5 6 7 3 5]
[1 3 7 3 2 3]]

Stacking together different arrays
A= np.arange(1,9).reshape(2,4)
print('Original Matrix A:n{}'.format(A))

B= np.arange(5,13).reshape(2,4)
print('nOriginal Matrix B:n{}'.format(B))

print('nvstack((A,B):n{}'.format(np.vstack((A,B))))

print('nhstack((A,B):n{}'.format(np.hstack((A,B))))

Original Matrix A:
[[1 2 3 4]
[5 6 7 8]]

Original Matrix B:
[[ 5 6 7 8]
[ 9 10 11 12]]

vstack((A,B):
[[ 1 2 3 4]
[ 5 6 7 8]
[ 5 6 7 8]
[ 9 10 11 12]]

hstack((A,B):
[[ 1 2 3 4 5 6 7 8]
[ 5 6 7 8 9 10 11 12]]

Splitting one array into several smaller ones
a = np.arange(1,21).reshape(2,10)
print('Original Matrix:n{}'.format(a))

print('nnp.hsplit(a,5):n{}'.format(np.hsplit(a,5))) #split a into 5 arrays with the same size
print('Current a:n{}'.format(a))

print('nnp.hsplit(a,(2,5)):n{}'.format(np.hsplit(a,(2,5))))  #split a into 3 arrays,the column index of middle one is col2 to col5

Original Matrix:
[[ 1 2 3 4 5 6 7 8 9 10]
[11 12 13 14 15 16 17 18 19 20]]

np.hsplit(a,5):
[array([[ 1, 2],
[11, 12]]), array([[ 3, 4],
[13, 14]]), array([[ 5, 6],
[15, 16]]), array([[ 7, 8],
[17, 18]]), array([[ 9, 10],
[19, 20]])]
Current a:
[[ 1 2 3 4 5 6 7 8 9 10]
[11 12 13 14 15 16 17 18 19 20]]

np.hsplit(a,(2,5)):
[array([[ 1, 2],
[11, 12]]), array([[ 3, 4, 5],
[13, 14, 15]]), array([[ 6, 7, 8, 9, 10],
[16, 17, 18, 19, 20]])]

Copies and Views No copies at all
a = np.arange(1,13).reshape(2,6)
print('Original Matrix:n{}'.format(a))

print('nb = a & modify b:')         #Wrong way to copy an array
b = a
b[:,2] = 0
print('Current A:n{}'.format(a))
print('The result shows that B is exactly the same as A,or A & B is not independentn')

print('nb = a[:,:] & modify b:')   #Slicing is also a wrong way to copy an array which is different from list slicing
a = np.arange(1,13).reshape(2,6)
print('Original A:n{}'.format(a))
b = a[:,:]
print('Current B:n{}'.format(b))

b[:,2] = 0                        # a also changes while b is modified
print('Current A:n{}'.format(a))
print('Current B:n{}'.format(b))

b = 0                             #b becomes a number after this assignment
print('Current A:n{}'.format(a))
print('Current B:n{}'.format(b))
print('The result shows that B is exactly the same as A,or A & B is not independentn')

Original Matrix:
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]

b = a & modify b:
Current A:
[[ 1 2 0 4 5 6]
[ 7 8 0 10 11 12]]
The result shows that B is exactly the same as A,or A & B is not independent


b = a[:,:] & modify b:
Original A:
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]
Current B:
[[ 1 2 3 4 5 6]
[ 7 8 9 10 11 12]]
Current A:
[[ 1 2 0 4 5 6]
[ 7 8 0 10 11 12]]
Current B:
[[ 1 2 0 4 5 6]
[ 7 8 0 10 11 12]]
Current A:
[[ 1 2 0 4 5 6]
[ 7 8 0 10 11 12]]
Current B:
0
The result shows that B is exactly the same as A,or A & B is not independent

Correct way to copy an array
a = np.random.randint(1,10,(2,6))
print('Original Matrix:n{}'.format(a))

print('nb = a.copy():')
b = a.copy()
print('Current b:n{}'.format(a))
print('nmodify b:')
b[:,:] = 100
print('Current a:n{}'.format(a))
print('Current b:n{}'.format(b))

Original Matrix:
[[2 9 2 9 7 2]
[4 7 9 7 5 7]]

b = a.copy():
Current b:
[[2 9 2 9 7 2]
[4 7 9 7 5 7]]

modify b:
Current a:
[[2 9 2 9 7 2]
[4 7 9 7 5 7]]
Current b:
[[100 100 100 100 100 100]
[100 100 100 100 100 100]]

Advanced indexing and index tricks¶ Indexing with Arrays of Indices
a = np.arange(1,13)**3
print('Original Matrix a:n{}'.format(a))
b = np.arange(2,8)
print('nIndex Matrix b:n{}'.format(b))
print('na[b]:n{}'.format(a[b]))

print('nIndex Matrix c:n{}'.format(c))
c = np.array([[2,4],[3,6],[7,8]])
print('na[c]:n{}'.format(a[c]))

Original Matrix a:
[ 1 8 27 64 125 216 343 512 729 1000 1331 1728]

Index Matrix b:
[2 3 4 5 6 7]

a[b]:
[ 27 64 125 216 343 512]

Index Matrix c:
[[2 4]
[3 6]
[7 8]]

a[c]:
[[ 27 125]
[ 64 343]
[512 729]]

palette = np.array([[0, 0, 0],         # black
                    [255, 0, 0],       # red
                    [0, 255, 0],       # green
                    [0, 0, 255],       # blue
                    [255, 255, 255]])  # white
print('Palette:n{}'.format(palette))
image = np.array([[0,2,3],
                  [1,2,1]])
print('nPalette[image]:n{}'.format(palette[image]))

Palette:
[[ 0 0 0]
[255 0 0]
[ 0 255 0]
[ 0 0 255]
[255 255 255]]

Palette[image]:
[[[ 0 0 0]
[ 0 255 0]
[ 0 0 255]]

[[255 0 0]
[ 0 255 0]
[255 0 0]]]

Indexing with Boolean Arrays
a = np.arange(10).reshape(2,5)
print('Original Matrix a:n{}'.format(a))
b = a<3
print('nb = a<3 Matrix b:n{}nnMatrix a[b]:n{}'.format(b,a[b]))

Original Matrix a:
[[0 1 2 3 4]
[5 6 7 8 9]]

b = a<3 Matrix b:
[[ True True True False False]
[False False False False False]]

Matrix a[b]:
[0 1 2]

a = np.random.randint(1,10,(2,5))
print('Original Matrix a:n{}'.format(a))
b = a<5
a[b] = 0
print('nAssign all elements <5 to 0:n{}'.format(a))

Original Matrix a:
[[7 6 9 6 3]
[2 6 1 3 4]]

Assign all elements <5 to 0:
[[7 6 9 6 0]
[0 6 0 0 0]]

a = np.arange(1,13).reshape(3,4)
print('Original Matrix a:n{}'.format(a))
b1 = np.array([False,True,True])           # first dim selection
b2 = np.array([True,True,False,False])    # second dim selection
print('nOriginal Matrix b1:n{}'.format(b1))
print('nOriginal Matrix b2:n{}'.format(b2))

print('na[b1,:]:n{}'.format(a[b1,:]))
print('na[b1]:n{}'.format(a[b1]))
print('na[:,b2]:n{}'.format(a[:,b2]))

print('na[b1,b2]:n{}'.format(a[b1,b2]))    # take the diagonal elements of the matrix slice

Original Matrix a:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]

Original Matrix b1:
[False True True]

Original Matrix b2:
[ True True False False]

a[b1,:]:
[[ 5 6 7 8]
[ 9 10 11 12]]

a[b1]:
[[ 5 6 7 8]
[ 9 10 11 12]]

a[:,b2]:
[[ 1 2]
[ 5 6]
[ 9 10]]

a[b1,b2]:
[ 5 10]

Indexing with ix_ function(Cartesian product)
a = np.arange(1,17).reshape(4,4)
print('Original Matrix:n{}'.format(a))
index = np.ix_([0,1],[2,3])                        #Cartesian product
print('nnp.ix_([0,1],[2,3]):n{}'.format(index))  #(0,2),(0,3),(1,2),(1,3)

print('nMatrix in Cartesian product index:n{}'.format(a[index]))

Original Matrix:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]

np.ix_([0,1],[2,3]):
(array([[0],
[1]]), array([[2, 3]]))

Matrix in Cartesian product index:
[[3 4]
[7 8]]

References

https://numpy.org/devdocs/user/quickstart.html
https://numpy.org/devdocs/user/absolute_beginners.html

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/714608.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号