如何实现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
pushmethod 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
StringRecordand handle type conversion for theSpeedfield (from string tof32). - 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
- Mutable Reference for
push: Changed&selfto&mut selfso we can modify theVecfields in theDataFrame—you can't append to a vector through an immutable reference! - 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. - Type Conversion: Converted the
Speedstring tof32usingparse(), with an error message that includes the problematic string for easier debugging. - 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 aResultinstead 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
相关产品推荐
相关产品推荐

