Rust极坐标从函数返回ndarray

6pp0gazn  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(130)

我想做一个函数,把Polars Dataframe (以及后面的序列)转换成ndarray数组,这样我就可以在smartcore这样的板条箱中使用它了?
我需要在下面的代码中添加什么才能使其编译?

:dep polars = {version="*"}
:dep polars-core = {version="*",features=["ndarray"]}  
:dep ndarray = {version="*"}

use polars::prelude::*;
use ndarray::{Array,ArrayBase,Dimension,DataOwned,OwnedRepr};
fn convert_2_ndarray<D>(
    x_train:DataFrame,
    x_test:DataFrame,
)->(ArrayBase<OwnedRepr<f64>,D>,ArrayBase<OwnedRepr<f64>,D>)
    where
        D: Dimension,
    {

    let x_train_conv = (&x_train).to_ndarray::<Float64Type>().unwrap();
    let x_test_conv = (&x_test).to_ndarray::<Float64Type>().unwrap();
    return (x_train_conv,x_test_conv)
}

已尝试编译代码,但未成功。出现以下错误:

[E0308] Error: mismatched types
        ╭─[command_413:1:1]
        │
      3 │ fn convert_2_ndarray<D>(
        ·                      ┬  
        ·                      ╰── this type parameter
        · 
     13 │     return (x_train_conv,x_test_conv)
        ·             ──────┬─────  
        ·                   ╰─────── expected type parameter `D`, found struct `Dim`
    ────╯

    [E0308] Error: mismatched types
        ╭─[command_413:1:1]
        │
      3 │ fn convert_2_ndarray<D>(
        ·                      ┬  
        ·                      ╰── this type parameter
        · 
     13 │     return (x_train_conv,x_test_conv)
        ·                          ─────┬─────  
        ·                               ╰─────── expected type parameter `D`, found struct `Dim`
vi4fp9gy

vi4fp9gy1#

由于维度受to_ndarray的约束,因此不需要维度的通用参数:

pub fn to_ndarray<N>(&self) -> PolarsResult<Array2<N::Native>>

您可以写入:

use ndarray::Array2;
use polars::prelude::*;

fn convert_2_ndarray(x_train: DataFrame, x_test: DataFrame) -> (Array2<f64>, Array2<f64>) {
    let x_train_conv = x_train.to_ndarray::<Float64Type>().unwrap();
    let x_test_conv = x_test.to_ndarray::<Float64Type>().unwrap();
    (x_train_conv, x_test_conv)
}

相关问题