Skip to content

Instantly share code, notes, and snippets.

@jdherman
Created December 9, 2014 20:09
Show Gist options
  • Save jdherman/d55a3b94f298b3304db7 to your computer and use it in GitHub Desktop.
Save jdherman/d55a3b94f298b3304db7 to your computer and use it in GitHub Desktop.
boost utility functions for dealing with files
// utility functions for boost matrices/vectors
#include <fstream>
namespace ublas = boost::numeric::ublas;
using namespace std;
// create matrix:
// ublas::matrix<double> my_matrix(num_rows, num_columns);
// loadtxt("/path/to/file", my_matrix);
//
// then access values with my_matrix(1,3) for example
void loadtxt(string fname, ublas::matrix<double> & M)
{
ifstream f (fname.c_str());
if(!f.is_open())
{
cerr << "Error opening file " << fname << ". Exiting..." << endl;
exit(EXIT_FAILURE);
}
for (unsigned int i = 0; i < M.size1(); i++)
for (unsigned int j = 0; j < M.size2(); j++)
f >> M(i,j);
f.close();
}
void savetxt(string fname, ublas::matrix<double> & M)
{
ofstream f (fname.c_str());
if(!f.is_open())
{
cerr << "Error opening file " << fname << ". Exiting..." << endl;
exit(EXIT_FAILURE);
}
for (unsigned int i = 0; i < M.size1(); i++)
{
for (unsigned int j = 0; j < M.size2(); j++)
{
f << M(i,j);
if(j < M.size2()-1) f << " ";
else f << endl;
}
}
f.close();
}
@vkrao123
Copy link

hi sir
How to convert CSV to NetCDF using python. I have a script but something going wrong please help me?

from netCDF4 import Dataset
import numpy as np
import pandas as pd
import numpy as np
import numpy as np

from netCDF4 import Dataset

root = Dataset('fromTxt.nc','w',format='NETCDF4')

root.description = 'Example text input via numpy and netCDF4'

root.createDimension('Lon', None)

root.createDimension('Lat', None)

temp = root.createVariable('tem', 'f4', ('Lat','Lon',),fill_value=-9999)

#lats = np.arange(-90,90,0.2)
#lons = np.arange(-180,180,0.4)
#latitudes[:] = lats[:]
#langitudes[:] = lons[:]

f = open("ts_sept.csv")
a = pd.read_csv(f)

temp[:] = a[:]

root.close()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment