Reputation: 814
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?
Upvotes: 0
Views: 206
Reputation: 250951
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')])
Upvotes: 2