, not String. I read API docs and it seem" /> , not String. I read API docs and it seem" /> , not String. I read API docs and it seem"/>

How to edit strings in place in ChunkedArray<StringType> Rust Polars

77 Views Asked by At

I'd like to do something like:

acc.str()?
    .iter()
    .map(|x| {
         x.push_str("AA");
    })

But the x is a Option<&str>, not String.

I read API docs and it seems that there is no way to extract String instead of &str.

Is there any way to modify the Strings in a ChunkedArray in-place?

1

There are 1 best solutions below

0
user459872 On

You can achieve the intended functionality by using apply_to_buffer API.

pub fn apply_to_buffer<'a, F>(&'a self, f: F) -> ChunkedArray<StringType>
where
    F: FnMut(&'a str, &mut String),

Utility that reuses an string buffer to amortize allocations. Prefer this over an apply that returns an owned String.

use polars::prelude::*;
use std::fmt::Write;

fn main() {
    let df = df! (
        "groups" => &["AB", "AB", "BA", "CB", "BC"],
    )
    .unwrap();
    let chunked_array = df.column("groups").unwrap().str().unwrap();
    let modified_chunked_array = chunked_array.apply_to_buffer(|val: &str, buf: &mut String| {
        write!(buf, "{}{}", val, "AA").unwrap();
    });
    println!("{:?}", modified_chunked_array);
}

This will print

shape: (5,)
ChunkedArray: 'groups' [str]
[
        "ABAA"
        "ABAA"
        "BAAA"
        "CBAA"
        "BCAA"
]

See also: