如何在Python中加载.mat文件,并单独访问列?

时间:2017-02-23 19:19:31

标签: python scipy mat

我可以加载.mat文件,但由于列没有名称,我不知道如何引用它们。

.mat文件由四列组成,列数很多。

import numpy as np 
import pandas as pd
from scipy.io import loadmat
from sklearn.preprocessing import PolynomialFeatures 


data = loadmat('data.mat')
data.keys()

这导致:data['no names for columns in mat file']

此代码有什么问题?

1 个答案:

答案 0 :(得分:3)

当我加载测试垫时,我得到一个像

这样的显示器
Sub ImportData()
    Dim lastRow As Long
    Dim lastSumRow As Long
    Dim j As Long
    Dim k As Long
    With ActiveSheet
        lastRow = ActiveSheet.Cells(1048576, 1).End(xlUp).Row
    End With
    For k = 2 To lastRow
        k = 2
        lastUsedRow = ThisWorkbook.Sheets("Summary").Cells(1048576, 1).End(xlUp).Row
        If ActiveSheet.Cells(k, 2).Value <> "Imported" Then
            Workbooks.Open Filename:=ThisWorkbook.Path & "\Analysis\" & Cells(k, 1), UpdateLinks:=False
            ActiveWorkbook.Sheets("Summary").Activate
            For j = 3 To 100
                If j Mod 3 = 0 Then
                    ThisWorkbook.Sheets("Summary").Cells((j / 3) + lastUsedRow, 1).Value = ActiveWorkbook.Sheets("Summary").Cells(j, 1).Value
                    ThisWorkbook.Sheets("Summary").Cells((j / 3) + lastUsedRow, 2).Value = ActiveWorkbook.Sheets("Summary").Cells(j + 1, 2).Value
                    ThisWorkbook.Sheets("Summary").Cells((j / 3) + lastUsedRow, 3).Value = ActiveWorkbook.Sheets("Summary").Cells(j + 1, 3).Value
                    ThisWorkbook.Sheets("Summary").Cells((j / 3) + lastUsedRow, 4).Value = ActiveWorkbook.Sheets("Summary").Cells(j + 1, 4).Value
                    ThisWorkbook.Sheets("Summary").Cells((j / 3) + lastUsedRow, 5).Value = ActiveWorkbook.Sheets("Summary").Cells(j + 2, 2).Value
                    ThisWorkbook.Sheets("Summary").Cells((j / 3) + lastUsedRow, 6).Value = ActiveWorkbook.Sheets("Summary").Cells(j + 2, 3).Value
                    ThisWorkbook.Sheets("Summary").Cells((j / 3) + lastUsedRow, 7).Value = ActiveWorkbook.Sheets("Summary").Cells(j + 2, 4).Value
                    ThisWorkbook.Sheets("Summary").Cells((j / 3) + lastUsedRow, 8).Value = ActiveWorkbook.Sheets("Summary").Cells(j + 1, 5).Value
                End If
            Next j
            ActiveWorkbook.Close
        End If
        ThisWorkbook.Sheets("Setup").Cells(k, 2).Value = "Imported"
    Next k
End Sub

这告诉我mat包含一个名为In [50]: data=loadmat('test7.mat') In [51]: print(data) {'__globals__': [], 'x': array([[ 1., 2., 3.], [ 4., 5., 6.]]), '__version__': '1.0', '__header__': b'MATLAB 5.0 MAT-file, written by Octave 4.0.0, 2016-09-01 15:43:02 UTC'} 的变量,我可以访问它:

x

我们需要类似的文件信息才能提供帮助。

In [52]: data['x']
Out[52]: 
array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.]])

我不太清楚MATLAB上下文中的列和名称是什么意思。文件中的项目是否应该是MATLAB矩阵,单元格和/或结构?

列名是一个熊猫概念,而不是In [53]: list(data.keys()) # list need in Py3 Out[53]: ['__globals__', 'x', '__version__', '__header__'] 或MATLAB(我知道)。