简体   繁体   中英

Creating columns with numpy Python

I have some elements stored in numpy.array[] . I wish to store them in a ".txt" file. The case is it needs to fit a certain standard, which means each element needs to be stored x lines into the file.

Example:

numpy.array[0] needs to start in line 1, col 26.

numpy.array[1] needs to start in line 1, col 34.

I use numpy.savetxt() to save the arrays to file.

Later I will implement this in a loop to create a lagre ".txt" file with coordinates.

Edit: This good example was provided below, it does point out my struggle:

 In [117]: np.savetxt('test.txt',A.T,'%20d %10d')
 In [118]: cat test.txt
                   0          6
                   1          7
                   2          8
                   3          9
                   4         10
                   5         11

The fmt option '%20d %10d' gives you spacing which depend on the last integer. What I need is an option which lets me set the spacing from the left side regardless of other integers.

Template is need to fit integers into: XXXXXXXX.XXX YYYYYYY.YYY ZZZZ.ZZZ


Final Edit:

I solved it by creating a test which checks how many spaces the last float used. I was then able to predict the number of spaces the next float needed to fit the template.

Have you played with the fmt of np.savetxt ?

Let me illustrate with a concrete example (the sort that you should have given us)

Make a 2 row array:

In [111]: A=np.arange((12)).reshape(2,6)
In [112]: A
Out[112]: 
array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11]])

Save it, and get 2 rows, 6 columns

In [113]: np.savetxt('test.txt',A,'%d')
In [114]: cat test.txt
0 1 2 3 4 5
6 7 8 9 10 11

save its transpose, and get 6 rows, 2 columns

In [115]: np.savetxt('test.txt',A.T,'%d')
In [116]: cat test.txt
0 6
1 7
2 8
3 9
4 10
5 11

Put more detail into fmt to space out the columns

In [117]: np.savetxt('test.txt',A.T,'%20d %10d')
In [118]: cat test.txt
                   0          6
                   1          7
                   2          8
                   3          9
                   4         10
                   5         11

I think you can figure out how to make a fmt string that puts your numbers in the correct columns (join 26 spaces etc, or use left and right justification - the usual Python formatting issues).

savetxt also takes an opened file. So you can open a file for writing, write one array, add some filler lines, and write another. Also, savetxt doesn't do anything fancy. It just iterates through the rows of the array, and writes each row to a line, eg

 for row in A:
     file.write(fmt % tuple(row))

So if you don't like the control that savetxt gives you, write the file directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM