Python numpy和matlab都是便捷灵活的科学计算语言,两者具有很多相似之处,但也有一些混淆的地方,这里假定你熟悉matlab,但不了解numpy,记录几个numpy实例:
1、Numpy数组索引指定开始和结束时,不包括结束,也即下面的b和c是一样的。
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
b = a[:2, 1:2]
c = a[:2, 1]
2、Numpy.ndarray切片的修改会引起原矩阵的修改,这与matlab不同。
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
b = a[:2, 1:3]
# [[2 3]
# [6 7]]
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"
3、numpy使用切片索引(例如1:2)不会产生降维,而使用整数索引(例如1)会产生降维。
import numpy as np
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
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)"
4、不同于matlab,numpy的转置对于1维数组的操作不发生变化。
v = np.array([1,2,3])
print(v) # Prints "[1 2 3]"
print(v.T) # Prints "[1 2 3]"
5、不同matlab对于矩阵预算要求大小一致,Numpy broadcasting直接支持操作(加减乘除等),要求前一个矩阵的最后一维度大小和待操作矩阵的大小相同。
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]