#!/usr/bin/env python # Wenchang Yang (wenchang@princeton.edu) # Sat Feb 13 12:35:18 EST 2021 if __name__ == '__main__': from misc.timer import Timer tt = Timer(f'start {__file__}') import sys, os.path, os, glob, datetime import xarray as xr, numpy as np, pandas as pd #import matplotlib.pyplot as plt #more imports # if __name__ == '__main__': tt.check('end import') # #start from here #if True: def nc2csv(ifile): #ifile = 'chirps.precip.daily.China.subregion.2009-2014.nc' print('[ifile]:', ifile) da = xr.open_dataarray(ifile).load() da = da.squeeze(drop=True) #if 'tas' in ifile: # units = 'degC' if ifile.startswith('t_ref'): da = da - 273.15 units = 'degC' da.drop_vars(['lon', 'lat']) else: units = da.attrs['units'].replace('/', '_per_') ofile = ifile.replace('.nc', f'.{units}.csv') if os.path.exists(ofile) and 'o' not in sys.argv: print('[exists]:', ofile) return #print(da.squeeze(drop=True).to_dataframe()) if ifile.startswith('zsurf'): da.to_dataframe().to_csv(ofile, float_format='%g') else: da.to_pandas().to_csv(ofile, float_format='%g') print('[saved]:', ofile) #extract all nc files and convert them to csv files #if len(sys.argv)>1: if [ifile for ifile in sys.argv[1:] if ifile.endswith('.nc')]: ifiles = [ifile for ifile in sys.argv[1:] if ifile.endswith('.nc')] else: ifiles = [ifile for ifile in glob.glob('*.nc')] # if ifile!='african_cities_latlon.nc'] ifiles.sort() nfiles = len(ifiles) for ii,ifile in enumerate(ifiles, start=1): print(f'{ii:02d} of {nfiles}') nc2csv(ifile) print() if __name__ == '__main__': #from wyconfig import * #my plot settings figname = __file__.replace('.py', f'_{tt.today()}.png') if len(sys.argv) > 1 and sys.argv[1] == 'savefig': plt.savefig(figname) print('[saved]:', figname) tt.check(f'**Done**') #plt.show()