how can I get python's np.savetxt to save each iteration of a loop in a different column? -
this extremely basic code want... except regard writing of text file.
import numpy np f = open("..\myfile.txt", 'w') tst = np.random.random(5) tst2 = tst/3 in range(3): j in range(5): test = np.random.random(5)+j = np.random.normal(test, tst2) np.savetxt(f, np.transpose(a), fmt='%10.2f') print f.close()
this code write .txt file single column concatenated after each iteration of loop.
what want independent columns each iteration.
how 1 that?
note: have used np.c_[]
well, , will write columns if express each iteration within command. ie: np.c_[a[0],a[1]]
, on. problem whit is, if both i
, j
values large? isn't reasonable follow method.
so run produces:
2218:~/mypy$ python3 stack39114780.py [ 4.13312217 4.34823388 4.92073836 4.6214074 4.07212495] [ 4.39911371 5.15256451 4.97868452 3.97355995 4.96236119] [ 3.82737975 4.54634489 3.99827574 4.44644041 3.54771411] 2218:~/mypy$ cat myfile.txt 4.13 4.35 4.92 4.62 4.07 # end of 1st iteration 4.40 5.15 4.98 3.97 ....
do understand what's going on? 1 call savetxt
writes set of lines. 1d array a
prints 1 number per row. (transpose(a)
doesn't anything).
file writing done line line, , can't rewound add columns. make multiple columns need create array multiple columns. 1 savetxt
. in other words, collect data before writing.
collect values in list, make array, , write that
alist = [] in range(3): j in range(5): test = np.random.random(5)+j = np.random.normal(test, tst2) alist.append(a) arr = np.array(alist) print(arr) np.savetxt('myfile.txt', arr, fmt='%10.2f')
i'm getting 15 rows of 5 columns, can tweak that.
2226:~/mypy$ cat myfile.txt 0.74 0.60 0.29 0.74 0.62 1.72 1.62 1.12 1.95 1.13 2.19 2.55 2.72 2.33 2.65 3.88 3.82 3.63 3.58 3.48 4.59 4.16 4.05 4.26 4.39
since arr
2d, np.transpose(arr)
meaningful - 5 rows 15 columns.
==================
with
for in range(3): j in range(5): test = np.random.random(5)+j = np.random.normal(test, tst2) np.savetxt(f, np.transpose(a), fmt='%10.2f')
you write a
once each i
- hence 3 rows. throwing away 4 of j
iterations. in variation collect a
, , hence 15 rows.
Comments
Post a Comment