将 mat 文件转换为 Pandas 数据框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45007081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:57:46  来源:igfitidea点击:

Convert mat file to pandas dataframe

pythonpandasdataframemat

提问by Mohammad Mahdi KouchakYazdi

I want to convert this fileto pandas dataframe.

我想将此文件转换为Pandas数据框。

import pandas as pd
import scipy.io
mat = scipy.io.loadmat('cardio.mat')
cardio_df = pd.DataFrame(mat)

I get this error : Exception: Data must be 1-dimensional

我收到此错误: Exception: Data must be 1-dimensional

回答by cs95

It seems matis a dict containing Xof shape (1831, 21), ywith shape (1831, 1), and some metadata. Assuming Xis the data and yare the labels for the same, you can stack them horizontally with np.hstackand load them into pandas:

它似乎mat是一个包含Xshape (1831, 21)yshape(1831, 1)和一些元数据的字典。假设X是数据并且y是相同的标签,您可以将它们水平堆叠并将它们np.hstack加载到Pandas中:

In [1755]: mat = scipy.io.loadmat('cardio.mat')

In [1758]: cardio_df = pd.DataFrame(np.hstack((mat['X'], mat['y'])))

In [1759]: cardio_df.head()
Out[1759]: 
         0         1         2         3         4         5         6   \
0  0.004912  0.693191 -0.203640  0.595322  0.353190 -0.061401 -0.278295   
1  0.110729 -0.079903 -0.203640  1.268942  0.396246 -0.061401 -0.278295   
2  0.216546 -0.272445 -0.203640  1.050988  0.148753 -0.061401 -0.278295   
3  0.004912  0.727346 -0.203640  1.212171 -0.683598 -0.061401 -0.278295   
4 -0.100905  0.363595  1.321366  1.027120  0.141359 -0.061401 -0.278295   

In [1760]: cardio_df.shape
Out[1760]: (1831, 22)