How to make a numpy recarray with datatypes (datetime,float)?
Question
Let's say I have some simple data
y = [[datetime.datetime( 2012,1,1,1,1), 2.1],
[datetime.datetime( 2012,1,1,1,2), -3.1],
[datetime.datetime( 2012,1,1,1,3), 0.1]]
and I want a numpy record array corresponding to it. It would seem I ought to be able to do this:
np.rec.array( y, dtype=[('timestamp', object),('x','f')] )
or this
np.rec.array( y, dtype=[('timestamp', '|O8'),('x','f')] )
or maybe this
np.rec.array( y, dtype=[('timestamp', 'V'),('x','f')] )
But each of them returns an error, either
ValueError: Setting void-array with object members using buffer.
or
TypeError: expected a readable buffer object
So how exactly can I set this up, assuming it is even possible?
Solution
You can use tuples instead of lists for the records:
>> y = [(datetime.datetime( 2012,1,1,1,1), 2.1),
... (datetime.datetime( 2012,1,1,1,2), -3.1),
... (datetime.datetime( 2012,1,1,1,3), 0.1)]
>> np.rec.array(y, dtype=[('timestamp', object), ('x','f')])
rec.array([(datetime.datetime(2012, 1, 1, 1, 1), 2.0999999046325684),
(datetime.datetime(2012, 1, 1, 1, 2), -3.0999999046325684),
(datetime.datetime(2012, 1, 1, 1, 3), 0.10000000149011612)],
dtype=[('timestamp', '|O8'), ('x', '<f4')])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow