Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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?

share|improve this question
up vote 2 down vote accepted

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')])
share|improve this answer
    
Or io.StringIO for Python 3 – bountiful Mar 17 '14 at 15:03
    
@fophillips Indeed. ;-) – Ashwini Chaudhary Mar 17 '14 at 15:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.