numpy 代表性语句

numpy 代表性语句,第1张

  1. a = np.array([1,2]) a.size : Number of elements in the array. Equal to np.prod(a.shape), i.e., the product of the array’s dimensions.
np.zeros((2,2))
np.ones((1,2))
c = np.full((2,2), 7) # Create a full of constant array
d = np.eye(2)        # Create a 2x2 identity matrix

# Slicing: Similar to Python lists, numpy arrays can be sliced. 
# Since arrays may be multidimensional, 
# you must specify a slice for each dimension of the array:
a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
b = a[:2, 1:3]
# A slice of an array is a view into the same data,!!!!
# so modifying it will modify 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
row_r3 = a[[1], :]  # Rank 2 view of the second row of a

col_r1 = a[:, 1]
col_r2 = a[:, 1:2]


# WOW 此时为什么不是切片了呢,因为已经构成了新的
# 索引中一旦有了 [], 就不再是引用了
a = np.array([[1,2], [3, 4], [5, 6]])
print(a[[0, 1, 2], [0, 1, 0]])
print(np.array([a[0, 0], a[1, 1], a[2, 0]]))

# One useful trick with integer array indexing is 
# selecting or mutating one element from each row of a matrix:
a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
b = np.array([0, 2, 0, 1])
print(a[np.arange(4), b])
a[np.arange(4), b] += 10 # 我了个去

bool_idx = (a > 2)
print(a[bool_idx])
print(a[a > 2])

z = np.array([1, 2], dtype=np.int64)

x/y # 点除
x*y # 点乘
x.dot(y) # 内积(点乘加起来) 跟 @ 一样。二维数组:矩阵积;矩阵乘法。

np.sum(x, axis=1)

v.T # 转置。

vv = np.tile(v, (4, 1))  # Stack 4 copies of v on top of each other
# 后面的1是指重复几次(在最低维)

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

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/731012.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-27
下一篇2022-04-27

发表评论

登录后才能评论

评论列表(0条)

    保存