首先导包:
import numpy as np
元素求和
a = np.array([1, 2])
b = np.array([3, 4])
print(a + b) #[4 6]
print(np.sum([a, b], axis=0)) #[4 6]
print(np.sum([a, b], axis=1)) #[3 7]
print(np.sum(a)) #3
print(np.sum([a], axis=0)) #[1 2]
print(np.sum([a], axis=1)) #[3]
条件筛选
#比如要筛选二维数组的多列
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(arr[(arr[:, 1] > 4) & (arr[:, 2] > 8)]) #array([[7, 8, 9]])
删除列
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(np.delete(arr, -1, axis=1)) #删除最后一列
print(np.delete(arr, [1, 2], axis=1)) #删除最后两列
数组拼接
#以鸢尾花数据为例,把标签拼接在最后一列
from sklearn.datasets import load_iris
iris = load_iris()
X, y = iris.data, iris.target
y = y.reshape(-1, 1)
concatenated_dat = np.concatenate((X, y), axis=1)