[Numpy-discussion] using numpy.savetxt to save columns of numerical values and columns of text values

Skipper Seabold jsseabold at gmail.com
Fri Nov 27 01:44:49 EST 2009


On Fri, Nov 27, 2009 at 12:55 AM, Gökhan Sever <gokhansever at gmail.com> wrote:
>
>
> On Thu, Nov 26, 2009 at 11:30 PM, Richared Beare
> <richard.beare at sci.monash.edu.au> wrote:
>>
>> I have been unable to find a way of doing a very simple thing: saving
>> data that contains both arrays of numerical values and arrays of string
>> values, using savetxt in numpy.
>>
>> As a very simple example, suppose a is a numpy array of integers and b
>> is one containing strings, e.g.:
>>
>>    a = np.array([1,2,3])
>>
>>    b = np.array(['one', 'two', 'three'])
>>
>> The following call to savetxt:
>>
>>    savetxt('test.txt', transpose((a,b)), fmt='%i %s')
>>
>> produces the following error:
>>
>>    float argument required, not numpy.string_
>>

In [14]: np.transpose((a,b))
Out[14]:
array([['1', 'one'],
       ['2', 'two'],
       ['3', 'three']],
      dtype='|S8')

The ints get cast to strings by transpose.  You need a structured
array. This works but there may be an easier way to build the array.

ab = np.zeros(3, dtype=[('var1',float),('var2','a5')])
ab['var1'] = a
ab['var2'] = b
np.savetxt('test.txt', ab, fmt="%i %s")

hth,

Skipper

>> I don't have any problems if I mix integers and floats in the format
>> string, or save all values as strings, but I am completely unable to
>> save formatted numerical values and strings in different columns using
>> savetxt.
>>
>> There must be an easy solution!
>
> Seemingly savetxt('test.txt', transpose((a,b)), fmt='%s %s')  ; replacing
> the %i with %s works. However you can't control the output precision while
> saving the data into a file.
>
>>
>> Thank you.
>>
>> Richard Beare
>> _______________________________________________
>> NumPy-Discussion mailing list
>> NumPy-Discussion at scipy.org
>> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>
>
> --
> Gökhan
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>



More information about the NumPy-Discussion mailing list