简体   繁体   中英

How to convert a dictionary with datetime objects as keys and numpy arrays as values to 2D numpy array?

I have a dictionary of keys and values that look like this:

datetime.datetime(2014, 7, 6, 22, 48, 53): array([ -2.88907517e-04, 1.69103129e-01,  -7.10729251e-01, ..., 2.88580034e+07,  -7.24711607e+07,  -2.38548542e+07])}

I need to pass these values to a function, and therefore a new numpy array should be similar to the one shown here:

array([[ 4.99459766,  4.9912371 ,  4.98197012, ...,  5.00396647,
     4.99551417,  5.0142518 ],
   [ 5.00355913,  5.00590134,  5.00569767, ...,  5.01272428,
     5.00966923,  5.01262244],
   [ 5.01007657,  5.00274445,  5.00447565, ...,  5.01639034,
     5.01618667,  5.01170593],
   ..., 
   [ 4.84249084,  4.83770859,  4.84310134, ...,  4.84940985,
     4.85002035,  4.8513431 ],
   [ 4.84157509,  4.84533985,  4.8452381 , ...,  4.8531746 ,
     4.8521571 ,  4.85561661],
   [ 4.84065934,  4.83974359,  4.83872609, ...,  4.8525641 ,
     4.8499186 ,  4.8489011 ]])

I have tried this:

sorted_data = sorted(data.iteritems(), key=itemgetter(0))
matrix = np.array(map(itemgetter(1),sorted_data))

where 'data' is the dictionary mentioned above. But that didn't really work. I got this as a result: .....

array([  1.31015456e-02,  -1.99737189e-01,   5.18320081e-01, ...,
    -3.19981710e+07,  -8.42037666e+07,  -2.71674094e+05]),
   array([ -2.36162151e-02,   5.51533735e-01,   6.73521669e-01, ...,
    -7.75100987e+05,  -7.75423838e+07,   3.86366785e+07]),
   array([ -2.88907517e-04,   1.69103129e-01,  -7.10729251e-01, ...,
     2.88580034e+07,  -7.24711607e+07,  -2.38548542e+07])], dtype=object)

Assumed that your Dictionary is dict

import numpy as np
data = np.concatenate([np.reshape(value,(1,-1)) for value in dict.values()])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM