Specific Column Widths And Alignment With Savetxt
I'm nearly finished with this program, but I can't get the output quite how I want it. Here is the code: import numpy as np filename = (raw_input('Which file are we loading? '))
Solution 1:
You can make different formats for each column by passing a sequence to the 'fmt' keyword argument. Three examples below show different options. More info available at docs.scipy.org.
>>>import numpy as np>>>a = np.random.random((3,4))>>>a[1] = a[1] + 10>>>a
array([[ 0.66860114, 0.29021582, 0.47168711, 0.86839242],
[ 10.41030497, 10.22771623, 10.80389801, 10.6170771 ],
[ 0.47201727, 0.90861352, 0.03952651, 0.67245859]])
>>>>>># saved using string format>>>>>>np.savetxt('string.txt', a, fmt='%s')>>>withopen('string.txt','r') as f: print(f.read())...
0.668601144977 0.290215822112 0.471687110847 0.86839242197
10.4103049716 10.2277162318 10.8038980106 10.617077099
0.472017270547 0.9086135154 0.0395265080276 0.672458588797
>>>>>># saved using floating format with the "width" parameter = 10>>>>>>np.savetxt('fixed.txt',a, fmt='%10.4f')>>>withopen('fixed.txt','r') as f: print(f.read())...
0.6686 0.2902 0.4717 0.8684
10.4103 10.2277 10.8039 10.6171
0.4720 0.9086 0.0395 0.6725
>>>>>># saved using format specifier sequence with format for each column>>>>>>np.savetxt('multi.txt',a, fmt=('%5.2f', '%10.4f', '%7.3f', '%12.1f'))>>>withopen('multi.txt','r') as f: print(f.read())...
0.67 0.2902 0.472 0.9
10.41 10.2277 10.804 10.6
0.47 0.9086 0.040 0.7
Solution 2:
What you want to achieve is a so called 'fixed-width' csv-file. Since neither numpy nor pandas is able to export data to a csv-file formatted like this you could do a workaround using the format specifier of numpy.savetext()
if you know the number of digits you have to handle:
#!/usr/bin/env python3# coding: utf-8import numpy as np
# generate a random array to get some sample data
newlist = np.random.rand(3,2)
# assume you have three decimal digits and seven in total (so four in front of the decimal sign)
np.savetxt('observe.list', newlist, fmt='%7.3f')
Giving:
0.021 0.571
0.471 0.416
0.177 0.720
Update due to comment:
newlist = np.array([1.5, 10.55555, 0.3, 2, 5.0])
np.savetxt('observe.list', newlist, fmt='%10.5f')
Giving:
1.50000
10.55555
0.30000
2.00000
5.00000
Post a Comment for "Specific Column Widths And Alignment With Savetxt"