1

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.

1
  • results is turned into an array before saving. Try that yourself to see what the formatting has to work with. Commented Sep 19, 2018 at 14:16

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Why is that I'm able to use %i and %f together without any issue? Or is my entire array being coerced into floats so that I can have that one float column?
Also, I found this link really helpful for building a structured array: docs.scipy.org/doc/numpy/user/basics.rec.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.