Home > Software engineering >  Converting the dictionary which is in NetCDF data into a single list with python?
Converting the dictionary which is in NetCDF data into a single list with python?

Time:09-29

I have a netCDF dataset and I did this:

nc = Dataset(nc_file, mode='r')  
lat = nc.variables['latitude'][:]   shape (452,)
lon = nc.variables['longitude'][:]  shape (918,)
time = nc.variables['GMTime'][:] shape (1,10)
t2 = nc.variables['t2'][:]  shape (1,452,918)
tp = nc.variables['tp'][:]   shape (1,452,918)           
sf = nc.variables['sf'][:]   shape (1,452,918)            
u10 = nc.variables['u10'][:] shape (1,452,918)
v10 = nc.variables['v10'][:] shape (1,452,918)
tcc = nc.variables['tcc'][:]

now I want to have a single list like: new_data = [{lat =s.th,lon= s.th,t2 =s.th,..},lat =s.th,lon= s.th,t2 =s.th,..},...] but I have no idea how should I do this. :( thank you in advance for your help

CodePudding user response:

I am not totally clear on the intended structure of the list. But what you might want to do is read the data into a pandas dataframe first. This is probably also better data structure than the list. Each row will correspond to a specific lon/lat/time, and presumably you can convert that to the intended list.

import xarray as xr
ds = xr.open_dataset(nc_file)
df = ds.to_dataframe().reset_index()

CodePudding user response:

I too am confused by your example, but the question implies that you want to access the dictionaries in your NetCDF file, which is where the attributes are stored. There are 2 types of python dicts in a NetCDF file, one for global attributes and then one for each data variable. See: https://unidata.github.io/netcdf4-python/#attributes-in-a-netcdf-file.
But then again, all the python examples you show are just assigning the data to your variables, but not the attributes. So perhaps I've misunderstood.

  • Related