[SciPy-User] numpy: loadtxt with default value

Andreas Matthias andreas.matthias at gmail.com
Sat Aug 15 16:50:19 EDT 2009


Pierre GM wrote:

> On Aug 15, 2009, at 4:11 PM, Andreas Matthias wrote:
> 
>> The documentation of numpy.loadtxt says that the `converters'
>> parameter can be used to provide a default value for missing
>> data. However the following doesn't work.
>> 
>> 
>> import numpy as np
>> from StringIO import StringIO
>> 
>> s = StringIO('111  222')
>> a = np.loadtxt(s,
>>               dtype = {'names': ('a', 'b', 'c'),
>>                        'formats': (float, float, float)},
>>               converters = {2: lambda s: float(s or 0)}
>>               )
>> 
>> 
>> What's wrong with this code?
> 
> You have only 2 columns in s, and gave the converter (and name and  
> format) for a third one ?

Yes. This was intended. This should be the case of a "default
value for missing data" as described in the documentation

    converters : {}
        A dictionary mapping column number to a function that will convert
        that column to a float.  E.g., if column 0 is a date string:
        ``converters = {0: datestr2num}``. Converters can also be used to
        provide a default value for missing data:
        ``converters = {3: lambda s: float(s or 0)}``.


Ciao
Andreas




More information about the SciPy-User mailing list