2045 字
10 分钟
Numpy学习笔记(1)
2025-10-24
NOTE

本笔记基于 Jupyter Lab

  • Numpy 是一个开源的 Python 库,它提供了高性能的数组对象,以及数学函数,用于操作这些数组, 广泛应用于科学和工程领域。
IMPORTANT

导入Numpy

import numpy as np

这种约定允许使用简短易识别的前缀 (np.) 访问 NumPy 功能,同时将 NumPy 功能与同名其他功能区分开来。

轴(Axis)的基本概念#

在 NumPy 中,轴(axis)是描述数组维度方向的核心概念,编号从 0 开始,从“最外层”到“最内层”。
规律:轴编号 = 维度层级,轴 0 为最外层,编号越大,操作越聚焦内层结构。

一维数组(1D Array)#

  • 轴 0(axis=0:唯一维度方向(如直线延伸)。
    • 示例:[1,2,3,4],轴 0 表示从第一个到最后一个元素的方向。

二维数组(2D Array)#

  • 轴 0(axis=0:垂直方向(行维度)。
    • 示例:[[1,2],[3,4]],沿轴 0 求和:[1+3, 2+4] = [4,6]
  • 轴 1(axis=1:水平方向(列维度)。
    • 示例:[[1,2],[3,4]],沿轴 1 求和:[1+2, 3+4] = [3,7]

三维数组(3D Array)#

  • 轴 0(axis=0:二维数组的堆叠方向(深度)。
    • 示例:[[[1,2],[3,4]], [[5,6],[7,8]]],沿轴 0 求和:[[1+5,2+6],[3+7,4+8]] = [[6,8],[10,12]]
  • 轴 1(axis=1:二维数组内部的垂直方向(行维度)。
    • 示例:上述数组,沿轴 1 求和:[[1+3,2+4], [5+7,6+8]] = [[4,6],[12,14]]
  • 轴 2(axis=2:二维数组内部的水平方向(列维度)。
    • 示例:上述数组,沿轴 2 求和:[[1+2,3+4], [5+6,7+8]] = [[3,7],[11,15]]

数组属性#

NumPy 的数组类名为 ndarray。它也以别名 array 著称。

WARNING

请注意,numpy.array 与标准 Python 库中的 array.array 类不同,后者只处理一维数组,功能较少。

import numpy as np
arr = np.array([[[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5]]])
print(arr) # 输出数组,注意格式:中括号,元素间无逗号(区别于列表)
print(arr.ndim) # 数组的轴(维度)数量
print(arr.shape) # 数组的维度,整数元组表示每个维度的大小
print(arr.size) # 数组的元素总数,等于 shape 中元素的乘积
print(arr.dtype) # 数组中元素的类型,可为标准 Python 类型或 NumPy 类型
print(arr.itemsize) # 数组中每个元素的字节大小,等同于 dtype.itemsize
print(arr.data) # 包含数组实际元素的缓冲区,通常通过索引访问元素

输出结果: alt text

数组创建#

使用 array 函数创建#

从普通的 Python 列表或元组创建数组:

import numpy as np
a = np.array([2, 3, 4])
print(a) # array([2, 3, 4])
print(a.dtype) # dtype('int64')
b = np.array([1.2, 3.5, 5.1])
print(b.dtype) # dtype('float64')
  • 参数np.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)
    • object:输入数据,可以是列表、元组或其他数组。
    • dtype:数组元素的数据类型,可选。
    • copy:是否复制输入数据,默认为 True
    • order:存储顺序,C 表示行优先,F 表示列优先。
    • subok:默认返回基础类的数组,若为 True 则返回子类。
    • ndmin:指定返回数组的最小维数。

注意:调用 array 时需提供单一序列作为参数:

a = np.array([1, 2, 3, 4]) # 正确

将序列的序列转换为二维数组:

b = np.array([(1.5, 2, 3), (4, 5, 6)])
print(b)
# array([[1.5, 2. , 3. ],
# [4. , 5. , 6. ]])

显式指定数组类型:

c = np.array([[1, 2], [3, 4]], dtype=complex)
print(c)
# array([[1.+0.j, 2.+0.j],
# [3.+0.j, 4.+0.j]])

重设数组的 shape 属性#

可以通过修改数组的 shape 属性来重设数组的形状,而无需创建新数组。

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
arr.shape = (2, 3) # 将一维数组重设为二维数组
print(arr)
# 输出:
# array([[1, 2, 3],
# [4, 5, 6]])

使用占位符函数创建#

创建具有初始占位符内容的数组:

np.zeros((3, 4))
# array([[0., 0., 0., 0.],
# [0., 0., 0., 0.],
# [0., 0., 0., 0.]])
np.ones((2, 3, 4), dtype=np.int16)
# array([[[1, 1, 1, 1],
# [1, 1, 1, 1],
# [1, 1, 1, 1]],
#
# [[1, 1, 1, 1],
# [1, 1, 1, 1],
# [1, 1, 1, 1]]], dtype=int16)
np.empty((2, 3))
# array([[...], # 内容可能因内存状态而异(随机)
# [...]])
np.eye(3)
# array([[1., 0., 0.],
# [0., 1., 0.],
# [0., 0., 1.]])
np.diag([1, 2, 3])
# array([[1, 0, 0],
# [0, 2, 0],
# [0, 0, 3]])
TIP

其余占位符函数不再列举,请参阅数组创建例程

  • 参数
    • np.zeros(shape, dtype=float, order='C')

      • shape:数组的形状,必须指定。
      • dtype:数组元素的数据类型,默认为 float
      • order:存储顺序,C 表示行优先,F 表示列优先。
    • np.ones(shape, dtype=None, order='C')

      • 参数与 np.zeros 相同。
    • np.empty(shape, dtype=float, order='C')

      • 参数与 np.zeros 相同。
    • np.eye(N, M=None, k=0, dtype=<class 'float'>, order='C')

      • N:行数。
      • M:列数,默认为 N
      • k:对角线的索引,默认为 0(主对角线)。
    • np.diag(v, k=0)

      • v:输入数组。
      • k:对角线的索引,默认为 0(主对角线)。

创建数字序列的数组#

arange 函数:#

np.arange(10, 30, 5)
# array([10, 15, 20, 25])
np.arange(0, 2, 0.3)
# array([0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])
  • 参数np.arange(start, stop, step)
    • start:起始值(包含),若省略则默认为 0
    • stop:终止值(不包含),必须指定。
    • step:步长,若省略则默认为 1;步长可为整数或浮点数,用于控制相邻元素的间隔。

linspace 函数:#

from numpy import pi
np.linspace(0, 2, 9)
# array([0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])
  • 参数np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
    • start:序列的起始值。
    • stop:序列的终止值。
    • num:生成的样本数,默认为 50
    • endpoint:是否包含终止值,默认为 True
    • retstep:是否返回样本间距,默认为 False
    • dtype:输出数组的数据类型。
    • axis:结果中样本的轴,默认为 0

logspace 函数#

生成对数刻度的数值序列。

arr = np.logspace(1, 3, num=5)
  • 参数start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0
    • start:对数刻度的起始值。
    • stop:对数刻度的终止值。
    • num:生成的样本数,默认为 50
    • base:对数的底数,默认为 10
NOTE

arange 函数和 linspace 函数的区别:

  • arange 函数生成的序列包含起始值,不包含终止值,步长可以是整数或浮点数。
  • linspace 函数生成的序列包含起始值,默认也包含终止值,样本数可以自定义。

数组数据类型#

常见的数据类型包括:

  • int:整数类型,如 np.int8np.int16np.int32np.int64
  • float:浮点类型,如 np.float32np.float64
  • bool:布尔类型,np.bool_
  • complex:复数类型,如 np.complex64np.complex128

数据类型转换示例#

import numpy as np
print('转换结果为:', np.float64(42)) # 整数转换为浮点数(精确转换)
print('转换结果为:', np.int8(42.0)) # 浮点数转换为整数(截断小数取整)
print('转换结果为:', np.bool_(42)) # 整数转换为布尔值(非零整数均为 True)
print('转换结果为:', np.bool_(0)) # 整数转换为布尔值(0 为 False)
print('转换结果为:', np.float64(True)) # 布尔值转换为浮点数
print('转换结果为:', np.float64(False)) # 布尔值转换为浮点数

np.dtype 函数#

np.dtype 用于定义数组元素的数据类型,支持标准 Python 类型和 NumPy 类型。

np.dtype 的参数#

  • dtype:数据类型,可以是 NumPy 类型(如 np.int32)或标准 Python 类型(如 int)。
  • byteorder:字节顺序,可选值为 >(大端)或 <(小端)。
  • align:是否对齐字段,默认为 False
  • subdtype:子类型,用于描述数组的维度。

创建数据类型#

import numpy as np
# 定义一个数组并指定数据类型
arr = np.array([1, 2, 3], dtype=np.float64)
print(arr)
# array([1., 2., 3.])
print(arr.dtype)
# dtype('float64')

查看已有数组类型#

import numpy as np
arr = np.array([1, 2, 3], dtype=np.float32)
print("数组数据类型:", np.dtype(arr.dtype))
# dtype('float32')

自定义数据类型#

import numpy as np
# 定义一个自定义数据类型
df = np.dtype([('name', 'U10'), ('quantity', 'i4'), ('price', 'f4')])
itemz = np.array([('tomatoes', 42, 4.14), ('cabbages', 13, 1.72)], dtype=df)
print('数组为:', itemz)
print('自定义数据为:', itemz.dtype)
# array([('tomatoes', 42, 4.14), ('cabbages', 13, 1.72)],
# dtype=[('name', '<U10'), ('quantity', '<i4'), ('price', '<f4')])

生成随机数#

np.random.random 函数#

生成 [0, 1) 区间的均匀分布随机数。

rand_array = np.random.random((3, 2))
  • 参数size:指定生成数组的形状,类型为 inttuple,如 (2, 3) 表示 2x3 的数组。

np.random.rand 函数#

生成 [0, 1) 区间的均匀分布随机数,支持直接传递形状参数。

rand_array = np.random.rand(3, 2)
  • 参数shape:指定生成数组的形状,类型为 inttuple

np.random.randn 函数#

生成标准正态分布(均值为 0,标准差为 1)的随机数。

rand_normal = np.random.randn(3, 2)
  • 参数shape:指定生成数组的形状,类型为 inttuple

np.random.randint 函数#

生成指定范围内的随机整数。

rand_int = np.random.randint(10, 50, size=(3, 2), dtype=int)
  • 参数low, high=None, size=None
    • low:随机整数的下界(包含)。
    • high:随机整数的上界(不包含)。
    • size:生成数组的形状。
    • dtype:输出数组的数据类型,默认为 int

参考

Numpy学习笔记(1)
https://blog.chuwu.top/posts/numpy/numpy1/
作者
ChuwuYo
发布于
2025-10-24
许可协议
CC BY-NC-SA 4.0