如何在polar数据框中添加列名,同时使用CsvReader



我可以读取一个csv文件,在文件中没有列标题。下面的代码在rust中使用了极性:

use polars::prelude::*;
fn read_wine_data() -> Result<DataFrame> {
let file = "datastore/wine.data";
CsvReader::from_path(file)?
.has_header(false)
.finish()
}

fn main() {
let df = read_wine_data();
match df {
Ok(content) => println!("{:?}", content.head(Some(10))),
Err(error) => panic!("Problem reading file: {:?}", error)
}
}

但是现在我想在读取时或读取后向数据框中添加列名,我如何添加列名?下面是一个列名向量:

let COLUMN_NAMES = vec![
"Class label", "Alcohol",
"Malic acid", "Ash",
"Alcalinity of ash", "Magnesium",
"Total phenols", "Flavanoids",
"Nonflavanoid phenols",
"Proanthocyanins",
"Color intensity", "Hue",
"OD280/OD315 of diluted wines",
"Proline"
];

如何将这些名称添加到数据框架中。可以使用以下代码下载数据:

wget https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data

通过创建一个模式对象并将其与CsvReader上的with_schema方法一起传递,这似乎可以工作:

use polars::prelude::*;
use polars::datatypes::DataType;
fn read_wine_data() -> Result<DataFrame> {
let file = "datastore/wine.data";
let mut schema: Schema = Schema::new();
schema.with_column("wine".to_string(), DataType::Float32);
CsvReader::from_path(file)?
.has_header(false)
.with_schema(&schema)
.finish()
}

fn main() {
let df = read_wine_data();
match df {
Ok(content) => println!("{:?}", content.head(Some(10))),
Err(error) => panic!("Problem reading file: {:?}", error)
}
}

虽然我不知道列名应该是什么,但这是我添加一列时得到的输出:

shape: (10, 1)
┌──────┐
│ wine │
│ ---  │
│ f32  │
╞══════╡
│ 1.0  │
├╌╌╌╌╌╌┤
│ 1.0  │
├╌╌╌╌╌╌┤
│ 1.0  │
├╌╌╌╌╌╌┤
│ 1.0  │
├╌╌╌╌╌╌┤
│ ...  │
├╌╌╌╌╌╌┤
│ 1.0  │
├╌╌╌╌╌╌┤
│ 1.0  │
├╌╌╌╌╌╌┤
│ 1.0  │
├╌╌╌╌╌╌┤
│ 1.0  │
└──────┘

这是为我工作的完整解决方案:

fn read_csv_into_df(path: PathBuf) -> Result<DataFrame> {
let schema = Schema::from(vec![
Field::new("class_label", Int64),
Field::new("alcohol", Float64),
Field::new("malic_acid", Float64),
Field::new("ash", Float64),
Field::new("alcalinity_of_ash", Float64),
Field::new("magnesium", Float64),
Field::new("total_phenols", Float64),
Field::new("flavanoids", Float64),
Field::new("nonflavanoid_phenols", Float64),
Field::new("color_intensity", Float64),
Field::new("hue", Float64),
Field::new("od280/od315_of_diluted_wines", Float64),
Field::new("proline", Float64),
]);
CsvReader::from_path(path)?.has_header(false).with_schema(&schema).finish()
}

我为每个字段使用字段和类型来创建模式,然后使用CsvReader中的模式来读取数据。

最新更新