【发布时间】:2015-11-13 16:39:09
【问题描述】:
我必须启动大量计算,并且每次都必须保存一个 2D 文件文本,所以我想将结果“实时”存储为 3D 文本文件,每个切片对应一个计算结果。
第一次计算是可以的,但是当我进行第二次计算时,在“np.loadtxt”步骤中,数组维度变成了二维......所以我无法达到我的目标......而且我不能当我开始尺寸(...,...,1)时进行重塑
#MY FIRST RESULTS
test1 = open("C:/test.txt", "r")
test_r = np.genfromtxt(test, skip_header=1)
test_r = np.expand_dims(test_r, axis=2) #I create a new axis to save in 3D
test1.close()
#I test if the "Store" file to keep all my results is created.
try:
Store= np.loadtxt('C:/Store.txt')
except:
test=1
#If "Store" is not created, I do it or I concatenate in my file.
if test ==1:
Store= test_r
np.savetxt('C:/Store.txt', Store)
test=2
else:
Store = np.concatenate((Store,test_r), axis=2)
np.savetxt('C:/Store.txt', Store)
#MY SECOND RESULTS
test2 = open("C:/test.txt", "r")
test_r = np.genfromtxt(test, skip_header=1)
test_r = np.expand_dims(test_r, axis=2)
test2.close()
#I launch the procedure again to "save" the results BUT DURING THE LOADTXT STEP THE ARRAY DIMENSIONS CHANGE TO BECOME A 2D ARRAY...
try:
Store= np.loadtxt('C:/Store.txt')
except:
test=1
if test ==1:
Store= test_r
np.savetxt('C:/Store.txt', Store)
test=2
else:
Store = np.concatenate((Store,test_r), axis=2)
np.savetxt('C:/Store.txt', Store)
【问题讨论】:
-
也许您更感兴趣的是使用可以轻松保存/加载任何 Python 对象的 Pickle 模块?
-
我不知道,我会检查一下;)谢谢你有例子吗?我正在寻找那个
-
根据您的用例,您可能能够摆脱与我最近在工作中所做的类似的事情。获取您的 numpy 数组,转换为普通的 python 列表并将其填充到 JSON 文件中。 JSON 是高度可移植的,您可以从那里读取您的数组。正如 Baruchel 提到的,有一些方法可以以二进制形式(例如 pickle)存储您的 numpy 数据。 Numpy 也为此内置了函数(列表顶部的前两个模块 docs.scipy.org/doc/numpy-1.10.0/reference/routines.io.html)
标签: python arrays numpy text concatenation