【问题标题】:Why can't I get the shape of this numpy array?为什么我不能得到这个 numpy 数组的形状?
【发布时间】:2017-05-09 16:26:18
【问题描述】:

我正在使用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
()

【问题讨论】:

  • len(R.shape)R.ndim 相同,以供将来参考。
  • R=pref_mat 的目的是什么?为什么不只是R = scipy.io.loadmat(...)
  • 为什么以...的名义你在做R=numpy.array(R)?你明白loadmat 返回的是什么吗?
  • @MadPhysicist 为什么?发生了什么?我不是普通的 python 用户,我只是碰巧需要它来完成这项特定的工作。据我了解,loadmat 加载 matlab 文件;我不知道它会返回什么。是字典吗?
  • 确实如此。看看你自己的输出和docs

标签: python arrays matlab numpy


【解决方案1】:

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 应该具有您想要的形状和数据类型。虽然在摘要视图中我只看到 0。

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

【讨论】:

  • 好的,谢谢。有用。数据没问题,它是一个稀疏矩阵,因此是 0。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-28
  • 2021-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
相关资源
最近更新 更多