如何使用numpy在Python中展平一个矩阵?

风敏大大_9717

风敏大大_9717

2023-08-20

1612人浏览

转载

如何使用numpy在python中展平一个矩阵?

In this article, we will show you how to flatten a matrix using the NumPy library in python.

numpy.ndarray.flatten()函数

The numpy module includes a function called numpy.ndarray.flatten() that returns a one-dimensional copy of the array rather than a two-dimensional or multi-dimensional array.

简单来说,我们可以说它将矩阵压平为1维。

语法

ndarray.flatten(order='C')

参数

order − 'C', 'F', 'A', 'K' (可选)

  • 当我们将排序参数设置为'C,'时,数组按行主序展平。

  • When the 'F' is set, the array is flattened in column-major order.

  • 只有当 'a' 在内存中是Fortran连续的,并且顺序参数设置为 'A' 时,数组才以列主序展开。最终顺序为 'K',以与内存中元素出现的顺序相同的顺序展开数组。此参数默认设置为 'C'。

Return Value − Returns a flattened 1-D matrix

Method 1 − Flattening 2x2 Numpy Matrix of np.array() type

Algorithm (Steps)

以下是执行所需任务的算法/步骤:

  • 使用import关键字,导入带有别名(np)的numpy模块。

  • 使用numpy.array()函数(返回一个ndarray。ndarray是满足给定要求的数组对象),通过将2维数组(2行,2列)作为参数传递给它来创建一个numpy数组。

  • 打印给定的二维矩阵。

  • 在输入矩阵上应用 numpy 模块的 flatten() 函数(将矩阵压平为一维) ,将输入的二维矩阵压平为一维矩阵。

  • 打印输入矩阵的结果扁平化矩阵。

Example

The following program flattens the given input 2-Dimensional matrix to a 1-Dimensional matrix using the flatten()function and returns it −

# importing numpy module with an alias name
import numpy as np

# creating a 2-Dimensional(2x2) numpy matrix
inputMatrix = np.array([[3, 5], [4, 8]])

# printing the input 2D matrix
print("The input numpy matrix:")
print(inputMatrix)

# flattening the 2D matrix to one-dimensional matrix
flattenMatrix = inputMatrix.flatten()

# printing the resultant flattened matrix
print("Resultant flattened matrix:")
print(flattenMatrix)

Output

在执行时,上述程序将生成以下输出 -

NumPy Linux版 2.4.2
NumPy Linux版 2.4.2

NumPy 2.4.2 历史版本下载,来自 PyPI 官方发布,适合旧项目兼容、科学计算脚本复现和指定环境安装。

下载
The input numpy matrix:
[[3 5]
[4 8]]
Resultant flattened matrix:
[3 5 4 8]

Method 2 − Flattening using reshape() function

Algorithm (Steps)

以下是执行所需任务的算法/步骤:

  • Use the numpy.array() function(returns a ndarray. The ndarray is an array object that satisfies the given requirements), for creating a numpy array by passing the 4-Dimensional array(4rows, 4columns) as an argument to it.

  • 打印给定的4维矩阵。

  • 通过将NumPy数组的长度与自身相乘来计算矩阵的元素数量。这些值表示所需的列数。

  • Use the reshape() function(reshapes an array without affecting its data) to reshape the array and flatten the input matrix(4D) to a one-dimensional matrix.

  • 打印输入矩阵的结果扁平化矩阵。

示例

下面的程序使用reshape()函数将给定的4维矩阵扁平化为一个1维矩阵,并返回结果 -

# importing numpy module with an alias name
import numpy as np

# creating a 4-Dimensional(4x4) numpy matrix
inputMatrix = np.array([[1, 2, 3, 97],
   [4, 5, 6, 98],
   [7, 8, 9, 99],
   [10, 11, 12, 100]])

# Getting the total Number of elements of the matrix
matrixSize = len(inputMatrix) * len(inputMatrix)

# printing the input 4D matrix
print("The input numpy matrix:")
print(inputMatrix)

# reshaping the array and flattening the 4D matrix to a one-dimensional matrix

# here (1,matrixSize(16)) says 1 row and 16 columns(Number of elements)
flattenMatrix= np.reshape(inputMatrix, (1, matrixSize))

# printing the resultant flattened matrix
print("Resultant flattened matrix:")
print(flattenMatrix)

Output

在执行时,上述程序将生成以下输出 -

The input numpy matrix:
[[  1   2   3  97]
 [  4   5   6  98]
 [  7   8   9  99]
 [ 10  11  12 100]]
Resultant flattened matrix:
[[  1   2   3  97   4   5   6  98   7   8   9  99  10  11  12 100]]

Method 3 − Flattening 4x4 Numpy Matrix of np.matrix() type

的中文翻译为:

方法3-将np.matrix()类型的4x4 Numpy矩阵展平

Algorithm (Steps)

以下是执行所需任务的算法/步骤:

  • 使用numpy.matrix()函数(从数据字符串或类似数组的对象返回一个矩阵。生成的矩阵是一个专门的4D数组),通过将4维数组(4行,4列)作为参数传递给它来创建一个numpy矩阵。

  • 打印输入矩阵的结果扁平化矩阵。

