Converting Matlab's datenum format to Python

后端 未结 5 1751
甜味超标
甜味超标 2020-12-01 12:59

I just started moving from Matlab to Python 2.7 and I have some trouble reading my .mat-files. Time information is stored in Matlab\'s datenum format. For those who are not

5条回答
  •  感情败类
    2020-12-01 13:27

    Just in case it's useful to others, here is a full example of loading time series data from a Matlab mat file, converting a vector of Matlab datenums to a list of datetime objects using carlosdc's answer (defined as a function), and then plotting as time series with Pandas:

    from scipy.io import loadmat
    import pandas as pd
    import datetime as dt
    import urllib
    
    # In Matlab, I created this sample 20-day time series:
    # t = datenum(2013,8,15,17,11,31) + [0:0.1:20];
    # x = sin(t)
    # y = cos(t)
    # plot(t,x)
    # datetick
    # save sine.mat
    
    urllib.urlretrieve('http://geoport.whoi.edu/data/sine.mat','sine.mat');
    
    # If you don't use squeeze_me = True, then Pandas doesn't like 
    # the arrays in the dictionary, because they look like an arrays
    # of 1-element arrays.  squeeze_me=True fixes that.
    
    mat_dict = loadmat('sine.mat',squeeze_me=True)
    
    # make a new dictionary with just dependent variables we want
    # (we handle the time variable separately, below)
    my_dict = { k: mat_dict[k] for k in ['x','y']}
    
    def matlab2datetime(matlab_datenum):
        day = dt.datetime.fromordinal(int(matlab_datenum))
        dayfrac = dt.timedelta(days=matlab_datenum%1) - dt.timedelta(days = 366)
        return day + dayfrac
    
    # convert Matlab variable "t" into list of python datetime objects
    my_dict['date_time'] = [matlab2datetime(tval) for tval in mat_dict['t']]
    
    # print df
    
    DatetimeIndex: 201 entries, 2013-08-15 17:11:30.999997 to 2013-09-04 17:11:30.999997
    Data columns (total 2 columns):
    x    201  non-null values
    y    201  non-null values
    dtypes: float64(2)
    
    # plot with Pandas
    df = pd.DataFrame(my_dict)
    df = df.set_index('date_time')
    df.plot()
    

    enter image description here

提交回复
热议问题