簡體   English   中英

如何讀取/打印 Python 中 netCDF 文件的 header(前 100 行)?

[英]How to read/print the header (first 100 lines) of a netCDF file in Python?

我一直在嘗試閱讀 Python 中 netCDF 文件的 header(前 100 行),但遇到了一些問題。 I am familiar with the read_nc function available in the synoptReg package for R and with the ncread function that comes with MATLAB, as well as the read_csv function available in the pandas library. 然而,據我所知,netCDF (.nc) 文件沒有任何類似之處。

注意到這一點,並使用這個問題的答案,我嘗試了以下方法(沒有成功):

with open(filepath,'r') as f:
    for i in range(100):
        line = next(f).strip()
        print(line)

但是,我收到此錯誤,即使我已確保制表符未與空格混合並且for語句位於with塊內( 如該問題的最佳答案所給出的解釋):

'utf-8' codec can't decode byte 0xbb in position 411: invalid start byte

我還嘗試了以下方法:

with open(filepath,'r') as f:
    for i in range(100):
        line = [next(f) for i in range(100)]
print(line)

from itertools import islice
with open('/Users/toshiro/Desktop/Projects/CCAR/Data/EDGAR/v6.0_CO2_excl_short-cycle_org_C_2010_TOTALS.0.1x0.1.nc','r') as f:
    for i in range(100):
        line = list(islice(f, 100))
print(line)

但收到與上述相同的錯誤。 有什么解決方法嗎?

你不能。 netCDF 是二進制文件,不能解釋為文本。

如果文件是netCDF3編碼的,您可以使用scipy.io.netcdf_file讀取它們。 但它們更有可能是netCDF4 ,在這種情況下,您將需要netCDF4 package。

除此之外,我強烈推薦使用xarray package 來讀取和處理 netCDF 數據。 它支持帶標簽的 N 維數組接口——想想 pandas 數組的每個維度上的 numpy 索引。

無論您是使用 netCDF 還是 xarray 的 go,netCDF 都是自描述的並支持任意讀取,因此您無需加載整個文件即可查看元數據。 類似於查看文本文件的頭部,您可以簡單地執行以下操作:

import xarray as xr
ds = xr.open_dataset("path/to/myfile.nc")
print(ds)  # this will give you a preview of your data

此外,xarray 確實有一個xr.Dataset.head function ,它將沿每個維度顯示前 5 個(如果您提供 int,則為 N 個)元素:

ds.head()  # display a 5x5x...x5 preview of your data

有關詳細信息,請參閱閱讀和編寫 netCDF 文件入門指南和用戶指南部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM