[SciPy-user] io.read_array with strings

Vincent Nijs v-nijs@kellogg.northwestern....
Thu Feb 22 14:45:26 CST 2007


Charles,

You could read-in the array using python's csv module. This will return an
array of strings. Then loop through each column and convert to an
appropriate type using something like:

def csvconvert(col):
    try: 
        return col.astype('i')
    except ValueError:
        try: 
            return col.astype('f')
        except ValueError:
            return col

The issue is how to store the returned columns. A normal array can, as far
as I know, only hold one data type. You could use a recarray or store the
data in a dictionary.

I have used both approaches in a data base class I posted on the cookbook
page:

http://www.scipy.org/Cookbook/dbase

Vincent



On 2/22/07 12:51 PM, "Charles-Antoine Robelin" <car@melix.org> wrote:

> I have been using io.read_array successfully to read ASCII
> files containing integers and floats, and I would like to
> import strings into arrays as well.
> 
> I tried with io.read_array, but did not get it to work:
> If I create an array manually (i.e., numpy.array([['a1',
> 'd3', 'gg'],['wq', 'ty', 'e']])), the type (dtype) of its
> elements is '|S4', so I suspect numpy.arrays can handle
> strings.
> 
> However, io.read_array(<filename>, separator=',') on the
> following file:
> a1, d3, gg
> wq, ty, e
> returns an array of floats with the correct shape,
> containing the numbers it could find (a1 -> 1.; d3 -> 3.)
> and 0. where no number could be found.
> I could not find how to force the type "strings," such as
> atype='<strings>' in the call of read_array.
> 
> Is importing strings possible with io.read_array, or with
> another function, without having to parse manually?
> 
> Thanks in advance.
> _______________________________________________
> SciPy-user mailing list
> SciPy-user@scipy.org
> http://projects.scipy.org/mailman/listinfo/scipy-user
> 

-- 





More information about the SciPy-user mailing list