如何写一个multidimensional array到文本文件?

另一个问题,如果我能提供我遇到麻烦的arrays,其他用户提供了一些帮助。 但是,我甚至在基本的I / O任务上失败,比如将一个数组写入文件。

任何人都可以解释什么样的循环,我将需要写一个4x11x14 numpy数组文件?

这个数组由四个11×14的数组组成,所以我应该用一个漂亮的换行符来格式化,以使其他文件的读取更容易。

编辑 :所以我已经尝试了numpy.savetxt函数。 奇怪的是,它给出了以下错误:

TypeError: float argument required, not numpy.ndarray 

我认为这是因为该function不适用于multidimensional array? 任何解决scheme,我想他们在一个文件中?

如果你想把它写到磁盘上,这样就可以很容易地以一个numpy数组的forms读回来,看看numpy.save 。 酸洗它也能很好地工作,但是对于大型arrays来说效率较低(这不是你的,所以或者是非常好的)。

如果你想要它是人类可读的,看看numpy.savetxt

编辑:所以,似乎savetxt不是一个伟大的select数组> 2维…但只是为了得出全部的结论:

我刚刚意识到,在nndary上numpy.savetxt扼stream器超过2维…这可能是由devise,因为没有固有的方式来指示文本文件中的额外维度。

例如,这(二维数组)工作正常

 import numpy as np x = np.arange(20).reshape((4,5)) np.savetxt('test.txt', x) 

虽然同样的事情会失败(与一个相当无误的错误:types错误TypeError: float argument required, not numpy.ndarray )为3D数组:

 import numpy as np x = np.arange(200).reshape((4,5,10)) np.savetxt('test.txt', x) 

一种解决方法是将3D(或更大)的数组分割成2D切片。 例如

 x = np.arange(200).reshape((4,5,10)) with file('test.txt', 'w') as outfile: for slice_2d in x: np.savetxt(outfile, slice_2d) 

但是,我们的目标是清晰的读取人的内容,同时还可以通过numpy.loadtxt轻松读取。 因此,我们可以稍微详细一点,并使用注释掉的行来区分切片。 默认情况下, numpy.loadtxt将忽略任何以#开头的行(或者由comments kwarg指定的任何字符)。 (这看起来比实际上更详细…)

 import numpy as np # Generate some test data data = np.arange(200).reshape((4,5,10)) # Write the array to disk with file('test.txt', 'w') as outfile: # I'm writing a header here just for the sake of readability # Any line starting with "#" will be ignored by numpy.loadtxt outfile.write('# Array shape: {0}\n'.format(data.shape)) # Iterating through a ndimensional array produces slices along # the last axis. This is equivalent to data[i,:,:] in this case for data_slice in data: # The formatting string indicates that I'm writing out # the values in left-justified columns 7 characters in width # with 2 decimal places. np.savetxt(outfile, data_slice, fmt='%-7.2f') # Writing out a break to indicate different slices... outfile.write('# New slice\n') 

这产生:

 # Array shape: (4, 5, 10) 0.00 1.00 2.00 3.00 4.00 5.00 6.00 7.00 8.00 9.00 10.00 11.00 12.00 13.00 14.00 15.00 16.00 17.00 18.00 19.00 20.00 21.00 22.00 23.00 24.00 25.00 26.00 27.00 28.00 29.00 30.00 31.00 32.00 33.00 34.00 35.00 36.00 37.00 38.00 39.00 40.00 41.00 42.00 43.00 44.00 45.00 46.00 47.00 48.00 49.00 # New slice 50.00 51.00 52.00 53.00 54.00 55.00 56.00 57.00 58.00 59.00 60.00 61.00 62.00 63.00 64.00 65.00 66.00 67.00 68.00 69.00 70.00 71.00 72.00 73.00 74.00 75.00 76.00 77.00 78.00 79.00 80.00 81.00 82.00 83.00 84.00 85.00 86.00 87.00 88.00 89.00 90.00 91.00 92.00 93.00 94.00 95.00 96.00 97.00 98.00 99.00 # New slice 100.00 101.00 102.00 103.00 104.00 105.00 106.00 107.00 108.00 109.00 110.00 111.00 112.00 113.00 114.00 115.00 116.00 117.00 118.00 119.00 120.00 121.00 122.00 123.00 124.00 125.00 126.00 127.00 128.00 129.00 130.00 131.00 132.00 133.00 134.00 135.00 136.00 137.00 138.00 139.00 140.00 141.00 142.00 143.00 144.00 145.00 146.00 147.00 148.00 149.00 # New slice 150.00 151.00 152.00 153.00 154.00 155.00 156.00 157.00 158.00 159.00 160.00 161.00 162.00 163.00 164.00 165.00 166.00 167.00 168.00 169.00 170.00 171.00 172.00 173.00 174.00 175.00 176.00 177.00 178.00 179.00 180.00 181.00 182.00 183.00 184.00 185.00 186.00 187.00 188.00 189.00 190.00 191.00 192.00 193.00 194.00 195.00 196.00 197.00 198.00 199.00 # New slice 

