在 Python 中将 3D 数组转换为 2D 数组
在本教程中,我们将讨论在 Python 中将 3D 数组转换为 2D 数组的方法。
在 Python 中使用 numpy.reshape()
函数将 3D 数组转换为 2D 数组
[numpy.reshape()
函数](numpy.reshape-NumPy v1.20 手册)更改数组形状而不更改其数据。numpy.reshape()
返回具有指定尺寸的数组。例如,如果我们有一个尺寸为 (4, 2, 2)
的 3D 数组,我们想将其转换为尺寸为 (4, 4)
的 2D 数组。
以下代码示例向我们展示了如何在 Python 中使用 numpy.reshape()
函数将尺寸为 (4, 2, 2)
的 3D 数组转换为尺寸为 (4, 4)
的 2D 数组。
import numpy
arr = numpy.array(
[[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]], [[12, 13], [14, 15]]]
)
newarr = arr.reshape(4, 2 * 2)
print(newarr)
输出:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
在上面的代码中,我们首先使用 numpy.array()
函数初始化 3D 数组 arr
,然后使用 numpy.reshape()
函数将其转换为 2D 数组 newarr
。
下面的代码示例演示了由于某种原因,如果我们不知道 3D 数组的确切尺寸,则可以执行相同操作的另一种方法。
import numpy
arr = numpy.array(
[[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]], [[12, 13], [14, 15]]]
)
newarr = arr.reshape(arr.shape[0], (arr.shape[1] * arr.shape[2]))
print(newarr)
输出:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
在上面的代码中,我们使用 numpy.shape()
函数指定 newarr
的尺寸。numpy.shape() 函数返回一个元组,其中包含数组每个维度中的元素。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串