You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现DataFrame的push方法,将csv::StringRecord数据存入对应向量?

Solution for Implementing DataFrame's push Method

Let's fix up your push method to correctly append data from a csv::StringRecord into your DataFrame's vectors. Here's the step-by-step solution:

Key Issues in the Original Code

  • The push method uses an immutable reference (&self), which prevents modifying the internal vectors (name, datetime, speed). We need a mutable reference instead (&mut self).
  • We need to extract the correct columns from the StringRecord and handle type conversion for the Speed field (from string to f32).
  • We should add basic error handling for missing columns or invalid numeric values.

Modified Complete Code

extern crate csv;

#[derive(Debug)]
struct DataFrame {
    header: csv::StringRecord,
    name: Vec<String>,
    datetime: Vec<String>,
    speed: Vec<f32>,
}

impl DataFrame {
    fn new() -> DataFrame {
        DataFrame {
            header: csv::StringRecord::new(),
            name: Vec::new(),
            datetime: Vec::new(),
            speed: Vec::new(),
        }
    }

    fn read_csv(filepath: &str, has_headers: bool) -> DataFrame {
        // Open file
        let file = std::fs::File::open(filepath).unwrap();
        let mut rdr = csv::ReaderBuilder::new()
            .has_headers(has_headers)
            .from_reader(file);

        // Add values to struct
        let mut empty_dataframe = DataFrame::new();
        empty_dataframe.header = rdr.headers().unwrap().clone();
        
        for result in rdr.records() {
            empty_dataframe.push(&result.unwrap());
        }
        
        empty_dataframe
    }

    // Update to use mutable reference to self
    fn push(&mut self, row: &csv::StringRecord) {
        // Extract values with error handling for missing columns
        let name = row.get("Name")
            .expect("Row is missing 'Name' column")
            .to_string();
        
        let datetime = row.get("DateTime")
            .expect("Row is missing 'DateTime' column")
            .to_string();
        
        // Parse Speed to f32 with error handling
        let speed_str = row.get("Speed")
            .expect("Row is missing 'Speed' column");
        let speed = speed_str.parse()
            .expect(&format!("Failed to parse '{}' as f32", speed_str));

        // Append to respective vectors
        self.name.push(name);
        self.datetime.push(datetime);
        self.speed.push(speed);
    }
}

fn main() {
    let data = DataFrame::read_csv("src/data.csv", true);
    println!("{:?}", data);
}

Explanation of Changes

  1. Mutable Reference for push: Changed &self to &mut self so we can modify the Vec fields in the DataFrame—you can't append to a vector through an immutable reference!
  2. Column Extraction by Name: Used row.get("ColumnName") instead of hardcoding indices. This makes the code more robust if the CSV column order changes later.
  3. Type Conversion: Converted the Speed string to f32 using parse(), with an error message that includes the problematic string for easier debugging.
  4. Error Handling: Used expect() to panic with meaningful messages if columns are missing or parsing fails. For production code, you could modify the method to return a Result instead for more graceful error handling.

Cargo.toml (Unchanged)

[dependencies]
csv = "1.0.0-beta.5"

Sample data.csv

Name,DateTime,Speed
Tom,2016-01-04 09:30:00.038279090,102.44
Tom,2016-01-04 09:30:00.038279090,102.44

内容的提问来源于stack exchange,提问作者Greg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:27:51