Home > database >  Rust Polars Dataframe to Tuple of vectors
Rust Polars Dataframe to Tuple of vectors

Time:11-22

I wanted to upload a polars dataframe to postgres using diesel. In that insert_into() function is there, where i have to give tuple of vectors as an input to .values().

Can anyone give suggestion on how to upload that.

pub fn insert_tuple_batch(conn: &mut PgConnection) -> Result<()> {
    use schema::users::dsl::*;
    insert_into(users)
        .values(&vec![
            (
                id.eq(1),
                title.eq("Sean"),
                body.eq("Black"),
                published.eq(true),
            ),
            (
                id.eq(2),
                title.eq("Tess"),
                body.eq("Brown"),
                published.eq(true),
            ),
        ])
        .execute(conn)
        .expect("Not inserted");
    println!("insert completed");
    Ok(())
}

I have id, title, body and published columns in a polars dataframe. I need to access the dataframe to convert to this.

&vec![
    (
        id.eq(1),
        title.eq("Sean"),
        body.eq("Black"),
        published.eq(true),
    ),
    (
        id.eq(2),
        title.eq("Tess"),
        body.eq("Brown"),
        published.eq(true),
    ),
]

where datatypes of columns are:

pub id: i32,  //Int4
pub title: String,  //Varchar
pub body: String,  //Text
pub published: bool,  //Bool

I have id, title, body and published columns in a polars dataframe. I need to access the dataframe to convert to this.

&vec![
    (
        id.eq(1),
        title.eq("Sean"),
        body.eq("Black"),
        published.eq(true),
    ),
    (
        id.eq(2),
        title.eq("Tess"),
        body.eq("Brown"),
        published.eq(true),
    ),
]

where datatypes of columns are:

pub id: i32,  //Int4
pub title: String,  //Varchar
pub body: String,  //Text
pub published: bool,  //Bool

CodePudding user response:

This might be the starting point for solution. This will vector one column, but not the whole dataframe. Maybe someone can comeup with better solution.

let b: Vec<_> = dataframe[1].iter().map(|x| (x).to_string()).collect();

CodePudding user response:

The column data are taken out as series. combine all values seperated by commas and split them by using commas. let id = "1,2,3,4,........"; let id_vector = id.split(',').collect::<Vec>(); But this will convert the dataframe from series to vector only, not into tuple of vector.

  • Related