numpy常用操作
发表于|更新于
|总字数:1.4k|阅读时长:5分钟|浏览量:
NumPy是Python中用于科学计算的基础库,提供了大量的数组操作函数。以下是一些NumPy中的常用操作:
基本操作
数组创建
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| import numpy as np
arr = np.array([1, 2, 3, 4]) print(arr)
zeros_arr = np.zeros((2, 3)) print(zeros_arr)
ones_arr = np.ones((2, 3), dtype=int) print(ones_arr)
empty_arr = np.empty((2, 2)) print(empty_arr)
full_arr = np.full((2, 2), 7) print(full_arr)
arange_arr = np.arange(0, 10, 2) print(arange_arr)
linspace_arr = np.linspace(0, 1, 5) print(linspace_arr)
logspace_arr = np.logspace(0, 2, 3, base=10) print(logspace_arr)
|
数组属性
1 2 3 4 5 6 7 8 9 10 11 12
| print(arr.shape)
print(arr.ndim)
print(arr.dtype)
print(arr.size)
|
数组操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| reshaped_arr = arr.reshape((2, 2)) print(reshaped_arr)
transposed_arr = reshaped_arr.T print(transposed_arr)
flattened_arr = reshaped_arr.flatten() print(flattened_arr)
expanded_arr = np.expand_dims(arr, axis=0) print(expanded_arr)
squeezed_arr = np.squeeze(expanded_arr) print(squeezed_arr)
concat_arr = np.concatenate((arr, np.array([5, 6, 7, 8]))) print(concat_arr)
split_arrs = np.split(arr, [2, 4]) print(split_arrs)
|
数组计算
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| arr1 = np.array([1, 2, 3]) arr2 = np.array([4, 5, 6]) sum_arr = arr1 + arr2 print(sum_arr)
dot_product = np.dot(arr1, arr2) print(dot_product)
sqrt_arr = np.sqrt(arr1) print(sqrt_arr)
sin_arr = np.sin(arr1) print(sin_arr)
|
统计分析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| sum_value = np.sum(arr) print(sum_value)
mean_value = np.mean(arr) print(mean_value)
median_value = np.median(arr) print(median_value)
std_value = np.std(arr) print(std_value)
var_value = np.var(arr) print(var_value)
max_value, min_value = np.max(arr), np.min(arr) print(max_value, min_value)
|
矩阵操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| mat1 = np.array([[1, 2], [3, 4]]) mat2 = np.array([[5, 6], [7, 8]]) mat_product = np.matmul(mat1, mat2) print(mat_product)
mat_product_at = mat1 @ mat2 print(mat_product_at)
inv_mat = np.linalg.inv(mat1) print(inv_mat)
det_value = np.linalg.det(mat1) print(det_value)
eig_values, eig_vectors = np.linalg.eig(mat1) print(eig_values) print(eig_vectors)
|
其他操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| unique_values = np.unique(arr) print(unique_values)
condition = arr > 2 filtered_arr = arr[condition] print(filtered_arr)
sorted_arr = np.sort(arr) print(sorted_arr)
copied_arr = np.copy(arr) print(copied_arr)
|