Python Forum
Converting units in NetCdf Files in Python - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Converting units in NetCdf Files in Python (/thread-10992.html)



Converting units in NetCdf Files in Python - fyec - Jun-16-2018

I have a script that reads Netcdf (.nc) files and coordinates from a 'csv' file, then it extracts a txt file that includes values of different parameters (Tmax, Tmin, Prcp and Wind Speed) in columns and different values of days in rows.

Because Netcdf file has different units from that I want, I need to change from the unit of Kelvin to the unit of Celcius.

Here is one part of the script. How can I put the codes inside to change units from Kelvin to Celcius?

    #After reading and giving the locations here, I can extract the values as .txt file:

    inpNETCDF ='E:/VIC/Forcing Data from princeton/from 85 for 35 years/02.tmin/tmin_daily_' + str(year) + '-' + str(year) + '.nc'
                    dataset = Dataset(inpNETCDF, mode='r')
                    var_dict = {}  
                    indexOfLat_down , indexOfLat_up, indexOfLon_down, indexOfLon_up = Find_IndexOfSite(lon_site,lat_site,dataset)
                    var_dict['tmin']=dataset.variables['tmin'][:, indexOfLon_down, indexOfLat_down]
                    dataFrame = pd.DataFrame(var_dict)
                    dataFrame_all = pd.concat([dataFrame_all, dataFrame])

    dataFrame_all.to_csv('data_' + gridCells[str(i+1)][j].replace(', ', '_') + '.txt', index=False, header=False, sep=' ',)

However the values in txt files are as Kelvin, I want to change these values as Celcius. How can I change the unit? Thanks.


RE: Converting units in NetCdf Files in Python - gontajones - Jun-18-2018

Who created the Netcdf (.nc) files?
If was you, try to create them setting the units attribute:
temp.units = "Celsius" #(or "C")
If not, I think you'll have to convert the values before creating the CSV:
temp_c = temp_k - 273.15