#!/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() units = da.attrs['units'].replace('/', '_per_').replace('%', 'pct') if units == 'K': #K -> C da = (da - 273.15).assign_attrs(units='degC') units = 'degC' ofile = ifile.replace('.nc', f'.{units}.csv') if os.path.exists(ofile): print('[exists]:', ofile) return #da.to_pandas().to_csv(ofile, float_format='%.2f') da.to_pandas().to_csv(ofile, float_format='%.3g') print('[saved]:', ofile) #extract all nc files and convert them to csv files if len(sys.argv)>1: ifiles = sys.argv[1:] else: ifiles = glob.glob('*.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()