Skip to content

Instantly share code, notes, and snippets.

@Steboss89
Created June 30, 2021 14:47
Show Gist options
  • Save Steboss89/d51720455824786ccb453b41f53caff5 to your computer and use it in GitHub Desktop.
Save Steboss89/d51720455824786ccb453b41f53caff5 to your computer and use it in GitHub Desktop.
Convert a DataFrame to a DenseMatrix
pub fn convert_features_to_matrix(in_df: &DataFrame) -> Result<DenseMatrix<f64>>{
/* function to convert feature dataframe to a DenseMatrix, readable by smartcore*/
let nrows = in_df.height();
let ncols = in_df.width();
// convert to array
let features_res = in_df.to_ndarray::<Float64Type>().unwrap();
// create a zero matrix and populate with features
let mut Xmatrix: DenseMatrix<f64> = BaseMatrix::zeros(nrows, ncols);
// populate the matrix
// initialize row and column counters
let mut col: u32 = 0;
let mut row: u32 = 0;
for val in features_res.iter(){
// Debug
//println!("{},{}", usize::try_from(row).unwrap(), usize::try_from(col).unwrap());
// define the row and col in the final matrix as usize
let m_row = usize::try_from(row).unwrap();
let m_col = usize::try_from(col).unwrap();
// NB we are dereferencing the borrow with *val otherwise we would have a &val type, which is
// not what set wants
xmatrix.set(m_row, m_col, *val);
// check what we have to update
if (m_col==ncols-1) {
row+=1;
col = 0;
} else{
col+=1;
}
}
// Ok so we can return DenseMatrix, otherwise we'll have std::result::Result<Densematrix, PolarsError>
Ok(xmatrix)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment