Ahmed Ali
Ahmed Ali

Reputation: 75

Extract data from NETCDF (.NC file) based on time

I am currently working on extracting data from a .NC file to create a .cur file for usage in GNOME. I am doing this in python

I extracted the following variables.

water_u(time, y, x)
water_v(time, y, x)
x(x): 
y(y): 
time(time): time
SEP(time, y, x)

The cur file should contain the following:

[x][y][velocity x][velocity y]

this should happen for each time variable present. In this case I have 10 time data extracted, but I have thousands and thousand of [x][y] and velocity.

My question is how to I extract the velocities based on the time variable?

import numpy as np 
from netCDF4 import Dataset 
volcgrp = Dataset('file_1.nc', 'r') 
var = volcgrp.variables['water_v'][:] 
print(var) 
newList = var.tolist() 
file = open('text.txt', 'w') 
file.write('%s\n' % newList) 
print("Done") 
volcgrp.close() 

Upvotes: 1

Views: 2820

Answers (1)

N1B4
N1B4

Reputation: 3453

The key here is to read in the water_u and water_v for each of its three dimensions and then you can access those variables along its time dimension.

import netCDF4

ncfile = netCDF4.Dataset('file_1.nc', 'r') 
time = ncfile.variables['time'][:]  #1D
water_u = ncfile.variables['water_u'][:,:,:] #3D (time x lat x lon)
water_v = ncfile.variables['water_v'][:,:,:]

To access data at each grid point for the first time in this file:

water_u_first = water_u[0,:,:]

To store this 3D data into a text file as you describe in the comments, you'll need to (1) loop over time, (2) access water_u and water_v at that time, (3) flatten those 2D arrays to 1D, (4) convert to strings if using the standard file.write technique (can be avoided using Pandas to_csv for example), and (5) write-out the 1D arrays as rows in the text file.

Upvotes: 2

Related Questions