I am looking for some pointers on how to format float numbers in a numpy array. This code selects lines from an array, and I want the output to look better so I can import into excel.

infile looks like this:
1074 CL 006 2004 A8LGPUYE 10 TY 2 S0111P 2

from numpy import *



infile = open("C:\Python25\Drew\idage.txt", 'r')   
outfile= open("CLrcwarray.txt",'w')


rcw = infile.readlines()
bird_a = []
known = []
ct=0
CLrcw=zeros((4813,5),float)    
for record in rcw:
    
    bird = record.strip().split()

    nID=int(bird[0])
    ter=int(bird[2])
    year=int(bird[3])
##    status=int(bird[5])
    fled=int(bird[9])
    age=float(bird[7])

    CLrcw[ct,0]=nID
    CLrcw[ct,1]=ter
    CLrcw[ct,2]=year
    CLrcw[ct,3]=fled
    CLrcw[ct,4]=age
    
    ct+=1
 
for each in CLrcw:
    age2 = each[4]
    if age2 > 0:
        outfile.writelines("%s \n" %(each))

So the output puts the last item of the array on the next line and I need it all on the same line.
outfile:

[ 1.07400000e+03 6.00000000e+00 2.00400000e+03 2.00000000e+00
2.00000000e+00]

I also would like to the numbers with less zeros where it would be easier to read.

Two thoughts.

(1) You're writing code as if it were C or Pascal. A better way is to write a class:

class Bird(object):

    def __init__(self, nID=0, ter=0, year=0, fled=0, age=0.0):
        self.nID = nID
        self.ter = ter
        self.year = year
        self.fled = fled
        self.age = age

    def from_line(self, string):
        items = string.strip().split()
        if len(items) != 9:
            raise ValueError, "Cannot parse line: %s" % string
        else:
            self.nID = items[0]
            self.ter = items[2]
            self.year = items[3]
            self.fled = items[9]
            self.age = items[7]
... # etc.

The point is that you can then test your class and forget about its operation.

And, you won't need numpy arrays anymore, since you can just maintain a list of objects.

Second thought:

If you do create the Bird class, then you can create a __str__() method for it that will properly format the way you want. Like this:

...
def __str__(self):
   s = "nID: %d  ter: %d  year: %d  fled: %d  age: %0.1f" % (self.nID, self.ter, self.year, self.fled, self.age)
   return s

and then your main code would go:

for each in CLrcw:
    if each.age > 0:
        outfile.writelines(str(each))

Hope that helps,
Jeff

Thanks so much jrcagle,
I appreciate the advice. I'm still trying to figure out classes but I think you got me going in the right direction.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.