numpy二维数组切片
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)"
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)" 列的话和行也一样
numpy横列索引
a = np.array([[1,2], [3, 4], [5, 6]])
print(a[[0, 1, 2], [0, 1, 0]]) # Prints "[1 4 5]" 相当于输出a[0,0],a[1,1],a[2,0]
numpy点乘
y = np.array([[5,6],[7,8]])
w = np.array([11, 12])
# Inner product of vectors; both produce 219
print(v.dot(w))
print(np.dot(v, w))
numpy axis
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]"
numpy转置(.T表示转置)
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]]"
v = np.array([1,2,3])
print(v) # Prints "[1 2 3]"
print(v.T) # Prints "[1 2 3]"
numpy添加向量
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)
numpy叠加
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)) # v的四个叠加起来
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]]"
将两个数组加在一起遵循以下规则:
如果阵列不具有相同的秩,则用1s预先准备低秩阵列的形状,直到两个形状具有相同的长度。
如果这两个数组在维度上具有相同的大小,或者如果其中一个数组在该维度中具有大小1,则称为两个数组。
如果它们在所有维度上兼容,则可以将数组加在一起。
在加之后,每个数组表现得,好像它的尺寸等于两个输入数组的尺寸最大值。
在任何维度中,一个数组的大小为1,而另一个数组的大小大于1,第一个数组的行为就好像它是沿着该维度复制的。
numpy reshape
# 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) #np.reshape(a,(2,2))=a.reshape(2,2)就是将矩阵a变成2*2,但是元素并不变