Import netCDF file to Pandas dataframe

user1911866 picture user1911866 · Dec 26, 2012 · Viewed 24.5k times · Source

Merry Christmas! I am still very new to Python and Pandas, so any help is appreciated. I am trying to read in a netCDF file, which I can do and then import that into a Pandas Dataframe. The netcDF file is 2D so I just want to 'dump it in'. I have tried the DataFrame method but it doesn't recognize the object. Presumably I need to convert the netCDF object to a 2D numpy array? Again, thanks for any ideas on the best way to do this.

Answer

naught101 picture naught101 · Mar 13, 2015

The xarray library handles arbitrary-dimensional netCDF data, and retains metadata. Xarray provides a simple method of opening netCDF files, and converting them to pandas dataframes:

import xarray as xr

ds = xr.open_dataset('/path/to/netcdf')
df = ds.to_dataframe()

This will create a dataframe with a multi-index with all of the dimensions in it. Unfortunately, Pandas doesn't support arbitrary metadata, so that will be lost in the conversion, but you can keep the ds around, and use the metadata from that.