[英]How to access elements of numpy ndarray?
我正在使用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=()
IndexError:
如果我嘗試訪問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數字或字符串數組。 您可能需要通過幾個級別來獲取數字數組。
檢查數組的“形狀”(大小)及其“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]
ind=(a,b,c); x[ind]
。 換句話說, []
中的參數被理解為值的元組。 (1,2)
是2元素元組, (1,)
是一個元素( (1)
只是一個分組), ()
是一個0元素元組。 所以x[()]
只是常規nd
索引表示法的擴展。 這不是一個特例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.