Reputation: 696
Let's say I have two numpy
arrays x
and y
and I want to save them in a txt
with a tab as a delimiter (\t
) and their appropriate type (x
is a float
and y
is a integer
) and a certain format. For example:
import numpy as np
x=np.random.uniform(0.1,10.,4)
y=np.random.randint(10,size=4)
If I simply use np.savetxt('name.txt',(x,y))
, this is what I get:
6.111548206503401026e+00 4.208270401300298058e-01 5.914485954766230957e-01 6.652272388676337966e-01
6.027109785846696433e+00 1.024051075089774443e+01 3.358386699980072621e+01 7.652668778594046151e-01
But what I want is a row-wise txt
file, so I followed this solution:
numpy array to a file, np.savetxt
and bu using
np.savetxt('name.txt',np.vstack((x,y)).T,delimiter='\t')
I get:
2.640596763338360020e+00 4.000000000000000000e+00
8.693117057064670306e+00 4.000000000000000000e+00
3.891035166453641558e+00 6.000000000000000000e+00
9.044178202861068883e+00 2.000000000000000000e+00
Until here it is ok, but as I mentioned, I want the output to have the appropriate data type and some formatting, so I tried np.savetxt('name.txt',np.vstack((x,y)).T,fmt=('%7.2f,%5i'),delimiter='\
...: t')
, and what I get is:
2.64, 4
8.69, 4
3.89, 6
9.04, 2
which does have the appropriate format and data type, but which adds a ,
after the columns. Does anyone knows how to get rid of this ,
printed after the column?
Upvotes: 1
Views: 374
Reputation: 16958
The comma is in your fmt
string. Replace it with fmt='%7.2f %5i'
, like so:
np.savetxt('name.txt',np.vstack((x,y)).T,fmt='%7.2f %5i')
Note the tab delimiter (delimiter='\t'
) is not necessary as np.vstack((x,y)).T
fills only one column. If you want a tab between the values, change the format string to fmt='%7.2f \t%5i'
or alternatively:
np.savetxt('name.txt',np.vstack((x,y)).T,fmt=('%7.2f', '%5i'), delimiter='\t')
Upvotes: 2