How to make a numpy recarray with datatypes (datetime,float)?
Asked Answered
S

1

8

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?

Stream answered 5/4, 2012 at 16:57 Comment(0)
C
6

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')])
Conformal answered 5/4, 2012 at 17:28 Comment(1)
Holy smokes, it's that simple. Thanks!Stream

© 2022 - 2024 — McMap. All rights reserved.