我正在使用scipy的loadmat
函数将一个matlab数据文件加载到python中。
from scipy.io import loadmat
data = loadmat('data.mat')
fields = data['field']
fields
的类型是numpy.ndarray
:
print 'fields type={}'.format(type(fields))
print 'fields dtype={}'.format(fields.dtype)
print 'fields shape={}'.format(fields.shape)
fields type=<type 'numpy.ndarray'> fields dtype=object fields shape=(5,)
我使用nditer
遍历数组:
for x in np.nditer(fields, flags=['refs_ok']):
print 'x={}'.format(x)
print 'x type={}'.format(type(x))
print 'x dtype={}'.format(x.dtype)
print 'x shape={}'.format(x.shape)
break
x=[u'ACE'] x type=<type 'numpy.ndarray'> x dtype=object x shape=()
索引器错误:
如果我试图访问x
的第一个元素,就会得到一个IndexError
:
x[0]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-102-8c374ae22096> in <module>() 17 print 'type={}'.format(type(x)) 18 print 'dtype={}'.format(x.dtype) ---> 19 x[0] 20 break 21 IndexError: too many indices for array
问题:
type(x)
返回nump.ndarray
,它会说“数组的索引太多”怎么办?x
的内容提取为字符串?以下是我正在使用的版本:
print 'python version: {}'.format(sys.version)
print 'numpy version: {}'.format(numpy.__version__)
print 'scipy version: {}'.format(scipy.__version__)
python version: 2.7.6 (default, Jun 22 2015, 17:58:13) [GCC 4.8.2] numpy version: 1.11.0 scipy version: 0.17.1
不用细看你的错误,我可以指出一些陷阱。
.mat将包含MATLAB矩阵(总是2d或更高)、单元和结构。
loadmat
以各种方式呈现它们。有些词典必须按名称索引。有对象数组(dtype=object)。有nd数字或字符串数组。您可能需要通过几个级别才能获得数值数组。检查数组的“shape”(大小)及其“dtype”。如果shape是
()
和dtype
对象,则使用y=x[()]
提取它。下面是这样一个0d对象数组的示例:
x
是0d数组(x.ndim),因此必须使用0元素元组()
对其进行索引。对于一个看起来很奇怪的MATLAB程序员来说。在
numpy
(通常是Python)中,x[a,b,c]
与x[(a,b,c)]
和ind=(a,b,c); x[ind]
相同。换句话说,[]
中的参数被理解为值的元组。(1,2)
是一个2元素元组,(1,)
是一个元素((1)
只是一个分组),而()
是一个0元素元组。所以x[()]
只是常规nd
索引表示法的扩展。这不是特例。相关问题 更多 >
编程相关推荐