I am trying to create an array of integers from a list of strings to do some calculations, but all I can get is an array of strings or an error.
Does numpy have any functions to do this? any help at all would be much appreciated.

infile:
23 CL 006 2004 DBA8ORPU 41 8Y 0 S0111P 2
53 CL 006 2004 LBA8PUYE 32 10Y 0 S0111P 2
39 CL 006 2004 A8LGPUYE 10 TY 2 S0111P 2

from numpy import *

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

rcw = infile.readlines()

for record in rcw:
    bird = record.strip().split()
    a = array('f',[bird[0],bird[2],bird[3],bird[5],bird[9],bird[7]])
    
    print a

Traceback (most recent call last):
File "C:\Python25\Drew\agecal.py", line 23, in <module>
a = array('f',[bird[0],bird[2],bird[3],bird[5],bird[9],bird[7]])
TypeError: data type not understood

without the 'f' (which I wanted to indicate floating point) I get the following array of strings:

a = array('f',[bird[0],bird[2],bird[3],bird[5],bird[9],bird[7]])

Doesn't the 'f' come second in the numpy.array() call?

BearofNH is right the correct usage is ...

import numpy

qq = [1, 2, 3]
ar = numpy.array(qq, dtype='f')
print(ar)  # [ 1.  2.  3.]

It is always easy to run a little test program.
It might also be easier to use something like this ...

qq = [x for x in bird if x.isdigit()]

So here is the solution I came up with to convert the strings to integers.

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.write("%s \n" %(each))

My results look like this :
[ 1.07400000e+03 6.00000000e+00 2.00400000e+03 2.00000000e+00
2.00000000e+00]
[ 1.69000000e+02 7.00000000e+00 2.00400000e+03 2.00000000e+00
2.00000000e+00]

Take a look at:
help(numpy.set_printoptions)

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.