介绍
NumPy 是 Numerical Python 的缩写,是 Python 中科学计算的基本包。它因其在处理大型多维数组和矩阵方面的强大功能以及大量用于操作这些数组的数学函数而被广泛使用。NumPy 是许多科学和数值库(包括 Pandas、Matplotlib 和 SciPy)的主干,使其成为任何在 Python 中处理数据的人的必备工具。。
本文中介绍的内容:
- NumPy 入门:从基础知识开始,包括如何安装 NumPy 并了解其主要概念和术语。
- 创建 NumPy 数组:了解创建 NumPy 数组的各种方法,包括从列表和使用内置 NumPy 函数。
- 数组运算:发现 NumPy 数组运算的强大功能,包括基本算术运算和通用函数 (ufunc)。
- 索引和切片:掌握访问和修改数组中元素的技术。
- 数组操作:探索高级数组操作技术,例如重塑、连接和拆分。
NumPy 入门
NumPy 入门
在深入研究 NumPy 的功能之前,必须设置环境并了解一些基本概念。本节将指导完成安装过程,并向介绍 NumPy 的基本元素。
安装 NumPy
使用 NumPy 的第一步是确保它安装在的 Python 环境中。可以使用 pip(Python 软件包安装程序)安装 NumPy。打开终端或命令提示符并运行以下命令:
pip install numpy
如果使用的是 Jupyter 笔记本,则可以通过运行以下命令直接从单元安装 NumPy:
!pip install numpy
在 Jupyter 笔记本中,!运算符允许直接从笔记本中运行 shell 命令。
安装后,可以在 Python 脚本或 Jupyter 笔记本中导入 NumPy:
import numpy as np
别名 np 是常用的,被认为是一种最佳实践,使代码更加简洁和可读。
基本概念和术语
要有效地使用 NumPy,了解一些关键概念和术语非常重要:
- 数组:NumPy 的核心功能是数组对象。数组是一个值网格,所有值都是相同的类型,由非负整数元组索引。NumPy 数组比 Python 列表更高效进行数值运算。
- ndarray:NumPy 的核心对象是 ndarray,它是一个固定大小项目的多维数组。它是 NumPy 中的主要数据结构。
- 轴:轴是沿其执行操作的维度。例如,2D 数组有两个轴:行(轴 0)和列(轴 1)。
- 形状:数组的形状是一个整数元组,表示数组沿每个维度的大小。例如,2x3 数组的形状是 (2, 3)。
- 数据类型 (dtype):NumPy 数组包含由 dtype 对象指定的单一类型的元素。这可确保对数组的操作快速高效。
下面是一个简单的示例来说明这些概念:
import numpy as np
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
# Displaying the array
print("Array:\n", array_2d)# Displaying the shape of the array
print("Shape of the array:", array_2d.shape)# Displaying the data type of the array
print("Data type of the array:", array_2d.dtype)# Accessing elements
print("Element at row 0, column 1:", array_2d[0, 1])"""
Output:
Array:
[[1 2 3]
[4 5 6]]Shape of the array: (2, 3)
Data type of the array: int64
Element at row 0, column 1: 2
"""
创建 NumPy 数组
创建 NumPy 数组
可以通过多种方式创建 NumPy 数组,为各种用例提供灵活性和便利性。本节将介绍创建 NumPy 数组的最常见方法,包括从列表、使用内置函数等。
从列表创建数组
创建 NumPy 数组最直接的方法是使用 np.array 函数从 Python 列表中创建。下面是一个示例:
# Creating a 1D array from a list
list_1d = [1, 2, 3, 4, 5]
array_1d = np.array(list_1d)
print("1D Array:", array_1d)
# Creating a 2D array (matrix) from a list of lists
list_2d = [[1, 2, 3], [4, 5, 6]]
array_2d = np.array(list_2d)
print("2D Array:\n", array_2d)
# Creating a 3D array from a list of lists of lists
list_3d = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
array_3d = np.array(list_3d)
print("3D Array:\n", array_3d)
"""
Output:
1D Array: [1 2 3 4 5]
2D Array:
[[1 2 3]
[4 5 6]]
3D Array:
[[[1 2]
[3 4]][[5 6]
[7 8]]]
"""
使用内置的 NumPy 函数
NumPy 提供了几个内置函数来快速有效地创建数组。以下是一些最常用的函数:
- np.zeros:创建一个填充了 0 的数组。
- np.ones:创建一个填充 1 的数组。
- np.arange:创建具有一系列值的数组。
- np.linspace:在指定范围内创建具有均匀间距值的数组。
- np.random.rand:创建具有随机值的数组。
以下是每个示例:
# Creating an array of zeros
array_zeros = np.zeros((3, 4))
print("Array of zeros:\n", array_zeros)
# Creating an array of ones
array_ones = np.ones((2, 3))
print("Array of ones:\n", array_ones)
# Creating an array with a range of values
array_arange = np.arange(0, 10, 2)
print("Array with a range of values:", array_arange)
# Creating an array with evenly spaced values
array_linspace = np.linspace(0, 1, 5)
print("Array with evenly spaced values:", array_linspace)
# Creating an array with random values
array_random = np.random.rand(3, 3)
print("Array with random values:\n", array_random)
"""
Output
Array of zeros:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
Array of ones:
[[1. 1. 1.]
[1. 1. 1.]]
Array with a range of values: [0 2 4 6 8]
Array with evenly spaced values: [0. 0.25 0.5 0.75 1. ]
Array with random values:
[[0.39236602 0.10292247 0.26992789]
[0.20464863 0.10948225 0.15399477]
[0.37111632 0.76641267 0.68806162]]
"""
从标量创建数组
还可以通过重复标量值来创建数组。这可以使用 np.full 函数来完成:
# Creating an array filled with a specific value
array_full = np.full((3, 3), 7)
print("Array filled with 7s:\n", array_full)
"""
Output:
Array filled with 7s:
[[7 7 7]
[7 7 7]
[7 7 7]]
"""
创建标识矩阵
单位矩阵是方形矩阵,对角线上有 1,其他位置有 0。可以使用 np.eye 函数创建这些:
# Creating an identity matrix
identity_matrix = np.eye(4)
print("Identity matrix:\n", identity_matrix)
"""
Output:
Identity matrix:
[[1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 1.]]
"""
这些方法涵盖了创建 NumPy 数组的广泛场景。使用这些工具,您可以有效地初始化用于数值计算的数组。
数组操作
数组操作
NumPy 数组提供了多种操作,使数值计算既高效又简单。本节将介绍基本的算术运算、通用函数 (ufunc) 和其他有用的数组运算。
基本算术运算
NumPy 允许您对数组执行元素级算术运算。这些操作是逐个元素应用的,并且比使用 Python 循环要快得多。
下面是一个演示基本算术运算的示例:
# Creating two arrays
array1 = np.array([1, 2, 3, 4])
array2 = np.array([5, 6, 7, 8])
# Element-wise addition
add_result = array1 + array2
print("Element-wise addition:", add_result)
# Element-wise subtraction
sub_result = array1 - array2
print("Element-wise subtraction:", sub_result)
# Element-wise multiplication
mul_result = array1 * array2
print("Element-wise multiplication:", mul_result)
# Element-wise division
div_result = array1 / array2
print("Element-wise division:", div_result)
"""
Output:
Element-wise addition: [ 6 8 10 12]
Element-wise subtraction: [-4 -4 -4 -4]
Element-wise multiplication: [ 5 12 21 32]
Element-wise division: [0.2 0.33333333 0.42857143 0.5]
"""
通用函数 (ufunc)
通用函数 (ufunc) 是对数组进行元素运算的函数。NumPy 提供了大量用于执行数学运算的内置 ufunc。
以下是一些示例:
# Creating an array
array = np.array([1, 2, 3, 4])
# Square root of each element
sqrt_result = np.sqrt(array)
print("Square root:", sqrt_result)
# Exponential (e^x) of each element
exp_result = np.exp(array)
print("Exponential:", exp_result)
# Sine of each element
sin_result = np.sin(array)
print("Sine:", sin_result)
# Natural logarithm of each element
log_result = np.log(array)
print("Natural logarithm:", log_result)
"""
Output:
Square root: [1. 1.41421356 1.73205081 2. ]
Exponential: [ 2.71828183 7.3890561 20.08553692 54.59815003]
Sine: [0.84147098 0.90929743 0.14112001 -0.7568025 ]
Natural logarithm: [0. 0.69314718 1.09861229 1.38629436]
"""
聚合函数
NumPy 提供了几个函数来聚合数组值,例如计算总和、平均值、最大值和最小值。
以下是一些示例:
# Creating an array
array = np.array([1, 2, 3, 4, 5])
# Sum of all elements
sum_result = np.sum(array)
print("Sum:", sum_result)
# Mean (average) of all elements
mean_result = np.mean(array)
print("Mean:", mean_result)
# Maximum value
max_result = np.max(array)
print("Maximum:", max_result)
# Minimum value
min_result = np.min(array)
print("Minimum:", min_result)
"""
Output:
Sum: 15
Mean: 3.0
Maximum: 5
Minimum: 1
"""
矩阵运算
NumPy 还支持矩阵运算,这对于线性代数至关重要。以下是一些基本的矩阵运算:
# Creating two 2x2 matrices
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
# Matrix addition
matrix_add = np.add(matrix1, matrix2)
print("Matrix addition:\n", matrix_add)
# Matrix multiplication
matrix_mul = np.dot(matrix1, matrix2)
print("Matrix multiplication:\n", matrix_mul)
# Transpose of a matrix
matrix_transpose = np.transpose(matrix1)
print("Transpose of the first matrix:\n", matrix_transpose)
"""
Output:
Matrix addition:
[[ 6 8]
[10 12]]
Matrix multiplication:
[[19 22]
[43 50]]
Transpose of the first matrix:
[[1 3]
[2 4]]
"""
索引和切片
索引和切片
索引和切片对于访问和操作 NumPy 数组中的元素至关重要。本节将介绍索引和切片 NumPy 数组的基本和高级技术。
基本索引
Basic indexing 允许您使用数组的索引访问数组的各个元素。NumPy 数组是零索引的,这意味着第一个元素位于索引 0 处。
下面是一个示例:
import numpy as np
# Creating a 1D array
array_1d = np.array([10, 20, 30, 40, 50])
# Accessing elements by index
print("First element:", array_1d[0])
print("Third element:", array_1d[2])
print("Last element:", array_1d[-1])
"""
Output:
First element: 10
Third element: 30
Last element: 50
"""
切片
切片允许您访问数组的子集。切片的语法是 start:stop:step,其中 start 是起始索引,stop 是停止索引(不包括),step 是步长。
下面是一个示例:
# Creating a 1D array
array_1d = np.array([10, 20, 30, 40, 50])
# Slicing the array
print("Elements from index 1 to 3:", array_1d[1:4])
print("Every second element:", array_1d[::2])
print("Elements from index 2 to the end:", array_1d[2:])
"""
Output:
Elements from index 1 to 3: [20 30 40]
Every second element: [10 30 50]
Elements from index 2 to the end: [30 40 50]
"""
多维数组
索引和切片的工作方式与多维数组类似。可以使用以逗号分隔的索引或切片元组来访问元素。
下面是一个 2D 数组的示例:
# Creating a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Accessing elements
print("Element at row 1, column 2:", array_2d[1, 2])
print("First row:", array_2d[0, :])
print("Second column:", array_2d[:, 1])
print("Subarray from rows 0 to 1 and columns 1 to 2:\n", array_2d[0:2, 1:3])
"""
Element at row 1, column 2: 6
First row: [1 2 3]
Second column: [2 5 8]
Subarray from rows 0 to 1 and columns 1 to 2:
[[2 3]
[5 6]]
"""
布尔索引
布尔索引允许根据条件选择元素。这对于筛选数据特别有用。
下面是一个示例:
# Creating an array
array = np.array([10, 20, 30, 40, 50])
# Boolean indexing
bool_idx = array > 30
print("Boolean index array:", bool_idx)
# Using boolean indexing to filter elements
filtered_array = array[bool_idx]
print("Filtered array:", filtered_array)
"""
Output:
Boolean index array: [False False False True True]
Filtered array: [40 50]
"""
花式索引
花式索引允许使用索引列表或数组一次访问多个数组元素。
下面是一个示例:
# Creating an array
array = np.array([10, 20, 30, 40, 50])
# Fancy indexing
indices = [1, 3, 4]
print("Elements at indices 1, 3 and 4:", array[indices])
# Ouput: Elements at indices 1, 3 and 4: [20 40 50]
这些技术提供了访问 NumPy 数组中数据的强大方法。无论您是需要提取特定元素、过滤数据还是创建子数组,NumPy 的索引和切片功能都能轻松高效地实现。
数组操作
数组操作
NumPy 提供了一系列用于操作数组的函数,允许您以各种方式重塑、连接、拆分和修改数组。本节介绍一些最常用的数组操作技术。
重塑阵列
通过重塑,可以在不更改数组数据的情况下更改数组的形状。reshape 函数用于为数组提供新形状。
下面是一个示例:
import numpy as np
# Creating a 1D array
array_1d = np.arange(12)
print("Original 1D array:", array_1d)
# Reshaping to a 3x4 2D array
array_2d = array_1d.reshape((3, 4))
print("Reshaped to 3x4 2D array:\n", array_2d)
# Reshaping to a 2x2x3 3D array
array_3d = array_1d.reshape((2, 2, 3))
print("Reshaped to 2x2x3 3D array:\n", array_3d)
"""
Ouput:
Original 1D array: [ 0 1 2 3 4 5 6 7 8 9 10 11]
Reshaped to 3x4 2D array:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Reshaped to 2x2x3 3D array:
[[ [0 1 2]
[3 4 5]]
[[6 7 8]
[9 10 11]]]
"""
串联和堆叠
Concatenation 沿现有轴连接两个或多个数组,而 Stacking Join 沿新轴连接。np.concatenate 和 np.stack 函数用于这些操作。
下面是一个串联的示例:
# Creating two 1D arrays
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
# Concatenating along the first axis
concatenated_array = np.concatenate((array1, array2))
print("Concatenated array:", concatenated_array)
# Creating two 2D arrays
array3 = np.array([[1, 2], [3, 4]])
array4 = np.array([[5, 6]])
# Concatenating along the first axis (rows)
concatenated_2d = np.concatenate((array3, array4), axis=0)
print("Concatenated 2D array along rows:\n", concatenated_2d)
"""
Concatenated array: [1 2 3 4 5 6]
Concatenated 2D array along rows:
[[1 2]
[3 4]
[5 6]]
"""
下面是一个堆叠的示例:
# Creating two 1D arrays
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
# Stacking along a new axis
stacked_array = np.stack((array1, array2), axis=0)
print("Stacked array along new axis:\n", stacked_array)
"""
Stacked array along new axis:
[[1 2 3]
[4 5 6]]
"""
拆分数组
拆分允许您将一个数组划分为多个子数组。np.split 函数用于此目的。
下面是一个示例:
# Creating a 1D array
array = np.arange(9)
# Splitting the array into 3 sub-arrays
split_array = np.split(array, 3)
print("Split array into 3 sub-arrays:", split_array)
# Creating a 2D array
array2d = np.arange(16).reshape((4, 4))
# Splitting the array into 2 sub-arrays along the rows
split_array2d = np.split(array2d, 2)
print("Split 2D array along rows:\n", split_array2d[0], "\n\n", split_array2d[1])
"""
Output:
Split array into 3 sub-arrays: [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]
Split 2D array along rows:
[[ 0 1 2 3]
[ 4 5 6 7]]
[[ 8 9 10 11]
[12 13 14 15]]
"""
修改数组形状
您还可以使用 ravel、flatten 和 transpose 等函数修改数组的形状。
下面是一个示例:
# Creating a 2D array
array2d = np.array([[1, 2, 3], [4, 5, 6]])
# Flattening the array (convert to 1D)
flattened_array = array2d.flatten()
print("Flattened array:", flattened_array)
# Raveling the array (convert to 1D)
raveled_array = array2d.ravel()
print("Raveled array:", raveled_array)
# Transposing the array (swap rows and columns)
transposed_array = array2d.transpose()
print("Transposed array:\n", transposed_array)
"""
Output:
Flattened array: [1 2 3 4 5 6]
Raveled array: [1 2 3 4 5 6]
Transposed array:
[[1 4]
[2 5]
[3 6]]
"""