【发布时间】:2016-10-26 02:21:51
【问题描述】:
我正在使用 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
【问题讨论】:
-
你能打印出
x.shape吗? -
@C_Z_ - 更新了问题以包含
x.shape,它返回() -
这是一个 0d 数组,您必须使用 0 元素元组
x[()]对其进行索引。看我的回答。
标签: python arrays matlab numpy scipy