如何使用 savetxt() 和 loadtxt() 函数加载和保存 3D Numpy 数组到文件?
先决条件: numpy.savetxt()、numpy.loadtxt()
Numpy.savetxt()是Python中 numpy 库中的一种方法,用于将一维和二维数组保存到文件中。
Syntax: numpy.savetxt(fname, X, fmt=’%.18e’, delimiter=’ ‘, newline=’\n’, header=”, footer=”, comments=’# ‘, encoding=None)
numpy.loadtxt()是Python中 numpy 库中的一种方法,用于从文本文件加载数据以加快读取速度。
Syntax: numpy.loadtxt(fname, dtype=’float’, comments=’#’, delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0)
保存和加载 3D 数组
如前所述,我们只能在 numpy.savetxt() 中使用 1D 或 2D 数组,如果我们使用更多维度的数组,它将抛出ValueError – Expected 1D or 2D array, got 3D array。因此,我们需要找到一种方法来保存和检索,至少对于 3D 数组,以下是如何使用一些Python技巧来做到这一点。
- 第 1 步:将 3D 阵列重塑为 2D 阵列。
- 第 2 步:将此数组插入文件
- 第 3 步:从文件中加载数据以显示
- 第 4 步:转换回原始形状数组
例子:
Python3
import numpy as gfg
arr = gfg.random.rand(5, 4, 3)
# reshaping the array from 3D
# matrice to 2D matrice.
arr_reshaped = arr.reshape(arr.shape[0], -1)
# saving reshaped array to file.
gfg.savetxt("geekfile.txt", arr_reshaped)
# retrieving data from file.
loaded_arr = gfg.loadtxt("geekfile.txt")
# This loadedArr is a 2D array, therefore
# we need to convert it to the original
# array shape.reshaping to get original
# matrice with original shape.
load_original_arr = loaded_arr.reshape(
loaded_arr.shape[0], loaded_arr.shape[1] // arr.shape[2], arr.shape[2])
# check the shapes:
print("shape of arr: ", arr.shape)
print("shape of load_original_arr: ", load_original_arr.shape)
# check if both arrays are same or not:
if (load_original_arr == arr).all():
print("Yes, both the arrays are same")
else:
print("No, both the arrays are not same")
输出:
shape of arr: (5, 4, 3)
shape of load_original_arr: (5, 4, 3)
Yes, both the arrays are same