问题描述
我有python dict对象,其键为datetime.date对象,值为元组对象:
I have python dict object with key as datetime.date object and values as tuple objects:
>>> 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),
...
,我想将其转换为以下格式的numpy数组对象:
and I want to convert it to numpy array object in this format:
dtype([('date', '|O4'), ('high', '<i1'), ('low', '<i1')])
这样我就可以将其存储在磁盘上,以后再使用它,并在numpy中学习matplotlib ...
so that I could store it on disk and later work with it, and learn, in numpy, matplotlib...
事实上,我认为在查看以下matplotlib示例后,便会使用这种格式: http ://matplotlib.sourceforge.net/users/recipes.html ,但找不到解决方法.
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.
推荐答案
以下将完成此操作:
arr = np.array([(k,)+v for k,v in data_dict.iteritems()], \
dtype=[('date', '|O4'), ('high', '<f8'), ('low', '<f8')])
如果您随后希望将arr
用作 recarray
,您可以使用:
If you then wish to use arr
as a recarray
, you could use:
arr = arr.view(np.recarray)
这将使您能够按名称引用字段,例如arr.date
.
This will enable you to reference fields by name, e.g. arr.date
.
这篇关于如何将Python字典对象转换为numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!