如何访问numpy ndarray的元素?

Ste*_*mer 5 python arrays matlab numpy scipy

我正在使用scipy的loadmat函数将matlab数据文件加载到python中.

from scipy.io import loadmat  

data   = loadmat('data.mat')
fields = data['field']
Run Code Online (Sandbox Code Playgroud)

类型fieldsnumpy.ndarray:

print 'fields type={}'.format(type(fields))
print 'fields dtype={}'.format(fields.dtype)
print 'fields shape={}'.format(fields.shape)
Run Code Online (Sandbox Code Playgroud)
fields type=<type 'numpy.ndarray'>
fields dtype=object
fields shape=(5,)
Run Code Online (Sandbox Code Playgroud)

我使用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
Run Code Online (Sandbox Code Playgroud)
x=[u'ACE']
x type=<type 'numpy.ndarray'>
x dtype=object
x shape=()
Run Code Online (Sandbox Code Playgroud)

IndexError:

如果我尝试访问第一个元素,x我得到一个IndexError:

x[0]
Run Code Online (Sandbox Code Playgroud)
---------------------------------------------------------------------------
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
Run Code Online (Sandbox Code Playgroud)

问题:

  • 怎么回事,如果type(x)回来nump.ndarray说"阵列的索引太多了"?
  • 如何将内容提取x到字符串中?

以下是我正在使用的版本:

print 'python version: {}'.format(sys.version)
print 'numpy version: {}'.format(numpy.__version__)
print 'scipy version: {}'.format(scipy.__version__)
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

hpa*_*ulj 7

没有详细查看您的错误,我可以指出一些陷阱.

.mat将包含MATLAB矩阵(总是2d或更高),单元格和结构.

loadmat以各种方式呈现这些.您必须按名称索引字典.有对象数组(dtype = object).并且有nd数字或字符串数​​组.您可能需要通过几个级别来获取数字数组.

检查数组的"形状"(大小)及其"dtype".如果形状是()dtype对象,则用它提取y=x[()].

这是一个这样的0d对象数组的例子:

In [4]: y=np.arange(3)

In [5]: x=np.empty((), dtype=object)    
In [6]: x[()]=y

In [7]: x
Out[7]: array(array([0, 1, 2]), dtype=object)

In [8]: x.shape
Out[8]: ()

In [9]: x.dtype
Out[9]: dtype('O')

In [10]: x[0]
...
IndexError: too many indices for array

In [11]: x[()]
Out[11]: array([0, 1, 2])
Run Code Online (Sandbox Code Playgroud)

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索引表示法的扩展.这不是一个特例.

  • `x.item()` 是另一种提取单个项目的方法。 (3认同)