[英]How to convert Python dictionary object to numpy array
I have python dict object with key as datetime.date object and values as tuple objects: 我有python dict对象,键为datetime.date对象,值为元组对象:
>>> data_dict
{datetime.date(2006, 1, 1): (5, 3),
datetime.date(2006, 1, 2): (8, 8),
datetime.date(2006, 1, 3): (8, 5),
datetime.date(2006, 1, 4): (3, 3),
datetime.date(2006, 1, 5): (3, 3),
datetime.date(2006, 1, 6): (4, 3),
...
and I want to convert it to numpy array object in this format: 我想以这种格式将其转换为numpy数组对象:
dtype([('date', '|O4'), ('high', '<i1'), ('low', '<i1')])
so that I could store it on disk and later work with it, and learn, in numpy, matplotlib... 这样我就可以将它存储在磁盘上,然后再使用它,并在numpy中学习matplotlib ......
As a matter of fact, I thought to use this format after looking at this matplotlib examples: http://matplotlib.sourceforge.net/users/recipes.html but can't find my way out how to get there. 事实上,在查看这个matplotlib示例之后我想使用这种格式: http : //matplotlib.sourceforge.net/users/recipes.html但是找不到如何到达那里的方法。
The following will do it: 以下将这样做:
arr = np.array([(k,)+v for k,v in data_dict.iteritems()], \
dtype=[('date', '|O4'), ('high', '<f8'), ('low', '<f8')])
If you then wish to use arr
as a recarray
, you could use: 如果您希望将
arr
用作recarray
,则可以使用:
arr = arr.view(np.recarray)
This will enable you to reference fields by name, eg arr.date
. 这将使您能够按名称引用字段,例如
arr.date
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.