- np
import numpy as np
- np.__version__
print(np.__version__) # 1.15.2
- np.arange(10),创建一维数组
print(np.arange(10)) # [0 1 2 3 4 5 6 7 8 9]
- np.ones((2, 2), dtype=bool),创建布尔数组
print(np.full((2, 2), True, dtype=bool)) # [[ True True] [ True True]]
print(np.ones((2, 2), dtype=bool)) # [[ True True] [ True True]]
print(np.full((2, 2), 3, dtype=float)) # [[3. 3.] [3. 3.]]
- 提取所有的奇数
arr = np.arange(10)
a = arr[arr % 2 == 1]
print(a) # [1 3 5 7 9]
- 所有的奇数赋值为-1
arr[arr % 2 == 1] = -1
print(arr) # [ 0 -1 2 -1 4 -1 6 -1 8 -1]
- 奇数赋值为 -1,其他数 +1
arr = np.arange(10)
out = np.where(arr % 2 == 1, -1, arr + 1)
print(arr) # [0 1 2 3 4 5 6 7 8 9]
print(out) # [1 -1 3 -1 5 -1 7 -1 9 -1]
- np.concatenate([a, b], axis=0)或np.vstack([a, b]),垂直拼接两个数组
a = np.arange(10).reshape(2, 5)
b = np.repeat(1, 10).reshape(2, -1) # automatically decides the number of cols
print(a) # [[0 1 2 3 4] [5 6 7 8 9]]
print(b) # [[1 1 1 1 1] [1 1 1 1 1]]
print(type(a)) # <class 'numpy.ndarray'>
print(np.concatenate([a, b], axis=0)) # [[0 1 2 3 4] [5 6 7 8 9] [1 1 1 1 1] [1 1 1 1 1]]
print(np.vstack([a, b])) # same
print(np.r_[a, b]) # same
- np.concatenate([a, b], axis=1)或np.hstack([a, b]),水平拼接两个数组
print(np.concatenate([a, b], axis=1)) # [[0 1 2 3 4 1 1 1 1 1] [5 6 7 8 9 1 1 1 1 1]]
print(np.hstack([a, b])) # same
print(np.c_[a, b]) # same
- np.repeat(a, 3),np.tile(a, 3),重复序列的两种方式
a = np.array([1, 2, 3])
print(np.repeat(a, 3)) # [1 1 1 2 2 2 3 3 3]
print(np.tile(a, 3)) # [1 2 3 1 2 3 1 2 3]
print(np.r_[np.repeat(a, 3), np.tile(a, 3)]) # 水平拼接 [1 1 1 2 2 2 3 3 3 1 2 3 1 2 3 1 2 3]
- np.intersect1d(a, b)获取共有项,np.setdiff1d(a, b)获取a独有项
a = np.array([1, 2, 3, 6])
b = np.array([1, 2, 8, 9])
print(np.intersect1d(a, b)) # [1 2]
print(np.setdiff1d(a, b)) # [3 6]
- np.where(a == b)获取元素匹配的位置,相同位置元素相同成为匹配
print(a == b) # [ True True False False]
print(np.where(a == b)) # (array([0, 1]),)
- np.where((a >= 5) & (a <= 7))提取给定范围的数字
a = np.arange(3, 10)
b = a[(a >= 5) & (a <= 7)]
print((a >= 5) & (a <= 7)) # [False False True True True False False]
print(np.logical_and(a>=5, a<=7)) # [False False True True True False False]
print(b) # [5 6 7]
index1 = np.where((a >= 5) & (a <= 7))
index2 = np.where(np.logical_and(a>=5, a<=7)) # 两种方法的效果相同
print(a[index1]) # [5 6 7]
print(a[index2]) # [5 6 7]
- np.vectorize(max),使用(自定义)函数处理数组,提取每一列的最大值
print(max(5, 6)) # 6
a = np.array([1, 2, 3])
b = np.array([2, 1, 3])
pair_max = np.vectorize(max, otypes=[float]) # 提取每一列的最大值
print(pair_max(a, b)) # [2 2 3]
- arr[:, [1, 0, 2]],交换二维数组的两列,理解为列的复制粘贴
arr = np.arange(9).reshape(3, 3)
print(arr[:, [1, 0, 2]])
# [[1 0 2]
# [4 3 5]
# [7 6 8]]
- arr[[1, 0, 2], :],交换二维数组的两行
print(arr[[1, 0, 2], :])
# [[3 4 5]
# [0 1 2]
# [6 7 8]]
- arr[:: -1, :],反转二维数组的行
print(arr[::-1])
# [[6 7 8]
# [3 4 5]
# [0 1 2]]
print(arr[:: -1, :])
# [[6 7 8]
# [3 4 5]
# [0 1 2]]
- arr[:, ::-1],反转二维数组的列
print(arr[:, ::-1])
# [[2 1 0]
# [5 4 3]
# [8 7 6]]
完
原文地址:https://www.cnblogs.com/yangzhaonan/p/10428470.html
时间: 2024-10-08 23:11:41