0

I have a string formatted that looks like

contents = "1,2,3;\n4,5,6;"

Which I want to load into numpy record array with dtype

structure = {'names': ['foo', 'bar', 'baz'], 'formats': ['i4']*3}

To create something like

array([(1,2,3),
       (4,5,6)],
      dtype = [('foo', '<i4'), ('bar', '<i4'), ('baz', '<i4')])

But numpy.fromstring only supports 1D arrays, and I can't use numpy.loadtxt because it is not a file.

The documentation of numpy.loadtxt seems to suggest I can use a generator, so I have used the split generator detailed in this answer to create a generator and have done

np.loadtxt(itersplit(contents, sep=";"), delimiter=",", dtype=structure)

Is this the best way?

1 Answer 1

2

You can use StringIO.StringIO:

>>> from StringIO import StringIO
>>> c = StringIO(contents.replace(';', ''))
>>> np.loadtxt(c, delimiter=",", dtype=structure)
array([(1, 2, 3), (4, 5, 6)], 
      dtype=[('foo', '<i4'), ('bar', '<i4'), ('baz', '<i4')])
Sign up to request clarification or add additional context in comments.

2 Comments

Or io.StringIO for Python 3
@fophillips Indeed. ;-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.