I want to save each numpy array (A,B, and C) as column in a text file, delimited by space:
import numpy as np
A = np.array([5,7,8912,44])
B = np.array([5.7,7.45,8912.43,44.99])
C = np.array([15.7,17.45,18912.143,144.99])
np.savetxt('test.txt', (A, B, C), fmt='%s %s %s')
But I got following error:
ValueError: fmt has wrong number of % formats: %s %s %s
How to solve it?
np.savetxt('/tmp/test.txt', np.column_stack((A, B, C)), fmt='%s %s %s')
yields
5.0 5.7 15.7
7.0 7.45 17.45
8912.0 8912.43 18912.143
44.0 44.99 144.99
Note that fmt='%s'
produces the same result.
If you try
np.savetxt('/tmp/test.txt', (A, B, C))
you'll see that NumPy is writing each 1-D array on a separate line -- i.e. horizontally. Since fmt='%s %s %s'
is used as the format for each line, an error was raised since each line had 4 values.
We can get around that problem by passing a 2-D array, np.column_stack((A, B, C))
to np.savetxt
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With