Comprehensive Guide to Common NumPy Array Operations
This article presents a thorough tutorial on NumPy array creation, indexing, reshaping, concatenation, splitting, copying, slicing, statistical analysis, boolean indexing, sorting, unique values, broadcasting, merging, insertion, deletion, transposition, flattening, multi‑dimensional merging, random sampling, dot and outer products, cumulative operations, and differences, providing code examples for each to boost data‑processing efficiency in Python.
NumPy provides a rich set of high‑level operations for creating and manipulating arrays, which are essential for scientific computing and data processing in Python.
1. Array creation
import numpy as np
# 创建一个全零数组
zeros_array = np.zeros((3, 3))
print("全零数组:")
print(zeros_array)
# 创建一个全一数组
ones_array = np.ones((2, 2))
print("全一数组:")
print(ones_array)
# 创建一个单位矩阵
identity_array = np.eye(2)
print("单位矩阵:")
print(identity_array)
# 创建一个随机数组
np.random.seed(0)
random_array = np.random.rand(2, 2)
print("随机数组:")
print(random_array)2. Array indexing
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
element = arr[1, 2]
print("访问单个元素:", element)
sub_array = arr[0:2, 1:3]
print("访问子数组:")
print(sub_array)3. Shape manipulation
arr = np.array([[1, 2, 3], [4, 5, 6]])
reshaped_arr = arr.reshape(3, 2)
print("改变形状后的数组:")
print(reshaped_arr)4. Concatenation
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
concatenated_arr = np.hstack((arr1, arr2))
print("水平拼接后的数组:", concatenated_arr)
concatenated_arr = np.vstack((arr1, arr2))
print("垂直拼接后的数组:")
print(concatenated_arr)5. Splitting
# Horizontal split
arr = np.array([1, 2, 3, 4, 5, 6])
split_arr = np.hsplit(arr, 2)
print("水平分割后的数组:")
print(split_arr)
# Vertical split
arr = np.array([[1, 2], [3, 4], [5, 6]])
split_arr = np.vsplit(arr, 2)
print("垂直分割后的数组:")
print(split_arr)6. Copy
arr = np.array([1, 2, 3])
deep_copy_arr = arr.copy()
print("深拷贝后的数组:", deep_copy_arr)7. Slicing
arr = np.array([1, 2, 3, 4, 5, 6])
sliced_arr = arr[1:4]
print("切片后的数组:", sliced_arr)8. Statistics
arr = np.array([1, 2, 3, 4, 5, 6])
min_value = arr.min()
print("最小值:", min_value)
max_value = arr.max()
print("最大值:", max_value)
sum_value = arr.sum()
print("总和:", sum_value)
mean_value = arr.mean()
print("平均值:", mean_value)9. Boolean indexing
bool_index = arr > 3
print("布尔索引:", bool_index)
selected_elements = arr[bool_index]
print("选择的元素:", selected_elements)10. Sorting and reversing
sorted_arr = np.sort(arr)
print("排序后的数组:", sorted_arr)
reversed_arr = np.flip(arr)
print("逆序后的数组:", reversed_arr)11. Unique values and counts
unique_values = np.unique(arr)
print("唯一值:", unique_values)
counts = np.bincount(arr)
print("每个元素的出现次数:", counts)12. Broadcasting
arr = np.array([1, 2, 3])
broadcasted_arr = arr * 2
print("广播机制后的数组:", broadcasted_arr)13. Merging arrays
# Horizontal merge
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
merged_arr = np.concatenate((arr1, arr2), axis=0)
print("水平合并后的数组:", merged_arr)
# Vertical merge
arr1 = np.array([[1, 2, 3]])
arr2 = np.array([[4, 5, 6]])
merged_arr = np.concatenate((arr1, arr2), axis=0)
print("垂直合并后的数组:")
print(merged_arr)14. Insert and delete
arr = np.array([1, 2, 3])
inserted_arr = np.insert(arr, 1, 99)
print("插入元素后的数组:", inserted_arr)
deleted_arr = np.delete(arr, 1)
print("删除元素后的数组:", deleted_arr)15. Transpose
arr = np.array([[1, 2, 3], [4, 5, 6]])
transposed_arr = arr.T
print("转置后的数组:")
print(transposed_arr)16. Flatten
arr = np.array([[1, 2, 3], [4, 5, 6]])
flattened_arr = arr.flatten()
print("展平后的数组:", flattened_arr)17. Split by column
arr = np.array([[1, 2, 3], [4, 5, 6]])
split_by_column_arr = np.hsplit(arr, 3)
print("按列拆分后的数组:")
print(split_by_column_arr)18. Multi‑dimensional merge
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr3 = np.array([7, 8, 9])
merged_multi_arr = np.array([arr1, arr2, arr3])
print("合并多维数组后的结果:")
print(merged_multi_arr)19. Random choice (single element)
arr = np.array([1, 2, 3, 4, 5])
probabilities = np.array([0.1, 0.2, 0.3, 0.2, 0.2])
random_element = np.random.choice(arr, p=probabilities)
print("按照概率分布随机抽取的元素:", random_element)20. Random choice (multiple elements)
n = 3
random_elements = np.random.choice(arr, size=n, p=probabilities)
print("按照概率分布随机抽取的多个元素:", random_elements)21. Dot product
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
dot_product = np.dot(arr1, arr2)
print("点积:", dot_product)22. Outer product
outer_product = np.outer(arr1, arr2)
print("外积:")
print(outer_product)23. Cumulative sum
cumulative_sum = np.cumsum(arr)
print("累积和:", cumulative_sum)24. Cumulative product
cumulative_product = np.cumprod(arr)
print("累积乘积:", cumulative_product)25. Difference
difference = np.diff(arr)
print("差分:", difference)By mastering these NumPy operations, you can dramatically improve the efficiency of data handling and scientific computation in Python.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.