[Tutor] Writing elements of an array to a file using CSV module

Evert Rol evert.rol at gmail.com
Thu Oct 14 10:28:19 CEST 2010


> I have a numpy array ('data') that is the result of reading a netCDF
> file, and it typically looks like this:
> 
> array([ 0.,  0.,  0.,  0.], dtype=float32)
> 
> 
> I want to write this, after a date and time, to a CSV file, so the CSV
> file would have the entry:
> 
>    2000-02-01,09:00,0.0,0.0,0.0,0.0
> 
> 
> The code I'm using to test it, is:
> 
> # file_details[0] is the date and file_details[1] is the time
> writer.writerow(('%s' % (file_details[0]),'%s' %
> (file_details[1]),'%f' % (data[0])))
> 
> 
> In my opinion, this should give an output line:
> 
> 2000-02-01,09:00,0.0
> 
> 
> Instead, I get an error
> 
> TypeError: float argument required, not numpy.ndarray
> 
> 
> 
> Can someone please explain to me why data[0] is giving a numpy array
> rather than one element? I don't understand it, since I get:
> 
>>>> data[0]
> 0.0

This means very little, since a string '0.0' will show the same output when printed:
>>> print '0.0'
0.0

The exception says 'TypeError', so try:

>>> type(data[0])
<type 'numpy.float32'>

Which is indeed what you specified at the start using dtype=float32.

The standard string formatting doesn't know what to do with a numpy.float32, so you'll need to convert it to a float:

>>> '%f' % float(data[0])
'0.000000'

(use proper float formatting to get at '0.0', which is what you apparently want.)


  Evert



More information about the Tutor mailing list