分配给numpy的结构数组 [英] Assigning to numpy structured arrays

查看:125
本文介绍了分配给numpy的结构数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要得到结构化的数据在某种程度上为numpy的结构数组形式。我读了一点,(对不起SciPy的!)马虎关于这个主题我能找到的文档,并且仍然感到越来越行不通。

I have to get structured data somehow into numpy structured array form. I read the little and (sorry SciPy!) sloppy documentation on this topic I could find, and still am getting nowhere.

基本上我想要做这样简单的东西:

Basically I want to do something simple like this:

import numpy as np

dt = [('contacts', '(2,4)f8'), 
      ('modelname', 'S10')]

arr = np.zeros((2,), dtype=dt)

testdata = [[99, 2, 3, 4], [7, 8, 9, 10]]

arr[0]['contacts'] = np.array(testdata)
arr[0]['modelname'] = 'test'
print arr

然后我想看到的结构化阵列领域联系人设置为所需的内容。

and then I'd like to see the field 'contacts' of the structured array to be set to the desired contents.

但是,输出是:

[([[99.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]], 'test')
 ([[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]], '')]

显然只有第一个得到了一些分配。

Obviously only the first number got assigned.

推荐答案

您正在索引阵列的南辕北辙。尝试:

You're indexing your array the wrong way round. Try:

 arr['contacts'][0] = np.array(testdata)

也就是说,对于通讯录列改编,定为<$ C $索引行C> 0 你的 TESTDATA 。当你写改编[0] 您retreive记录标。事实上,如果你检查,你会看到改编[0] 的类型 numpy.void

That is, for the 'contacts' column of arr, set the row indexed at 0 to your testdata. When you write arr[0] you retreive a "record scalar". In fact, if you check, you'll see that arr[0] has type numpy.void.

分配给它不影响分配给整个记录的存储器。相比之下,改编['接触​​'] 创建视图,并分配给改编['接触​​'] [0] 中该数组视图修改原始的记忆。

Assigning to it does not affect the memory assigned to the entire record. By contrast, arr['contacts'] creates view and assigning to arr['contacts'][0] in that array view modifies the original memory.

我同意numpy的文档可以更清楚这个...

I agree the NumPy docs could be clearer on this...

这篇关于分配给numpy的结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