The following renames a column in a Polars-Rust dataframe:
#![allow(unused_variables)]
use polars::prelude::*;
fn main() {
println!("Hello, world!");
let mut df = df! [
"names" => ["a", "b", "c"],
"values" => [1, 2, 3],
].unwrap();
println!("{:?}", df);
let new_name = <PlSmallStr>::from_str("letters");
let _ = df.rename("names", new_name);
println!("{:?}", df);
}
Suppose now that the name of the first column is unknown (e.g., the dataframe is read from a csv/excel file, where it has no name), and I would like to rename it for the sake of future use:
fn main() {
println!("Hello, world!");
let mut df = df! [
"names" => ["a", "b", "c"],
"values" => [1, 2, 3],
].unwrap();
println!("{:?}", df);
let old_name = df.get_column_names_str()[0];
// let old_name = df.get_column_names_str()[0].clone();
// let old_name = &mut df.get_column_names_str()[0].clone();
// let mut old_name = &mut df.get_column_names_str()[0].clone();
let new_name = <PlSmallStr>::from_str("letters");
let _ = df.rename(old_name, new_name);
println!("{:?}", df);
}
This results in an error
error[E0502]: cannot borrow `df` as mutable because it is also borrowed as immutable
--> src/main.rs:32:13
|
27 | let old_name = df.get_column_names_str()[0];
| -- immutable borrow occurs here
...
32 | let _ = df.rename(old_name, new_name);
| ^^^------^^^^^^^^^^^^^^^^^^^^
| | |
| | immutable borrow later used by call
| mutable borrow occurs here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `rename_col` (bin "rename_col") due to 1 previous error
It is more or less clear why the error occurs, but not clear how to fix it...
The commented lines show my various unsuccessful attempts at resolving this issue.
Related:
In Rust, how to rename all columns of a Polars Dataframe?
How to rename column names with first row in polars?
Alternatively you can use df.get_column_names_owned()
function which will return Vec<PlSmallStr>
.
let column_names = df.get_column_names_owned();
let old_name = column_names.first().unwrap();
let new_name = <PlSmallStr>::from_str("letters");
let _ = df.rename(old_name, new_name);
OR
let old_name = &df.get_column_names_owned()[0];
let new_name = <PlSmallStr>::from_str("letters");
let _ = df.rename(old_name, new_name);
println!("{:?}", df);