将包含字符串数组的 .mat 文件加载到 Python 3.6

use*_*906 4 python string matlab

我有一个 .mat 文件,其中包含两个字符串格式的 DateTime 数组。数组就像:

A = ["15-Nov-2014 22:42:16",
         "16-Dec-2014 04:14:07",
         "20-Jan-2015 17:05:32"]
Run Code Online (Sandbox Code Playgroud)

我将两个字符串数组保存在 .mat 文件中。我尝试使用以下命令在 Python 中加载它们:

import hdf5storage
Input = hdf5storage.loadmat('Input.mat')
Run Code Online (Sandbox Code Playgroud)

或这个命令:

import scipy
Input = scipy.io.loadmat('Input.mat')
Run Code Online (Sandbox Code Playgroud)

两者都会导致读取 Python 中的字典,这是预期的,但我看不到两个数组的名称作为字典键。

有任何想法吗?

Rot*_*tem 6

我建议您将字符串转换为字符数组。

显然,没有记录从 HDF5 存储读取 MATLAB 字符串的解决方案(MATLAB 字符串是对象,具有未记录的内部存储格式)。

将字符数组保存到Input.matMATLAB 中(不是 HDF5 格式):

A = ["15-Nov-2014 22:42:16"; "16-Dec-2014 04:14:07"; "20-Jan-2015 17:05:32"];

% Convert A from array of strings to 2D character array.
% Remark: all strings must be the same length
A = char(A); % 3*20 char array

% Save A to mat file (format is not HDF5).
save('Input.mat', 'A');
Run Code Online (Sandbox Code Playgroud)

使用 scipy.io.loadmat 在 Python 中读取A

from scipy import io

# Read mat file
Input = io.loadmat('Input.mat')  # Input is a dictioanry {'A': array(['15-Nov-2014 ...pe='<U20'), ...}

# Get A from Input (A stored in MATLAB - character arrays in MATLAB are in type utf-16)
A = Input['A'];  # A is 2D numpy array of type '<U20' array(['15-Nov-2014 22:42:16', '16-Dec-2014 04:14:07', ...], dtype='<U20')
Run Code Online (Sandbox Code Playgroud)