参考资料:
- 黑马程序员相关课程
索引和切片
t1 = np.array([[i for i in range(j, j+4)] for j in range(5)])
print(t1[:, :])
# [[0 1 2 3]
# [1 2 3 4]
# [2 3 4 5]
# [3 4 5 6]
# [4 5 6 7]]
print(t1[[1, 2, 4]])
# [[1 2 3 4]
# [2 3 4 5]
# [4 5 6 7]]
print(t1[::2, ::2])
# [[0 2]
# [2 4]
# [4 6]]
# 中括号里的参数个数为数组的维数,每个参数为一个索引
数值的修改
# 利用数组中的bool索引
t1 = np.array([[i for i in range(j, j+4)] for j in range(5)])
print(t1 >= 3)
# [[False False False True]
# [False False True True]
# [False True True True]
# [ True True True True]
# [ True True True True]]
t1[t1 >= 3] = 3
print(t1)
# [[0 1 2 3]
# [1 2 3 3]
# [2 3 3 3]
# [3 3 3 3]
# [3 3 3 3]]
# where方法
t2 = np.array([[i for i in range(j, j+4)] for j in range(5)])
t2 = np.where(t2 < 3, 0, 3) #相当于三目运算符, 小于3的赋值为0, 否则赋值为3
print(t2)
# clip方法
t3 = np.array([[i for i in range(j, j+4)] for j in range(5)])
t3 = t3.clip(2, 4) # 小于2的赋值为2, 大于4的赋值为4
print(t3)
数组的拼接
t1 = np.array([[i for i in range(j, j+4)] for j in range(5)])
t2 = np.array([[i for i in range(j, j+4)] for j in range(5, 10)])
print(t1)
# [[0 1 2 3]
# [1 2 3 4]
# [2 3 4 5]
# [3 4 5 6]
# [4 5 6 7]]
print(t2)
# [[ 5 6 7 8]
# [ 6 7 8 9]
# [ 7 8 9 10]
# [ 8 9 10 11]
# [ 9 10 11 12]]
# 竖直拼接
t3 = np.vstack((t1, t2))
print(t3)
# [[ 0 1 2 3]
# [ 1 2 3 4]
# [ 2 3 4 5]
# [ 3 4 5 6]
# [ 4 5 6 7]
# [ 5 6 7 8]
# [ 6 7 8 9]
# [ 7 8 9 10]
# [ 8 9 10 11]
# [ 9 10 11 12]]
# 水平拼接
t4 = np.hstack((t1, t2))
print(t4)
# [[ 0 1 2 3 5 6 7 8]
# [ 1 2 3 4 6 7 8 9]
# [ 2 3 4 5 7 8 9 10]
# [ 3 4 5 6 8 9 10 11]
# [ 4 5 6 7 9 10 11 12]]
行列交换
t1 = np.array([[i for i in range(j, j+4)] for j in range(5)])
# 行交换
t1[[2, 3], :] = t1[[3, 2], :]
# 列交换
t1[:, [2, 3]] = t1[:, [3, 2]]