只要我们知道原始数组的形状,就可以很容易地读回来。 我们可以做numpy.loadtxt('test.txt').reshape((4,5,10)) 。 作为一个例子(你可以做到这一点,我只是在详细说明事情):

 # Read the array from disk new_data = np.loadtxt('test.txt') # Note that this returned a 2D array! print new_data.shape # However, going back to 3D is easy if we know the # original shape of the array new_data = new_data.reshape((4,5,10)) # Just to check that they're the same... assert np.all(new_data == data) 

我不确定这是否符合您的要求,因为我认为您有兴趣使文件可以被人读取,但是如果这不是主要的问题,那就去pickle吧。

要保存它:

 import pickle my_data = {'a': [1, 2.0, 3, 4+6j], 'b': ('string', u'Unicode string'), 'c': None} output = open('data.pkl', 'wb') pickle.dump(data1, output) output.close() 

读回来:

 import pprint, pickle pkl_file = open('data.pkl', 'rb') data1 = pickle.load(pkl_file) pprint.pprint(data1) pkl_file.close() 

如果你不需要一个人类可读的输出,你可以尝试的另一个select是将数组保存为一个MATLAB .mat文件,这是一个结构化数组。 我鄙视MATLAB,但是我可以在很less的几行读写.mat的事实很方便。

与Joe Kington的回答不同,这样的好处是你不需要知道 .mat文件中原始数据的形状 ,也就是说在读入时不需要重塑。而且,与使用pickle不同, .mat文件可以可以通过MATLAB读取,也可能是其他一些程序/语言。

这里是一个例子:

 import numpy as np import scipy.io # Some test data x = np.arange(200).reshape((4,5,10)) # Specify the filename of the .mat file matfile = 'test_mat.mat' # Write the array to the mat file. For this to work, the array must be the value # corresponding to a key name of your choice in a dictionary scipy.io.savemat(matfile, mdict={'out': x}, oned_as='row') # For the above line, I specified the kwarg oned_as since python (2.7 with # numpy 1.6.1) throws a FutureWarning. Here, this isn't really necessary # since oned_as is a kwarg for dealing with 1-D arrays. # Now load in the data from the .mat that was just saved matdata = scipy.io.loadmat(matfile) # And just to check if the data is the same: assert np.all(x == matdata['out']) 

如果您忘记了在.mat文件中命名该数组的键,则始终可以这样做:

 print matdata.keys() 

当然,你可以使用更多的键存储许多arrays。

所以是的 – 用你的眼睛看不懂,但只需要2行来写和读数据,我认为这是一个公平的权衡。

看看scipy.io.savemat和scipy.io.loadmat以及本教程页面的文档: scipy.io File IO Tutorial

ndarray.tofile()也应该工作

例如,如果你的数组被称为a

 a.tofile('yourfile.txt',sep=" ",format="%s") 

不知道如何获得换行格式。

有专门的图书馆来做到这一点。 (加上python的包装)

  • netCDF4: http : //www.unidata.ucar.edu/software/netcdf/
  • netCDF4 Python界面: http : //www.unidata.ucar.edu/software/netcdf/software.html#Python

  • HDF5: http ://www.hdfgroup.org/HDF5/

希望这可以帮助

您可以简单地遍历三个嵌套循环中的数组,并将其值写入您的文件。 阅读,你只需使用相同的确切的循环结构。 您将按照正确的顺序获取值,以再次正确地填充arrays。

我有办法做一个简单的filename.write()操作。 它对我来说工作正常,但我正在处理有1500个数据元素的数组。

我基本上只是循环迭代通过文件,并将其写入输出目的地逐行csv样式输出。

 import numpy as np trial = np.genfromtxt("/extension/file.txt", dtype = str, delimiter = ",") with open("/extension/file.txt", "w") as f: for x in xrange(len(trial[:,1])): for y in range(num_of_columns): if y < num_of_columns-2: f.write(trial[x][y] + ",") elif y == num_of_columns-1: f.write(trial[x][y]) f.write("\n") 

if和elif语句用于在数据元素之间添加逗号。 无论出于何种原因,当读取文件为nd数组时,这些会被剥离。 我的目标是输出文件为csv,所以这个方法有助于处理。

希望这可以帮助!