Mark
Mark

Reputation: 389

How to use fmt in numpy savetxt to align information in each column

I found someone else's use of fmt and tried to adapt it to my purposes. However, I do not understand it, despite reading about it here: http://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html. I would like my data to be centered in each column in the text file that I am saving (or for it to look organized in some way, honestly I don't care as long as the columns are aligned in some way). Right now I get the first row left aligned and then there is an even amount of space between my data. Since each entry in my array is not of the same length, this causes the data to be offset. How can I align the entries in each column?

import numpy as np
my_list =['str123456789', 'str2', 'str3']
my_list2=[1,2458734750,3]
my_array=np.array(my_list)
my_array2=np.array(my_list2)
combined=np.column_stack([my_array,my_array2])
np.savetxt('test_file_name.txt', combined, fmt='{0: ^{1}}'.format("%s", 12))

It gives even amount of space between entires, but I want the entries aligned.

Left or right align is fine. One comment suggests using {0:<{1}} or {0:>{1}} in place of {0: ^{1}}; however, that is not aligning my data any differently.

I'm guessing that .format("%s", 12) makes each string 12 characters (adding whitespace characters when there are no characters), causing problems with alignment. However, if I write .format("%s"), I get an error. fmt='%s', was working, but again with no alignment.

Upvotes: 1

Views: 4967

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180502

You can do it without str.format:

np.savetxt('test_file_name.txt', combined, fmt="%-12s")

Output:

str123456789 1           
str2         2458734750  
str3         3           

- is left aligned and 12 is the width. You need to specify a width as long or longer than the longest element in your array.

To explain your own attempt, you are centering the data with ^ with a minimum width of 12 characters but that will not align each column.

Upvotes: 7

Related Questions