標籤: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檔案