How do I read the elements of an xtensor 'xexpression' object that is returned from a call to xt::load_csv()?

437 Views Asked by At

My code is:

#include <istream>
#include <fstream>
#include <xtensor/xcsv.hpp>

int main()
{
    std::ifstream in_file; 
    in_file.open("csv_file.csv"); 
    auto data = xt::load_csv<std::string>(in_file); 

    return 0;
}

When I inspect the xt::xexpression object data in my IDE, it appears correctly dimensioned and populated, but I can't find a way to read its elements in the code.

After poring through the xtensor documentation I am no wiser... Perhaps a pointer to a good introduction to xtensor might answer this question.

1

There are 1 best solutions below

3
On

After reading, data is simply an xarray: a multi-dimensional array, or in the case of CSV typically a matrix. On the matrix you can operate much like for example in NumPy. For example:

  • << allows you to print.
  • operator()(...) allows you to get an item using row and column indices.
  • xt::view(data, ...) allows you to get a 'slice'.

To be more specific consider this example:

#include <istream>
#include <fstream>
#include <iostream>
#include <xtensor/xarray.hpp>
#include <xtensor/xview.hpp>
#include <xtensor/xio.hpp>
#include <xtensor/xcsv.hpp>

int main()
{
    std::ifstream in_file;
    in_file.open("csv_file.csv");
    auto data = xt::load_csv<int>(in_file);

    std::cout << data << std::endl;
    std::cout << data(0, 0) << std::endl;
    std::cout << data(0, 1) << std::endl;
    std::cout << xt::view(data, 0, xt::all()) << std::endl;
}

which for the following CSV file

1,2,3
4,5,6
7,8,9

prints:

{{1, 2, 3},
 {4, 5, 6},
 {7, 8, 9}}
1
2
{1, 2, 3}