I would like to return some data from c++ code as a numpy.array
object. I had a look at boost::python::numeric
, but its documentation is very terse. Can I get an example of e.g. returning a (not very large) vector<double>
to python? I don't mind doing copies of data.
You can save your NumPy arrays to CSV files using the savetxt() function. This function takes a filename and array as arguments and saves the array into CSV format.
The numpy. flipr() function always accepts a given array as a parameter and returns the same array and flip in the left-right direction. It reverses the order of elements on the given axis as 1 (left/right).
NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions the array have.
The Boost. Numpy library exposes quite a few methods to create ndarrays. ndarrays can be created in a variety of ways, include empty arrays and zero filled arrays. ndarrays can also be created from arbitrary python sequences as well as from data and dtypes.
UPDATE: the library described in my original answer (https://github.com/ndarray/Boost.NumPy) has been integrated directly into Boost.Python as of Boost 1.63, and hence the standalone version is now deprecated. The text below now corresponds to the new, integrated version (only the namespace has changed).
Boost.Python now includes a moderately complete wrapper of the NumPy C-API into a Boost.Python interface. It's pretty low-level, and mostly focused on how to address the more difficult problem of how to pass C++ data to and from NumPy without copying, but here's how you'd do a copied std::vector return with that:
#include "boost/python/numpy.hpp" namespace bp = boost::python; namespace bn = boost::python::numpy; std::vector<double> myfunc(...); bn::ndarray mywrapper(...) { std::vector<double> v = myfunc(...); Py_intptr_t shape[1] = { v.size() }; bn::ndarray result = bn::zeros(1, shape, bn::dtype::get_builtin<double>()); std::copy(v.begin(), v.end(), reinterpret_cast<double*>(result.get_data())); return result; } BOOST_PYTHON_MODULE(example) { bn::initialize(); bp::def("myfunc", mywrapper); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With