搜索
首页后端开发Python教程如何使用numpy在Python中展平一个矩阵?

如何使用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

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

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函数展平矩阵。

以上是如何使用numpy在Python中展平一个矩阵?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:tutorialspoint。如有侵权,请联系admin@php.cn删除
2小时的Python计划:一种现实的方法2小时的Python计划:一种现实的方法Apr 11, 2025 am 12:04 AM

2小时内可以学会Python的基本编程概念和技能。1.学习变量和数据类型,2.掌握控制流(条件语句和循环),3.理解函数的定义和使用,4.通过简单示例和代码片段快速上手Python编程。

Python:探索其主要应用程序Python:探索其主要应用程序Apr 10, 2025 am 09:41 AM

Python在web开发、数据科学、机器学习、自动化和脚本编写等领域有广泛应用。1)在web开发中,Django和Flask框架简化了开发过程。2)数据科学和机器学习领域,NumPy、Pandas、Scikit-learn和TensorFlow库提供了强大支持。3)自动化和脚本编写方面,Python适用于自动化测试和系统管理等任务。

您可以在2小时内学到多少python?您可以在2小时内学到多少python?Apr 09, 2025 pm 04:33 PM

两小时内可以学到Python的基础知识。1.学习变量和数据类型,2.掌握控制结构如if语句和循环,3.了解函数的定义和使用。这些将帮助你开始编写简单的Python程序。

如何在10小时内通过项目和问题驱动的方式教计算机小白编程基础?如何在10小时内通过项目和问题驱动的方式教计算机小白编程基础?Apr 02, 2025 am 07:18 AM

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

如何在使用 Fiddler Everywhere 进行中间人读取时避免被浏览器检测到?如何在使用 Fiddler Everywhere 进行中间人读取时避免被浏览器检测到?Apr 02, 2025 am 07:15 AM

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

Python 3.6加载Pickle文件报错"__builtin__"模块未找到怎么办?Python 3.6加载Pickle文件报错"__builtin__"模块未找到怎么办?Apr 02, 2025 am 07:12 AM

Python3.6环境下加载Pickle文件报错:ModuleNotFoundError:Nomodulenamed...

如何提高jieba分词在景区评论分析中的准确性?如何提高jieba分词在景区评论分析中的准确性?Apr 02, 2025 am 07:09 AM

如何解决jieba分词在景区评论分析中的问题?当我们在进行景区评论分析时,往往会使用jieba分词工具来处理文�...

如何使用正则表达式匹配到第一个闭合标签就停止?如何使用正则表达式匹配到第一个闭合标签就停止?Apr 02, 2025 am 07:06 AM

如何使用正则表达式匹配到第一个闭合标签就停止?在处理HTML或其他标记语言时,常常需要使用正则表达式来�...

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器