python - 带有列表列表的 Scipy.io savemat/loadmat

标签 python python-3.x list numpy scipy

我正在尝试创建一个列表列表并将其添加到字典键中,然后将字典保存为 .mat 文件。我的代码如下所示:

from scipy.io import loadmat
dic = {"X": [[1,2,3],[1,2,4],[6,7,8,9],[1]]}
savemat('Test.mat', mdict=dic)

当我使用 loadmat 加载 .mat 文件并打印 dic['X'];输出应为[[1,2,3],[1,2,4],[6,7,8,9],[1]]。相反,我得到了这个:

[[array([[1, 2, 3]]) array([[1, 2, 4]]) array([[6, 7, 8, 9]]) array([[1]])]]

我的用于加载和恢复dic的代码片段:

X = loadmat("Test.mat")
print(X['X'])

如何将原始列表存储到 .mat 文件中?

最佳答案

最可能的解释是您的库不能很好地处理列表列表,尤其是子列表具有不同长度的情况。您应该检查一下情况是否确实如此。

根据 docsscipy.io.savemat 是为数组字典设计的,这不是您提供的:

Save a dictionary of names and arrays into a MATLAB-style .mat file.

This saves the array objects in the given dictionary to a MATLAB- style .mat file.

您可以做的是重组数据:

dic = {"A": np.array([1, 2, 3]),
       "B": np.array([1, 2, 4]),
       "C": np.array([6, 7, 8, 9]),
       "D": np.array([1])}

请记住,具有不同长度的行的 numpy 数组将变成 dtype=Object 并且对于大多数矢量化函数来说几乎无法使用。它可能也无法与 scipy 很好地配合。

<小时/>

一个痛苦的解决方案是在再次加载数据时执行转换:

import numpy as np
from operator import itemgetter

lst = [[np.array([[1, 2, 3]]), np.array([[1, 2, 4]]),
        np.array([[6, 7, 8, 9]]), np.array([[1]])]]

res = list(map(list, (map(itemgetter(0), map(list, lst[0])))))

[[1, 2, 3], [1, 2, 4], [6, 7, 8, 9], [1]]
<小时/>

Python 中没有原生函数组合,但可以使用第 3 方库 toolz 使上述逻辑更具可读性:

from operator import itemgetter
from toolz import compose

res = list(map(compose(list, itemgetter(0), list), lst[0]))

关于python - 带有列表列表的 Scipy.io savemat/loadmat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50075877/

相关文章:

python - Pandas :excel days360 等效项

python - 想用 sympy 做多变最小化

python - 如何检查python脚本是否启动?

python - Python 将 3 channel rgb 彩色图像更改为 1 channel 灰色的速度有多快?

python - 比较Python列表中的数字序列

python - 以 ASCII 显示树

python dataset - 读取一组列并将其放入单独的数据框中?

javascript - 将谷歌日历 API 集成到 React hooks

html - 使用 List 模拟带有嵌套表格的动态表格 <ul> <li> 仅限 HTML 和 CSS

两个有序列表中项目的最佳配对策略同时保持顺序的算法