零维numpy.ndarray:唯一的元素是2D数组:如何访问它? [英] Zero-dimensional numpy.ndarray : only element is a 2D array : how to access it?
问题描述
我已经使用scipy.io导入了Matlab * .mat文件,并尝试从中提取2D数据.里面有几个数组,当我尝试获取它们时,我陷入了最后的操作.
I have imported a Matlab *.mat file using scipy.io and trying to extract the 2D data from it. There are several arrays inside, and when I am trying to get them I got stuck at the last operation.
数据如下图所示.当我尝试建立索引时: IndexError:数组的索引过多
The data looks like the image below. When I try to index it: IndexError: too many indices for array
我已经搜索到看起来像一个单值元组,其中唯一的元素是我的数组.原则上,这必须是可索引的,但不起作用. type(data)返回< class'numpy.ndarray'>
I have googled to the point that it looks like a single valued tuple, where the only element is my array. This in principle must be indexable, but it doesn't work. The type(data) returns <class 'numpy.ndarray'>
问题是:如何从这种数据结构中提取2D阵列?
So the question is: how do I get my 2D array out of this data structure?
data[0] # Doesn't work.
推荐答案
在 loadmat
上进行搜索应会产生许多SO问题,以帮助您区分该结果. loadmat
必须将MATLAB对象转换为Python/numpy近似值.
A search on loadmat
should yield many SO questions that will help you pick apart this result. loadmat
has to translate MATLAB objects into Python/numpy approximations.
data = io.loadmat(filename)
应该产生一个带有一些封面键和各种数据键的字典. list(data.keys())
进行识别.
should produce a dictionary with some cover keys and various data keys. list(data.keys())
to identify those.
x = data['x']
应与MATLAB工作区中的 x
变量匹配.可以是二维的F数组,对应于MATLAB矩阵.
should match the x
variable in the MATLAB workspace. It could be a 2d, order F array, corresponding to a MATLAB matrix.
可能是(n,m)个对象dtype数组,对应于MATLAB单元格.
It could be (n,m) object dtype array, corresponding to a MATLAB cell.
它可以是结构化的数组,其中字段名称对应于MATLAB的 struct
属性.
It could be a structured array, where the field names correspond to a MATLAB struct
attributes.
在您的情况下,看起来您有一个0d对象dtype数组.形状是()
,一个空的元组(1d具有(n,)形状,2d具有(n,m)形状,等等).您可以使用以下方法将元素从()数组中拉出:
In your case it looks like you have a 0d object dtype array. The shape is ()
, an empty tuple (1d has (n,) shape, 2d has (n,m) shape, etc). You can pull the element out of a () array with:
y[()]
y.item()
[()]
看起来很奇怪,但这是合乎逻辑的.对于一维数组, y [1]
可以写为 y [(1,)]
.对于2d, y [1,2]
和 y [(1,2)]
是相同的.标引元组应与维数匹配.因此,()
可以索引()形状数组.
The [()]
looks odd, but it's logical. For a 1d array y[1]
can be written as y[(1,)]
. For 2d, y[1,2]
and y[(1,2)]
are the same. The indexing tuple should match the number of dimensions. Hence a ()
can index a () shape array.
这篇关于零维numpy.ndarray:唯一的元素是2D数组:如何访问它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!