更改numpy数组的dtype data_type字段 [英] Change dtype data_type fields of numpy array

查看:305
本文介绍了更改numpy数组的dtype data_type字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.mat文件,可以使用scipy加载:

I have a .mat file which I load using scipy:

from oct2py import octave
import scipy.io as spio
matPath = "path/to/file.mat"
matFile = spio.loadmat(matPath)

我得到一个要用oct2py传递给倍频程函数的numpy数组,像这样:

I get a numpy array which I want to pass to octave function using oct2py, like that:

aMatStruct = matFile["aMatStruct"]
result = octave.aMatFunction(aMatStruct)

但是出现以下错误:

oct2py.utils.Oct2PyError: Datatype not supported

似乎是由于数组dtype引起的,它看起来像:[('x', 'O'), ('y', 'O'), ('z', 'O')]

It seems it's due to the array dtype, which looks like: [('x', 'O'), ('y', 'O'), ('z', 'O')]

所以我考虑过将其更改为'S''U'或受支持的内容.

So I thought about changing it to 'S', 'U', or something that's supported.

  1. 该怎么办?
  2. 我在 otc2py文档中找不到受支持的dtype.有什么帮助吗?
  3. 是否可以用另一个(受支持的)dtype加载.mat文件?我在此处但找不到有用的东西.
  1. How can it be done?
  2. I couldn't find a supported dtype in the otc2py documentation. Any help on that?
  3. Is there a way to load the .mat file with another (supported) dtype? I looked here but couldn't find anything useful.

请注意,在aMatFunction内部,它使用的是aMatStruct,例如:x = aMatStruct.x.

Note that inside aMatFunction it uses aMatStruct like that: x = aMatStruct.x.

推荐答案

我建议将结果数组转换为有效的字典,但是您击败了我,因此我不会对其进行编码:p

I was going to suggest converting the resulting array to a valid dictionary but you beat me to it so I won't code it :p

但是,我建议的另一个更简单的解决方案是,由于仅在octave中使用该结构,因此您可以可以将其加载到其工作区中并直接进行评估.即以下对我有用的东西:

However, the other, simpler solution I was going to suggest is that, since you're only using the struct within octave, you could just load it into its workspace and evaluate directly. i.e. the following works for me:

>>> octave.load("MyFile.mat")
>>> octave.eval("fieldnames(S)")
ans = 
{
  [1,1] = name
  [2,1] = age
}
[u'name', u'age']

编辑:拧紧它,这是python解决方案;我还是开始了:p

EDIT eh screw it, here's the python solution; I'd started it anyway :p

>>> from oct2py import octave
>>> from scipy.io import loadmat
>>> F = loadmat("/home/tasos/Desktop/MyFile.mat")
>>> M = F["S"] # the name of the struct variable I saved in the mat file
>>> M = M[0][0]
>>> D = {M.dtype.names[i]:M[i][0] for i in range(len(M))}
>>> out = octave.fieldnames(D); out
[u'age', u'name']

这篇关于更改numpy数组的dtype data_type字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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