示例

以下程序使用flatten()函数将给定的4维矩阵展平为1维矩阵,并返回结果 -

# importing NumPy module with an alias name
import numpy as np

# creating a NumPy matrix (4x4 matrix) using matrix() method
inputMatrix = np.matrix('[11, 1, 8, 2; 11, 3, 9 ,1; 1, 2, 3, 4; 9, 8, 7, 6]')

# printing the input 4D matrix
print("The input numpy matrix:")
print(inputMatrix)

# flattening the 4D matrix to one-dimensional matrix
flattenMatrix = inputMatrix.flatten()

# printing the resultant flattened matrix
print("Resultant flattened matrix:")
print(flattenMatrix)

Output

在执行时,上述程序将生成以下输出 -

The input numpy matrix:
[[11  1  8  2]
 [11  3  9  1]
 [ 1  2  3  4]
 [ 9  8  7  6]]
Resultant flattened matrix:
[[11  1  8  2 11  3  9  1  1  2  3  4  9  8  7  6]]

Conclusion

在这篇文章中,我们学习了如何使用三个不同的示例在Python中展平矩阵。我们学习了如何使用两种不同的方法在Numpy中获取矩阵:numpy.array()和NumPy.matrix()。我们还学习了如何使用reshape函数展平矩阵。

Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!

相关文章

python速学教程(入门到精通)
python速学教程(入门到精通)

python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
Tailwind CSS 响应式布局怎么写
Tailwind CSS 响应式布局怎么写

Tailwind CSS 响应式布局通常从移动端样式写起,再用 sm、md、lg 等前缀调整不同屏幕宽度下的网格、间距和导航。本专题整理断点配置、Grid 与 Flex 自适应布局及常见溢出问题,帮助你逐步完成多设备适配。

2026.11.03

0

19

Tailwind CSS 常用类名怎么记
Tailwind CSS 常用类名怎么记

Tailwind CSS 类名很多,先按布局、间距、文字、颜色和状态分组记忆,再通过官方文档检索具体写法。本专题结合类名排序、动态拼接失效、自定义实用类等问题,帮助你建立常用类名的速查方法。

2026.11.03

0

12

码上飞入口地址合集
码上飞入口地址合集

本专题汇总了码上飞(CodeFlying)的官方入口地址合集,涵盖官网主站及网页版在线使用入口,支持注册登录后直接在线体验零代码AI应用生成。同时整理了APP端下载渠道与小程序入口,助你快速访问平台,通过自然语言描述需求即可生成应用、小程序或网站。

2026.11.03

0

10

Uvicorn 报错与问题解决教程
Uvicorn 报错与问题解决教程

本专题汇总了Uvicorn服务器常见问题与报错解决的教程合集,涵盖启动失败、端口占用、模块导入错误、事件循环冲突及热重载失效等典型故障的排查思路。同时整理了多进程与Worker配置、SSL/HTTPS证书报错、跨域与代理配置等实战解决方案,助你快速定位并解决Uvicorn运行中的各类问题。

2026.11.02

20

14

Uvicorn使用教程
Uvicorn使用教程

本专题汇总了Uvicorn使用教程与启动运行指南,涵盖其作为Python ASGI服务器的定位与特点,以及命令行启动(uvicorn main:app --reload)、参数配置(host/port/workers)、程序内嵌运行与Gunicorn结合部署等核心用法。同时整理了热重载调试、日志配置与生产环境部署优化等技巧,助你快速掌握Uvicorn的运行与配置。

2026.11.02

20

17

Uvicorn安装配置教程
Uvicorn安装配置教程

本专题汇总了Uvicorn的安装配置教程与部署指南,涵盖通过pip安装Uvicorn、启动FastAPI/Starlette应用、开发模式热重载(--reload)及多进程工作模式配置等核心操作。同时整理了结合Gunicorn的生产部署方案、HTTPS与反向代理配置及性能调优技巧,助你快速完成Uvicorn服务的安装与上线部署。

2026.11.02

20

17

Vite 项目如何打包和部署
Vite 项目如何打包和部署

Vite项目打包部署专题汇集生产构建、产物预览、输出目录、资源路径、Nginx与GitHub Pages部署及常见白屏和路由404问题的已审核文章,帮助读者完成上线流程。

2026.10.28

120

16

Vite 如何搭配 Vue.js
Vite 如何搭配 Vue.js

Vite搭配Vue.js专题汇集创建Vue 3项目、配置开发环境、路径别名、Vue插件、代理、多环境构建与调试的已审核文章,帮助读者完成从初始化到日常开发的配置。

2026.10.28

100

15

Vite 项目目录怎么看
Vite 项目目录怎么看

Vite项目目录专题汇集入口文件、src源码、public静态资源、路径别名、项目根目录和构建输出目录相关的已审核文章,帮助读者理解各文件夹的用途与引用方式。

2026.10.28

300

10

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
NumPy 官方文档与用户指南
NumPy 官方文档与用户指南

共0课时 | 0人学习

SciPy 教程
SciPy 教程

共10课时 | 4.2万人学习