1、定义一维数组
import numpy as np
my_array = np.array([1,2,2,3,4])
print (my_array)
=======================================================================
[1 2 2 3 4]
2、查看数组的大小形状
print (my_array.shape)
=======================================================================
(5,)
3、查看数组中各个元素
print (my_array[0])
print (my_array[1])
=======================================================================
1
2
4、修改数组的元素
my_array[0] = -1
print (my_array)
=======================================================================
[-1 2 2 3 4]
5、创建所有元素都为0的数组
my_new_array = np.zeros((5))
print (my_new_array)
=======================================================================
[0. 0. 0. 0. 0.]
6、创建所有元素都为1的数组
my_new_array = np.ones((5))
print (my_new_array)
=======================================================================
[1. 1. 1. 1. 1.]
7、创建随机值的数组
my_new_array = np.random.random((5))
print (my_new_array)
=======================================================================
[0.14329067 0.38828972 0.05740159 0.08703259 0.79184246]
8、定义二维数组
my_2d_array = np.zeros((2, 3))
print (my_2d_array)
=======================================================================
[[0. 0. 0.]
[0. 0. 0.]]
my_2d_array = np.ones((2, 3))
print (my_2d_array)
=======================================================================
[[1. 1. 1.]
[1. 1. 1.]]
my_array = np.array([[4, 5], [6, 1]])
print (my_array)
=======================================================================
[[4 5]
[6 1]]
9、查找数组中元素,索引从0开始
my_array = np.array([[4, 5], [6, 1]])
print (my_array[0][1])
=======================================================================
5
my_array_column_2 = my_array[:, 1]
print (my_array_column_2)
=======================================================================
[5 1]
10、数组的加减乘除运算
import numpy as np
a = np.array([[1.0, 2.0], [3.0, 4.0]])
b = np.array([[5.0, 6.0], [7.0, 8.0]])
sum = a + b
difference = a - b
product = a * b
quotient = a / b
print ("Sum = \n", sum )
print ("Difference = \n", difference )
print ("Product = \n", product )
print ("Quotient = \n", quotient )
=======================================================================
Sum =
[[ 6. 8.]
[10. 12.]]
Difference =
[[-4. -4.]
[-4. -4.]]
Product =
[[ 5. 12.]
[21. 32.]]
Quotient =
[[0.2 0.33333333]
[0.42857143 0.5 ]]
11、矩阵乘法
matrix_product = a.dot(b)
print ("Matrix Product = \n", matrix_product)
=======================================================================
Matrix Product =
[[19. 22.]
[43. 50.]]
12、创建数组的4种不同方法
a = np.array([0, 1, 2, 3, 4])
b = np.array((0, 1, 2, 3, 4))
c = np.arange(5)
d = np.linspace(0, 2*np.pi, 5)
print(a)
print(b)
print(c)
print(d)
print(a[3])
=======================================================================
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0. 1.57079633 3.14159265 4.71238898 6.28318531]
3
a = np.arange(25)
a = a.reshape((5, 5))
print(a)
=======================================================================
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
13、多维数组切片
a = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28 ,29, 30],
[31, 32, 33, 34, 35]])
print(a[0, 1:4])
print(a[1:4, 0])
print(a[::2,::2])
print(a[:, 1])
=======================================================================
[12 13 14]
[16 21 26]
[[11 13 15]
[21 23 25]
[31 33 35]]
[12 17 22 27 32]
14、数组属性
a = np.array([[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25],
[26, 27, 28 ,29, 30],
[31, 32, 33, 34, 35]])
print(type(a)) # 数组的类型
print(a.dtype) # 数组的数据类型
print(a.size) # 元素个数
print(a.shape) # 数组的形状
print(a.itemsize) # 每个项占用的字节数
print(a.ndim) # 数组的维数
print(a.nbytes) # 数组中的所有数据消耗掉的字节数
=======================================================================
<class 'numpy.ndarray'>
int32
25
(5, 5)
4
2
100
15、基本操作符
a = np.arange(25)
a = a.reshape((5, 5))
b = np.array([10, 62, 1, 14, 2, 56, 79, 2, 1, 45,
4, 92, 5, 55, 63, 43, 35, 6, 53, 24,
56, 3, 56, 44, 78])
b = b.reshape((5,5))
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a ** 2)
print(a < b)
print(a > b)
print(a.dot(b))
=======================================================================
[[ 10 63 3 17 6]
[ 61 85 9 9 54]
[ 14 103 17 68 77]
[ 58 51 23 71 43]
[ 76 24 78 67 102]]
[[-10 -61 1 -11 2]
[-51 -73 5 7 -36]
[ 6 -81 7 -42 -49]
[-28 -19 11 -35 -5]
[-36 18 -34 -21 -54]]
[[ 0 62 2 42 8]
[ 280 474 14 8 405]
[ 40 1012 60 715 882]
[ 645 560 102 954 456]
[1120 63 1232 1012 1872]]
[[0. 0.01612903 2. 0.21428571 2. ]
[0.08928571 0.07594937 3.5 8. 0.2 ]
[2.5 0.11956522 2.4 0.23636364 0.22222222]
[0.34883721 0.45714286 2.83333333 0.33962264 0.79166667]
[0.35714286 7. 0.39285714 0.52272727 0.30769231]]
[[ 0 1 4 9 16]
[ 25 36 49 64 81]
[100 121 144 169 196]
[225 256 289 324 361]
[400 441 484 529 576]]
[[ True True False True False]
[ True True False False True]
[False True False True True]
[ True True False True True]
[ True False True True True]]
[[False False True False True]
[False False True True False]
[ True False True False False]
[False False True False False]
[False True False False False]]
[[ 417 380 254 446 555]
[1262 1735 604 1281 1615]
[2107 3090 954 2116 2675]
[2952 4445 1304 2951 3735]
[3797 5800 1654 3786 4795]]
16、数组特殊运算符
# dot, sum, min, max, cumsum
a = np.arange(10)
print(a.sum()) # 元素求和
print(a.min()) # 找出最小元素
print(a.max()) # 找出最大元素
print(a.cumsum()) # 元素累加
=======================================================================
45
0
9
[ 0 1 3 6 10 15 21 28 36 45]
17、花式索引:获取数组中我们想要的特定元素
# Fancy indexing
a = np.arange(0, 100, 10)
indices = [1, 5, -1]
b = a[indices]
print(a)
print(b)
=======================================================================
[ 0 10 20 30 40 50 60 70 80 90]
[10 50 90]
18、布尔屏蔽:允许我们根据我们指定的条件检索数组中的元素。
# Boolean masking
import matplotlib.pyplot as plt
a = np.linspace(0, 2 * np.pi, 50)
b = np.sin(a)
plt.plot(a,b)
mask = b >= 0
plt.plot(a[mask], b[mask], 'bo') # 绘制b中大于零的元素
mask = (b >= 0) & (a <= np.pi / 2)
plt.plot(a[mask], b[mask], 'go')# 绘制b中大于零且a小于pi / 2的元素
plt.show()
=======================================================================
19、不完全索引:从多维数组的第一个维度获取索引或切片的一种方便方法
# Incomplete Indexing
a = np.arange(0, 100, 10)
b = a[:5]
c = a[a >= 50]
print(a)
print(b)
print(c)
=======================================================================
[ 0 10 20 30 40 50 60 70 80 90]
[ 0 10 20 30 40]
[50 60 70 80 90]
20、where() 函数:根据条件返回数组中的值。只需要把条件传递给它,它就会返回一个使得条件为真的元素的索引列表。
# Where
a = np.arange(0, 100, 10)
b = np.where(a < 50)
c = np.where(a >= 50)[0]
print(a)
print(b)
print(c)
=======================================================================
[ 0 10 20 30 40 50 60 70 80 90]
(array([0, 1, 2, 3, 4], dtype=int64),)
[5 6 7 8 9]
21、Numpy创建数组的函数
import numpy as np
a = np.zeros((2,2))
print(a)
b = np.ones((1,2))
print(b)
c = np.full((2,2), 7)
print(c)
d = np.eye(2)
print(d)
e = np.random.random((2,2))
print(e)
=======================================================================
[[0. 0.]
[0. 0.]]
[[1. 1.]]
[[7 7]
[7 7]]
[[1. 0.]
[0. 1.]]
[[0.39337359 0.14130749]
[0.85263329 0.05512763]]
22、Numpy几种索引数组的方法
切片(Slicing)
import numpy as np
# Create the following rank 2 array with shape (3, 4)
# [[ 1 2 3 4]
# [ 5 6 7 8]
# [ 9 10 11 12]]
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
print(a)
# Use slicing to pull out the subarray consisting of the first 2 rows
# and columns 1 and 2; b is the following array of shape (2, 2):
# [[2 3]
# [6 7]]
b = a[:2, 1:3]
print(b)
# A slice of an array is a view into the same data, so modifying it
# will modify the original array.
print(a[0, 1]) # Prints "2"
b[0, 0] = 77 # b[0, 0] is the same piece of data as a[0, 1]
print(a[0, 1]) # Prints "77"
=======================================================================
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
[[2 3]
[6 7]]
2
77
整数索引与切片索引混合使用
import numpy as np
# Create the following rank 2 array with shape (3, 4)
# [[ 1 2 3 4]
# [ 5 6 7 8]
# [ 9 10 11 12]]
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
# Two ways of accessing the data in the middle row of the array.
# Mixing integer indexing with slices yields an array of lower rank,
# while using only slices yields an array of the same rank as the
# original array:
row_r1 = a[1, :] # Rank 1 view of the second row of a
row_r2 = a[1:2, :] # Rank 2 view of the second row of a
print(row_r1, row_r1.shape) # Prints "[5 6 7 8] (4,)"
print(row_r2, row_r2.shape) # Prints "[[5 6 7 8]] (1, 4)"
# We can make the same distinction when accessing columns of an array:
col_r1 = a[:, 1]
col_r2 = a[:, 1:2]
print(col_r1, col_r1.shape) # Prints "[ 2 6 10] (3,)"
print(col_r2, col_r2.shape) # Prints "[[ 2]
# [ 6]
# [10]] (3, 1)"
=======================================================================
[5 6 7 8] (4,)
[[5 6 7 8]] (1, 4)
[ 2 6 10] (3,)
[[ 2]
[ 6]
[10]] (3, 1)
整数数组索引
import numpy as np
a = np.array([[1,2], [3, 4], [5, 6]])
print(a)
# An example of integer array indexing.
# The returned array will have shape (3,) and
print(a[[0, 1, 2], [0, 1, 0]]) # 表示行取a的0 1 2 行,列取a的0 1 0 列
# The above example of integer array indexing is equivalent to this:
print(np.array([a[0, 0], a[1, 1], a[2, 0]])) # Prints "[1 4 5]"
# When using integer array indexing, you can reuse the same
# element from the source array:
print(a[[0, 0], [1, 1]]) # Prints "[2 2]"
# Equivalent to the previous integer array indexing example
print(np.array([a[0, 1], a[0, 1]])) # Prints "[2 2]"
=======================================================================
[[1 2]
[3 4]
[5 6]]
[1 4 5]
[1 4 5]
[2 2]
[2 2]
整数数组索引的一个有用技巧是从矩阵的每一行中选择或改变一个元素
import numpy as np
# Create a new array from which we will select elements
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
print(a)
# Create an array of indices
b = np.array([0, 2, 0, 1])
# Select one element from each row of a using the indices in b
print(a[np.arange(4), b]) # Prints "[ 1 6 7 11]"
# Mutate one element from each row of a using the indices in b
a[np.arange(4), b] += 10
print(a)
=======================================================================
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
[ 1 6 7 11]
[[11 2 3]
[ 4 5 16]
[17 8 9]
[10 21 12]]
23、布尔数组索引
import numpy as np
a = np.array([[1,2], [3, 4], [5, 6]])
bool_idx = (a > 2) # Find the elements of a that are bigger than 2;
# this returns a numpy array of Booleans of the same
# shape as a, where each slot of bool_idx tells
# whether that element of a is > 2.
print(bool_idx) # Prints "[[False False]
# [ True True]
# [ True True]]"
# We use boolean array indexing to construct a rank 1 array
# consisting of the elements of a corresponding to the True values
# of bool_idx
print(a[bool_idx]) # Prints "[3 4 5 6]"
# We can do all of the above in a single concise statement:
print(a[a > 2]) # Prints "[3 4 5 6]"
=======================================================================
[[False False]
[ True True]
[ True True]]
[3 4 5 6]
[3 4 5 6]
24、数据类型
import numpy as np
x = np.array([1, 2]) # Let numpy choose the datatype
print(x.dtype) # Prints "int64"
x = np.array([1.0, 2.0]) # Let numpy choose the datatype
print(x.dtype) # Prints "float64"
x = np.array([1, 2], dtype=np.int64) # Force a particular datatype
print(x.dtype) # Prints "int64"
=======================================================================
int32
float64
int64
25、基本数学函数
import numpy as np
x = np.array([[1,2],[3,4]], dtype=np.float64)
y = np.array([[5,6],[7,8]], dtype=np.float64)
# Elementwise sum; both produce the array
print(x + y)
print(np.add(x, y))
# Elementwise difference; both produce the array
print(x - y)
print(np.subtract(x, y))
# Elementwise product; both produce the array
print(x * y)
print(np.multiply(x, y))
# Elementwise division; both produce the array
print(x / y)
print(np.divide(x, y))
# Elementwise square root; produces the array
print(np.sqrt(x))
=======================================================================
[[ 6. 8.]
[10. 12.]]
[[ 6. 8.]
[10. 12.]]
[[-4. -4.]
[-4. -4.]]
[[-4. -4.]
[-4. -4.]]
[[ 5. 12.]
[21. 32.]]
[[ 5. 12.]
[21. 32.]]
[[0.2 0.33333333]
[0.42857143 0.5 ]]
[[0.2 0.33333333]
[0.42857143 0.5 ]]
[[1. 1.41421356]
[1.73205081 2. ]]
import numpy as np
x = np.array([[1,2],[3,4]])
y = np.array([[5,6],[7,8]])
v = np.array([9,10])
w = np.array([11, 12])
# Inner product of vectors; both produce 219
print(v.dot(w))
print(np.dot(v, w))
# Matrix / vector product; both produce the rank 1 array [29 67]
print(x.dot(v))
print(np.dot(x, v))
# Matrix / matrix product; both produce the rank 2 array
# [[19 22]
# [43 50]]
print(x.dot(y))
print(np.dot(x, y))
=======================================================================
219
219
[29 67]
[29 67]
[[19 22]
[43 50]]
[[19 22]
[43 50]]
import numpy as np
x = np.array([[1,2],[3,4]])
print(np.sum(x)) # Compute sum of all elements; prints "10"
print(np.sum(x, axis=0)) # Compute sum of each column; prints "[4 6]"
print(np.sum(x, axis=1)) # Compute sum of each row; prints "[3 7]"
=======================================================================
10
[4 6]
[3 7]
import numpy as np
x = np.array([[1,2], [3,4]])
print(x) # Prints "[[1 2]
# [3 4]]"
print(x.T) # Prints "[[1 3]
# [2 4]]"
# Note that taking the transpose of a rank 1 array does nothing:
v = np.array([1,2,3])
print(v) # Prints "[1 2 3]"
print(v.T) # Prints "[1 2 3]"
=======================================================================
[[1 2]
[3 4]]
[[1 3]
[2 4]]
[1 2 3]
[1 2 3]
26、广播(Broadcasting):允许numpy在执行算术运算时使用不同形状的数组
将两个数组一起广播遵循以下规则:
1、如果数组不具有相同的rank,则将较低等级数组的形状添加1,直到两个形状具有相同的长度。
2、如果两个数组在维度上具有相同的大小,或者如果其中一个数组在该维度中的大小为1,则称这两个数组在维度上是兼容的。
3、如果数组在所有维度上兼容,则可以一起广播。
4、广播之后,每个数组的行为就好像它的形状等于两个输入数组的形状的元素最大值。
5、在一个数组的大小为1且另一个数组的大小大于1的任何维度中,第一个数组的行为就像沿着该维度复制一样
import numpy as np
# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = np.empty_like(x) # Create an empty matrix with the same shape as x
# Add the vector v to each row of the matrix x with an explicit loop
for i in range(4):
y[i, :] = x[i, :] + v
# Now y is the following
# [[ 2 2 4]
# [ 5 5 7]
# [ 8 8 10]
# [11 11 13]]
print(y)
=======================================================================
[[ 2 2 4]
[ 5 5 7]
[ 8 8 10]
[11 11 13]]
import numpy as np
# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
vv = np.tile(v, (4, 1)) # Stack 4 copies of v on top of each other
print(vv) # Prints "[[1 0 1]
# [1 0 1]
# [1 0 1]
# [1 0 1]]"
y = x + vv # Add x and vv elementwise
print(y) # Prints "[[ 2 2 4
# [ 5 5 7]
# [ 8 8 10]
# [11 11 13]]"
=======================================================================
[[1 0 1]
[1 0 1]
[1 0 1]
[1 0 1]]
[[ 2 2 4]
[ 5 5 7]
[ 8 8 10]
[11 11 13]]
import numpy as np
# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = x + v # Add v to each row of x using broadcasting
print(y) # Prints "[[ 2 2 4]
# [ 5 5 7]
# [ 8 8 10]
# [11 11 13]]"
=======================================================================
[[ 2 2 4]
[ 5 5 7]
[ 8 8 10]
[11 11 13]]
广播的应用
import numpy as np
# Compute outer product of vectors
v = np.array([1,2,3]) # v has shape (3,)
w = np.array([4,5]) # w has shape (2,)
# To compute an outer product, we first reshape v to be a column
# vector of shape (3, 1); we can then broadcast it against w to yield
# an output of shape (3, 2), which is the outer product of v and w:
# [[ 4 5]
# [ 8 10]
# [12 15]]
print(np.reshape(v, (3, 1)) * w)
# Add a vector to each row of a matrix
x = np.array([[1,2,3], [4,5,6]])
# x has shape (2, 3) and v has shape (3,) so they broadcast to (2, 3),
# giving the following matrix:
# [[2 4 6]
# [5 7 9]]
print(x + v)
# Add a vector to each column of a matrix
# x has shape (2, 3) and w has shape (2,).
# If we transpose x then it has shape (3, 2) and can be broadcast
# against w to yield a result of shape (3, 2); transposing this result
# yields the final result of shape (2, 3) which is the matrix x with
# the vector w added to each column. Gives the following matrix:
# [[ 5 6 7]
# [ 9 10 11]]
print((x.T + w).T)
# Another solution is to reshape w to be a column vector of shape (2, 1);
# we can then broadcast it directly against x to produce the same
# output.
print(x + np.reshape(w, (2, 1)))
# Multiply a matrix by a constant:
# x has shape (2, 3). Numpy treats scalars as arrays of shape ();
# these can be broadcast together to shape (2, 3), producing the
# following array:
# [[ 2 4 6]
# [ 8 10 12]]
print(x * 2)
=======================================================================
[[ 4 5]
[ 8 10]
[12 15]]
[[2 4 6]
[5 7 9]]
[[ 5 6 7]
[ 9 10 11]]
[[ 5 6 7]
[ 9 10 11]]
[[ 2 4 6]
[ 8 10 12]]