Skip to main content
 首页 » 编程设计

python之为什么我不能得到这个 numpy 数组的形状

2024年10月01日8落叶

我正在使用 scipy.io 导入一个 matlab 文件,并试图找到它的尺寸。看起来,即使文件被加载到 python 中,它也无法给出尺寸。这是为什么?以及如何解决这个问题?

>>> import scipy.io 
>>> pref_mat = scipy.io.loadmat('pref_mat_loc.mat') 
>>> R=pref_mat 
>>> import numpy 
>>> R=numpy.array(R) 
>>> len(R) 
0 
>>> R # We see that the first line of the file is getting printed, means the file has been loaded. 
 
array({'pref_mat': array([[0, 0, 0, ..., 0, 0, 0], 
       [0, 0, 0, ..., 0, 0, 0], 
       [0, 0, 0, ..., 0, 0, 0], 
       ..., 
       [0, 0, 0, ..., 0, 0, 0], 
       [0, 0, 0, ..., 0, 0, 0], 
       [0, 0, 0, ..., 0, 0, 0]], dtype=uint16), '__header__': b'MATLAB 5.0 MAT-file, Platform: PCWIN64, Created on: Mon May 08 23:42:05 2017', '__version__': '1.0', '__globals__': []}, dtype=object) 
 
>>> len(R.shape) # But it appears here as though R is empty 
0 
>>> R.shape # As does here 
() 

请您参考如下方法:

pref_mat,loadmat返回的是一个字典。您已将其包装在数组 R 中。我可以将 pref_mat 的内容推断为 R 的 {} 部分:

{'pref_mat': array([[0, 0, 0, ..., 0, 0, 0], 
       [0, 0, 0, ..., 0, 0, 0], 
       [0, 0, 0, ..., 0, 0, 0], 
       ..., 
       [0, 0, 0, ..., 0, 0, 0], 
       [0, 0, 0, ..., 0, 0, 0], 
       [0, 0, 0, ..., 0, 0, 0]], dtype=uint16),  
'__header__': b'MATLAB 5.0 MAT-file, Platform: PCWIN64, Created on: Mon May 08 23:42:05 2017',  
'__version__': '1.0',  
'__globals__': []} 

所以你感兴趣的数组是

R = pref_mat['pref_mat'] 

那个 R 应该有你想要的形状和数据类型。虽然在摘要 View 中我只看到 0。

如果 MATLAB 保存了单元格或结构,“对象”类型数组的嵌套会变得更加复杂。