Daniel
Daniel

Reputation: 1837

Numpy.savetxt formatting issue: adding a string column

I've narrowed my issue down to the following:

import numpy as np

out_file = "results.txt"
results = [[1,2,3,.4,"5"]] # just one row for testing
format = ['%i', '%i', '%i', '%f', '%s']

np.savetxt(out_file, results, format, '\t')

I'm just trying to save 5 columns of data: 3 ints, 1 float, and a string. When I attempt to so, I receive the error:

File ".\npyio.py", line 1391, in savetxt
    % (str(X.dtype), format))
TypeError: Mismatch between array dtype ('<U32') and format specifier ('%i      %i      %i      %f      %s')

The code works just fine if I remove the string format and the corresponding value in the array.

This feels like one of those times that I'm just doing something really stupid, but after a couple hours of fruitless googling I think I need help.

Upvotes: 1

Views: 723

Answers (1)

mannykoum
mannykoum

Reputation: 81

Normal numpy arrays have one datatype only. You could initialize the array with the dtype='O' Object type but it stil wouldn't work with savetxt().

The solution to your problem is a structured array as shown here.

Upvotes: 2

Related Questions