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

3

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

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

我将两个字符串数组保存在.mat文件中。我试图使用以下命令在Python中加载它们:
import hdf5storage
Input = hdf5storage.loadmat('Input.mat')

或者这个命令:
import scipy
Input = scipy.io.loadmat('Input.mat')

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

有任何想法吗?


1
显然,目前没有记录下来的解决方案可以从HDF5存储中读取MATLAB字符串(MATLAB字符串是对象,具有未记录的内部存储格式)。我建议您将字符串转换为字符数组。 - Rotem
@Rotem 它起作用了!在MATLAB中,我将字符串转换为字符,然后保存到.mat文件中,最后使用scipy.io.loadmat在Python中加载。非常感谢您的答案!请将此提示编写为答案,以便我可以接受和评价它。 - user9439906
我已经发布了一个答案。请注意,mat文件不是HDF5格式,并且Python中的字符串以utf-16格式读取(numpy数组类型为'<U20')。 - Rotem
1个回答

5

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

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

在MATLAB中将字符数组保存到Input.mat(不以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');

使用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')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接