【问题标题】:How to access elements of numpy ndarray?如何访问 numpy ndarray 的元素?
【发布时间】: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


【解决方案1】:

如果不详细查看您的错误,我可以指出一些陷阱。

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

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

检查数组的“形状”(大小)及其“dtype”。如果 shape 是 ()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])

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[()]) 有效。你有资源可以让我阅读那个符号吗?我以前从未见过。
  • 我在这个符号上加了一段。
  • x.item() 是另一种提取此单项的方式。
猜你喜欢
  • 1970-01-01
  • 2016-09-23
  • 1970-01-01
  • 2022-07-06
  • 2020-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多