将Python字典列表映射到Matlab结构

2024-05-23 17:42:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将Python字典列表映射到特定的.matfromat。我之所以需要这样做,是因为我使用Python开发了一些代码来生成“绘画”(即由这样一个字典表示),但我想重用另一个项目提供的Matlab程序,该项目将这种结构的字典可视化

在整个项目中,我确保生成的所有绘画的名称、类型和结构都与Matlab项目的示例数据集相匹配。最后一步是将它转换成这个.matfromat。为此,我使用了numpyscipy.io。然而,需要注意的是,我对Matlab没有任何经验,这就是我用Python开发代码的原因

我的Python字典:

[{'xmax': 593, 'ymax': 685, 'h_pts': [0, 168, 362, 685], 'v_pts': [0, 25, 468, 487, 540, 593], 'h_thick': [0, 14, 16, 0], 'v_thick': [0, 14, 15, 16, 17, 0], 'h_ext': [[1, 6], [2, 6], [2, 5], [1, 6]], 'v_ext': [[1, 4], [1, 4], [2, 4], [2, 3], [2, 4], [1, 4]], 'rect': [[4, 3, 3, 5], [4, 3, 2, 3], [4, 2, 5, 6], [4, 1, 1, 2], [3, 2, 4, 5], [3, 2, 3, 4], [3, 2, 2, 3], [2, 1, 2, 6]], 'rect_colors': [2, 3, 1, 3, 3, 3, 1, 1]}]

文件.mat的示例表示形式(我所需要的):enter image description here

我目前正在尝试的:

saveformat = {}
paintings = [<python dictionary as above here>, ...]   
representations = np.asarray(representations).astype('object')    
saveformat['reps'] = representations
sio.savemat("cool_name.mat", saveformat)

我在Matlab中的结果:

enter image description here

单击上面的一个单元格时^

enter image description here

显然,这里出了点问题,我似乎无法从scipy.io的文档中准确地找出问题所在。它不是为字典的每个键值生成一列,然后为行中的每个字典实例列出这些键值,而是生成一行,每列中有一个字典(每幅画一个字典)

因此,问题相当直截了当,如何正确映射此格式


Tags: 项目代码io示例字典scipy结构ext
1条回答
网友
1楼 · 发布于 2024-05-23 17:42:27
也许这是次优的,但是你有没有考虑过像这样的熊猫?p>
dict1, dict2 = {'x': 1, 'y': 0, 'h': [1,2]}, {'x': -1, 'y':2, 'h':[3,3]}
df = pd.DataFrame(columns = dict1.keys(),data = [dict1,dict2])

你得到

 |   -|   -|   -|
 |   x   |   y   |   h   |
 |   -|   -|   -|
 |   1   |   0   | [1,2] |
 |   -|   -|   -|
 |   -1  |   2   | [3,3] |
 |   -|   -|   -|

相关问题 更多 >