Python解析HDF檔案

來源:互聯網
上載者:User

標籤:python   資料   hdf檔案解析   

前段時間因為一個業務的需求需要解析一個HDF格式的檔案。在這之前也不知道到底什麼是HDF檔案。百度百科的解釋如下:

HDF是用於儲存和分發科學資料的一種自我描述、多個物件檔案格式。HDF是由美國國家超級計算應用中心NCSA(全稱:National Center for Supercomputing Application)建立的,為了滿足各種領域研究需求而研製的一種能高效儲存和分發科學資料的新型資料格式。HDF可以表示出科學資料存放區和分布的許多必要條件。

使用Python解析當然會用到第三方的包,如下:

import mathimport pandas as pdimport xlwt

第一個是用來做數學計算的math包主要處理數學相關的運算。至於關於pandas的介紹請點擊這裡。xlwt這個包是寫HDF檔案的。

使用Python讀取HDF檔案的代碼如下:

    with closing(pd.HDFStore(HDF_FILR_URL)) as store:        df = store[date]    # index shoule be end -> region -> group    df.reset_index(inplace=True)    df.set_index(["end", "region", "group"], inplace=True)    df.sort_index(inplace=True)

其實這樣擷取到資料之後就是pandas提供的函數,擷取自己需要的資料。

    slice_df = df.loc[dt]    rtt = slice_df.rtt.unstack(level=0) / 1000    cwnd = slice_df.cwnd.unstack(level=0)    total = slice_df.total.unstack(level=0)    rows = rtt.index.tolist()    columns = rtt.columns.tolist()

最後寫入Excel,代碼如下:

def writexcel(listname, name, time):    #將資料寫入Excel    saveurl = EXCEL_FILR_URL + ‘%s_%s_%s.xls‘ % (AVG_RTT, time, name)    excel_file = xlwt.Workbook()    table = excel_file.add_sheet(‘tcpinfo‘)    index_row = 0    for item in listname:        for item_key, item_value in item.items():            table.write(index_row, 0, str(item_key))            table.write(index_row, 1, str(item_value[1][0]))            table.write(index_row, 2, str(item_value[1][1]))            table.write(index_row, 3, str(item_value[0]).decode(‘utf-8‘))            index_row += 1    excel_file.save(saveurl)

Python解析HDF檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.