3

I want to set the character length of each element of numpy array that is written in a text file

The output which I am getting currently is:

99941     1 56765 56767 51785 51793     0     0     0     0

101150      1  59006  59005  51782  51783      0      0      0      0

As you see in above case as the numbers increase the columns are shifted.

But in ideal case the output should look like:

 99941      1  56765  56767  51785  51793      0      0      0      0

101150      1  59006  59005  51782  51783      0      0      0      0

Is there any way I can fix the character length of each element of numpy array so that it writes the elements from right to left after considering the element character length and keep the column formatting fixed?

This is the code snippet on which i am working.

def calculate(self, ElementNum1, ElementNum2):
    Angle = Function().Transformation(ElementNum1, ElementNum2)
    ElementInfo = Shell().getElement(ElementNum2)
    Card1 = np.array([0,0,0,0,0,0,0,0,0,0])
    Card1.itemset(0,(ElementInfo[0]))
    Card1.itemset(1,(ElementInfo[1]))
    Card1.itemset(2,(ElementInfo[2]))
    Card1.itemset(3,(ElementInfo[3]))
    Card1.itemset(4,(ElementInfo[4]))
    Card1.itemset(5,(ElementInfo[5]))
    return str(Card1)

def AngleSolution1(self,ElementPair):
    Pair = np.genfromtxt(ElementPair, dtype=int, comments='None', delimiter=', ')
    row = int(Pair.size/2)
    p = mp.Pool(processes=4)
    result = [p.apply_async(AngleCalculateFunction().calculate, args=(Pair[i][0], Pair[i][1])) for i in range(0, int(row/4))]
    Result = open('Angles.csv', "a")
    Result.write('\n'.join(map(str, ((((p.get()).replace('[','')).replace(']','')) for p in result))))
    Result.write('\n')
    Result.close()
    p.close()

There are certain performance issues as I am using the multiprocessing incorrectly, but its out of the scope of this discussion.

3
  • 1
    Yes, there is a fmt parameter in numpy.savetxt that you can use for that. Commented Oct 3, 2015 at 6:50
  • Thanks for the quick response cel. If I am opening and closing the txt file for each iteration I guess its an additional overhead. But if I could convert the array in string and then write it once in the text file it wouldn't have that overhead. Is there any other way to return this array as a string for each line for required output format? Commented Oct 3, 2015 at 7:05
  • Can you give us a minimal example how you currently write out your data? Commented Oct 3, 2015 at 7:16

2 Answers 2

2

You can do something like this:

#!/usr/bin/env python

import numpy as np

test_array=np.array([[99941,1,56765,56767,51785,51793,0,0,0,0],
                 [101150,1,59006,59005,51782,51783,0,0,0,0]])
np.savetxt("test.out",test_array, fmt='%-10s')

That should give you something like this as output:

99941      1          56765      56767      51785      51793      0          0          0          0         
101150     1          59006      59005      51782      51783      0          0          0          0         

The %-10s part specifies that that column should have a width of 10 characters, and to fill the remaining characters with spaces. A bit of warning: this prints a lot of extra spaces at the end of every line.

Sign up to request clarification or add additional context in comments.

Comments

1

np.savetxt formats one row at a time, and writes it to an open file.

In [536]: x
Out[536]: 
array([[ 99941,      1,  56765,  56767,  51785,  51793,      0,      0,
             0,      0],
       [101150,      1,  59006,  59005,  51782,  51783,      0,      0,
             0,      0]])

In effect, it is doing (using print instead of a file write of illustration purposes):

In [537]: fmt=' '.join(['%8d']*x.shape[1])
In [538]: for row in x:
    print(fmt%tuple(row))
   .....:     
   99941        1    56765    56767    51785    51793        0        0        0        0
  101150        1    59006    59005    51782    51783        0        0        0        0

Or if you'd like to collect all the lines in one string, you could append them to a list:

In [544]: astr = []
In [545]: for row in x:
    astr.append(fmt%tuple(row))
   .....:     
In [546]: print('\n'.join(astr))
   99941        1    56765    56767    51785    51793        0        0        0        0
  101150        1    59006    59005    51782    51783        0        0        0        0

Python object display (str(...)) routinely does this sort of line append and join.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.