Python解析HDF文件

谁借莪1个温暖的怀抱¢ 2022-08-01 12:29 254阅读 0赞

前段时间因为一个业务的需求需要解析一个HDF格式的文件。在这之前也不知道到底什么是HDF文件。百度百科的解释如下:

HDF是用于存储和分发科学数据的一种自我描述、多对象文件格式。HDF是由美国国家超级计算应用中心NCSA(全称:National Center for Supercomputing Application)创建的,为了满足各种领域研究需求而研制的一种能高效存储和分发科学数据的新型数据格式。HDF可以表示出科学数据存储和分布的许多必要条件。

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

  1. import math
  2. import pandas as pd
  3. import xlwt

第一个是用来做数学计算的math包主要处理数学相关的运算。至于关于pandas的介绍请点击这里。xlwt这个包是写HDF文件的。

使用Python读取HDF文件的代码如下:

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

其实这样获取到数据之后就是pandas提供的函数,获取自己需要的数据。

  1. slice_df = df.loc[dt]
  2. rtt = slice_df.rtt.unstack(level=0) / 1000
  3. cwnd = slice_df.cwnd.unstack(level=0)
  4. total = slice_df.total.unstack(level=0)
  5. rows = rtt.index.tolist()
  6. columns = rtt.columns.tolist()

最后写入Excel,代码如下:

  1. def writexcel(listname, name, time):
  2. #将数据写入Excel
  3. saveurl = EXCEL_FILR_URL + '%s_%s_%s.xls' % (AVG_RTT, time, name)
  4. excel_file = xlwt.Workbook()
  5. table = excel_file.add_sheet('tcpinfo')
  6. index_row = 0
  7. for item in listname:
  8. for item_key, item_value in item.items():
  9. table.write(index_row, 0, str(item_key))
  10. table.write(index_row, 1, str(item_value[1][0]))
  11. table.write(index_row, 2, str(item_value[1][1]))
  12. table.write(index_row, 3, str(item_value[0]).decode('utf-8'))
  13. index_row += 1
  14. excel_file.save(saveurl)

发表评论

表情:
评论列表 (有 0 条评论,254人围观)

还没有评论,来说两句吧...

相关阅读

    相关 python解析xml文件

        最近有个问题需要解析xml文件,以前没接触过,完成后发现原来解析xml很简单,但还是记录一下相关概念与解析过程,日后查看方便查找。 country\_data.x