Paul Menzel wrote: > Dear NumPy folks, > > > is there an easy way to also save the indexes of an array (columns, rows > or both) when outputting it to a text file. For saving an array to a > file I only found `savetxt()` [1] which does not seem to have such an > option. Adding indexes manually is doable but I would like to avoid > that. > > --- minimal example (also attached) --- > from numpy import * > > a = zeros([2, 3], int) > print(a) > > savetxt("/tmp/test1.txt", a, fmt='%8i') > > # Work around for adding the indexes for the columns. > a[0] = range(3) > print(a) > > savetxt("/tmp/test2.txt", a, fmt='%8i') > --- minimal example --- > > The output is the following. > > $ python output-array.py > [[0 0 0] > [0 0 0]] > [[0 1 2] > [0 0 0]] > $ more /tmp/test* > :::::::::::::: > /tmp/test1.txt > :::::::::::::: > 0 0 0 > 0 0 0 > :::::::::::::: > /tmp/test2.txt > :::::::::::::: > 0 1 2 > 0 0 0 > > Is there a way to accomplish that task without reserving the 0th row or > column to store the indexes? > > I want to process these text files to produce graphs and MetaPost’s [2] > graph package needs these indexes. (I know about Matplotlib [3], but I > would like to use MetaPost.) > > > Thanks, > > Paul > > > [1] http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html > [2] http://wiki.contextgarden.net/MetaPost > [3] http://matplotlib.sourceforge.net/ > > ------------------------------------------------------------------------ > > _______________________________________________ > NumPy-Discussion mailing list > NumPy-Discussion@scipy.org > http://mail.scipy.org/mailman/listinfo/numpy-discussion Paul,
I don't know of any numpy function which will output the array indexes but with numpy's ndindex this can be accomplished with a for loop. import numpy as np a = np.arange(12).reshape(3,4) f = open("test.txt",'w') for i in np.ndindex(a.shape): print >> f," ".join([str[s] for s in i]),a[i] f.close() cat test.txt 0 0 0 0 1 1 0 2 2 ... _______________________________________________ NumPy-Discussion mailing list NumPy-Discussion@scipy.org http://mail.scipy.org/mailman/listinfo/numpy-discussion