MacSanhe
MacSanhe

Reputation: 2240

Python: Numpy Data IO, how to save data by different dtype for each column?

I am trying to use numpy.savetxt to dump data in to varieties of format for each column.

when data is

data = np.array([[1.111, 2.222, 3.333],
                 [4.444, 5.555, 6.666],
                 [7.777, 8.888, 9.999] ])
np.savetxt('data.txt', data, 
           fmt= ['%i', '%.2f', '%s'], ## <== 1st column, int, 2nd float, 3rd string
           delimiter = ',')

everything works fine. But when data is:

data = np.array([[1.111, 2.222, 'three'],
                 [4.444, 5.555, 'six'],
                 [7.777, 8.888, 'nine'] ])

np.savetxt('data.txt', data, 
           fmt= ['%i', '%.2f', '%s'], ## <== 1st column, int, 2nd float, 3rd string
           delimiter = ',')

it gives me a error that: fh.write(asbytes(format % tuple(row) + newline)) TypeError: %d format: a number is required, not numpy.string_

Anybody have a clue?

Upvotes: 3

Views: 1674

Answers (2)

Saullo G. P. Castro
Saullo G. P. Castro

Reputation: 58955

For integer the %d format option should be used instead of %i:

np.savetxt('test.txt', data, fmt=['%d', '%.2f', '%s'])

When loading the array you should also specify dtype properly:

np.genfromtxt('test.txt', dtype=[('col1', int), ('col2', float), ('col3', '|S8')])

Upvotes: 2

183.amir
183.amir

Reputation: 412

Looking at the array that you have created it looks like this:

array([['1.111', '2.222', 'three'],
   ['4.444', '5.555', 'six'],
   ['7.777', '8.888', 'nine']], 
  dtype='<U5')

As you can see all elements are strings and that is why you get that error. However, if you do something like this, it should work.

dt = np.dtype("f, f, U5")
data = np.array([(1.111, 2.222, 'three'), # notice that each row had to be a tuple in my case
             (4.444, 5.555, 'six'),
             (7.777, 8.888, 'nine')], dtype=dt)
np.savetxt('data.txt', data, 
           fmt= ['%i', '%.2f', '%s'], ## <== 1st column, int, 2nd float, 3rd string
           delimiter = ',')

More info about dtypes are here: Data Type Objects

Upvotes: 3

Related Questions