Python Numpy数组扩展repeat和tile使用实例解析

Cora
Cora
发布时间:2026-10-13| 3人浏览过
原创

本文详细解析Python Numpy库中repeat和tile两个数组扩展函数的用法。通过具体代码示例,对比展示了repeat如何复制数组元素,以及tile如何按指定次数重复整个数组,帮助开发者掌握这两种常见的数组操作技巧。

Numpy数组扩展函数概述

本文深入探讨Python Numpy库中用于数组扩展的两个核心函数:repeat和tile,并通过详细的代码示例进行解析,旨在为读者的学习与工作提供实用的参考指南。

numpy.repeat函数详解

numpy.repeat

官方文档

numpy.repeat(a, repeats, axis=None) Repeat elements of an array.

从函数功能来看,repeat主要负责对数组中的每一个独立元素执行复制操作。

具体应用示例如下:


>>> a = np.arange(3)
>>> a
array([0, 1, 2])
>>> np.repeat(a, 2)
array([0, 0, 1, 1, 2, 2])

>>> a = [[0,1], [2,3], [4,5]]
>>> y = np.repeat(a, 2)
>>> y
array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5])

numpy.tile函数详解

numpy.tile

官方文档

numpy.tile(A, reps) Construct an array by repeating A the number of times given by reps.

相比之下,tile函数则是将整个数组A视为一个整体操作对象进行重复处理。

其典型使用场景如下:


>>> a = np.array([[1,2],[3,4]])
>>> a
array([[1, 2],
    [3, 4]])
>>> np.tile(a, 2)
array([[1, 2, 1, 2],
    [3, 4, 3, 4]])

>>> a = [[0,1], [2,3], [4,5]]
>>> x = np.tile(a, (2,1))
>>> x
array([[0, 1],
    [2, 3],
    [4, 5],
    [0, 1],
    [2, 3],
    [4, 5]])

希望以上内容能对各位的学习与实践有所帮助,欢迎持续关注本站获取更多信息。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。