Weiss
Weiss

Reputation: 303

convert csv to netcdf in Python

Hi I have a CSV file that is for several monitoring stations that have measured isotope data repeatedly over a period of time.

     Country Latitude Longitude  Altitude  Sample Name        Date Begin of Period End of Period      H2 Precipitation  begin year  end year  Dif year  begin month  end month  begin days  end days  Days  Year  month      dates
5         DE  511.622   149.506       238       199706  15.06.1997      01.06.1997    30.06.1997   -71.7          74.3        1997      1997         0            1          6           6        30    24  1997      6 1997-06-15
6         DE  511.622   149.506       238       199707  15.07.1997      01.07.1997    31.07.1997   -70.1         171.7        1997      1997         0            1          7           7        31    24  1997      7 1997-07-15
7         DE  511.622   149.506       238       199708  15.08.1997      01.08.1997    31.08.1997   -64.5          57.5        1997      1997         0            1          8           8        31    23  1997      8 1997-08-15
8         DE  511.622   149.506       238       199709  15.09.1997      01.09.1997    30.09.1997   -39.1          37.9        1997      1997         0            1          9           9        30    21  1997      9 1997-09-15
9         DE  511.622   149.506       238       199710  15.10.1997      01.10.1997    31.10.1997   -56.4          68.2        1997      1997         0            1         10          10        31    21  1997     10 1997-10-15
...      ...      ...       ...       ...          ...         ...             ...           ...     ...           ...         ...       ...       ...          ...        ...         ...       ...   ...   ...    ...        ...
4995      DE  490.422   121.019       365       201304  15.04.2013      01.04.2013    30.04.2013  -41.86          35.7        2013      2013         0            1          4           4        30    26  2013      4 2013-04-15

Since I would like to plot this data nicely using the example: https://joehamman.com/2013/10/12/plotting-netCDF-data-with-Python/, the next step is to convert this CSV file into a NetCDF file. Does anyone have a suggestion for Python? For R there is already the question: convert csv to netcdf in R

Upvotes: 2

Views: 4162

Answers (1)

Gam
Gam

Reputation: 322

you could use xarray to import the dataframe, build the dataset shape as you want and then save it as NetCDF file.

A small example:

import pandas as pd
# Execute pip install xarray first
import xarray

# Example dataframe
diz = {
    'Country':['DE','DE','DE'],
    'Latitude':[511.622,511.622,511.622],
    'Longitude':[149.506,149.506,149.506]
}

df = pd.DataFrame(diz) 

# Create xray Dataset from Pandas DataFrame
xr = xarray.Dataset.from_dataframe(df)

# Save to netCDF
xr.to_netcdf('test.nc')

Upvotes: 1

Related Questions