pub struct Sheet {
pub data: Vec<Vec<Cell>>,
}
Expand description
Represents a 2D vector of cells, forming a sheet of data.
Fields§
§data: Vec<Vec<Cell>>
2D vector of cells
Implementations§
Source§impl Sheet
impl Sheet
Sourcepub fn load_data(file_path: &str) -> Result<Self, Box<dyn Error>>
pub fn load_data(file_path: &str) -> Result<Self, Box<dyn Error>>
Loads data from a CSV file into the Sheet’s data structure.
This function reads the content of a CSV file specified by file_path
and populates
the Sheet’s data structure accordingly. The file must have a “.csv” extension, and
its content should be in CSV (Comma-Separated Values) format.
§Arguments
file_path
- The path to the CSV file to load.
§Errors
Returns a Result
indicating success or an error if the file cannot be opened,
read, or if the file format is unsupported.
§Examples
use datatroll::Sheet;
if let Err(err) = Sheet::load_data("input.csv") {
eprintln!("Error loading data: {}", err);
} else {
println!("Data loaded successfully from input.csv");
}
pub fn load_data_from_str(data: &str) -> Self
Sourcepub fn export(&self, file_path: &str) -> Result<(), Box<dyn Error>>
pub fn export(&self, file_path: &str) -> Result<(), Box<dyn Error>>
Exports the content of a Sheet to a CSV file.
The function writes the content of the Sheet into a CSV file specified by file_path
.
If the file already exists, it truncates the file and overwrites its content.
§Arguments
file_path
- The path to the CSV file.
§Examples
let cell_string = Cell::String(String::from("Hello, Rust!"));
let cell_int = Cell::Int(42);
let row1 = vec![cell_string, Cell::Bool(true), cell_int];
let row2 = vec![Cell::Null, Cell::Float(3.14), Cell::String(String::from("World"))];
let sheet = Sheet { data: vec![row1, row2] };
if let Err(err) = sheet.export("output.csv") {
eprintln!("Error exporting data: {}", err);
} else {
println!("Data exported successfully to output.csv");
}
§Errors
Returns an Result
indicating success or failure.
Sourcepub fn insert_row(&mut self, input: &str) -> Result<(), Box<dyn Error>>
pub fn insert_row(&mut self, input: &str) -> Result<(), Box<dyn Error>>
insert_row appends a row to the data sheet at the last position
The function takes a comma seperated input string, trim the whitespace, parse it into a vector oc Cell and then push it to the sheet.
§Arguments
input
- input string to be inserted.
§Errors
Returns a Result
indicating success or an error if the input is of unvalid format
§Examples
let row1 = vec![Cell::String("Hello, Rust!".to_string()), Cell::Bool(true), Cell::Int(42)];
let sheet = Sheet { data: vec![row1] };
sheet.insert_row(",3.14,World")?;
assert_eq!(sheet[0], row1);
assert_eq!(sheet[1], vec![Cell::Null, Cell::Float(3.14), Cell::String("World".to_string()]);
Sourcepub fn fill_col(
&mut self,
column: &str,
value: Cell,
) -> Result<(), Box<dyn Error>>
pub fn fill_col( &mut self, column: &str, value: Cell, ) -> Result<(), Box<dyn Error>>
fill_col replace the value of a column in every row
The function takes a column name and the value to be filled, and iterate through every row and effectively replace its old cell values with the new value
§Arguments
column
- the column to be mutatedvalue
- the value which every row will be filled with
§Errors
Returns a Result
indicating success or an error
§Examples
let row1 = vec![Cell::String("greeting".to_string()), Cell::String("is_good".to_string()), Cell::String("count".to_string())];
let row2 = vec![Cell::String("Hello, Rust!".to_string()), Cell::Bool(false), Cell::Int(42)];
let row3 = vec![Cell::String("Hello, World!".to_string()), Cell::Bool(true), Cell::Int(145)];
let sheet = Sheet { data: vec![row1, row2, row3] };
sheet.fill_col("greeting", Cell::Null)?;
assert_eq!(sheet[1][0], Cell::Null);
assert_eq!(sheet[1][0], Cell::Null);
Sourcepub fn paginate(
&self,
page: usize,
size: usize,
) -> Result<Vec<Vec<Cell>>, Box<dyn Error>>
pub fn paginate( &self, page: usize, size: usize, ) -> Result<Vec<Vec<Cell>>, Box<dyn Error>>
paginate takes part of a sheet with a fixed size and return it
The function takes a page number and a page size, and slice the sheet and returns it as a page of fixed size
§Arguments
page
- the number of the pagesize
- number of rows for every page
§Errors
Returns a Result
indicating success or an error
§Examples
let row1 = vec![Cell::String("greeting".to_string()), Cell::String("is_good".to_string()), Cell::String("count".to_string())];
let row2 = vec![Cell::String("Hello, Rust!".to_string()), Cell::Bool(false), Cell::Int(42)];
let row3 = vec![Cell::String("Hello, World!".to_string()), Cell::Bool(true), Cell::Int(145)];
let row4 = vec![Cell::String("Hello, Dzair!".to_string()), Cell::Bool(true), Cell::Int(145)];
let row5 = vec![Cell::String("Hello, Africa!".to_string()), Cell::Bool(true), Cell::Int(145)];
let row6 = vec![Cell::String("Hello, Algeria!".to_string()), Cell::Bool(true), Cell::Int(145)];
let row7 = vec![Cell::String("Hello, Friday!".to_string()), Cell::Bool(true), Cell::Int(145)];
let sheet = Sheet { data: vec![row1, row2, row3, row4, row5, row6, row7] };
let page = sheet.paginate(1, 2)?;
assert_eq!(page[0][0], Cell::String("Hello, Rust!".to_string()));
assert_eq!(page[1][0], Cell::String("Hello, World!".to_string()));
Sourcepub fn find_first_row<F>(
&self,
column: &str,
predicate: F,
) -> Option<&Vec<Cell>>
pub fn find_first_row<F>( &self, column: &str, predicate: F, ) -> Option<&Vec<Cell>>
Finds the first row in the table that matches a predicate applied to a specific column.
§Panics
Panics if the specified column doesn’t exist or is absent for a row.
§Examples
let mut sheet = Sheet::new_sheet();
sheet.load_data("test_data.csv").unwrap();
let first_matching_rows = sheet.find_rows("Age", |cell| cell.as_int() >= 30);
§Generics
The predicate
argument is a generic function that allows for flexible filtering criteria.
It accepts a reference to a Cell
and returns a boolean indicating whether the row matches.
§Returns
An Option<&Vec<Cell>>
:
Some(&row)
if a matching row is found, whererow
is a reference to the first matching row.None
if no matching row is found.
Sourcepub fn filter<F>(&self, column: &str, predicate: F) -> Vec<Vec<Cell>>
pub fn filter<F>(&self, column: &str, predicate: F) -> Vec<Vec<Cell>>
Finds rows in the table that match a predicate applied to a specific column.
§Panics
Panics if the specified column doesn’t exist or is absent for a row.
§Examples
let mut sheet = Sheet::new_sheet();
sheet.load_data("test_data.csv").unwrap();
let matching_rows = sheet.filter("Age", |cell| cell.as_int() >= 30);
§Generics
The predicate
argument is a generic function that allows for flexible filtering criteria.
It accepts a reference to a Cell
and returns a boolean indicating whether the row matches.
§Returns
A vector of vectors, where each inner vector represents a row that matches the predicate.
Sourcepub fn map<F>(&mut self, column: &str, transform: F) -> Result<(), String>
pub fn map<F>(&mut self, column: &str, transform: F) -> Result<(), String>
The map function applies a given transformation to each column value of rows.
§Errors
Returns a Result
indicating success or an error
§Examples
use datatroll::{Sheet, Cell};
let data = "id ,title , director, release date, review
1, old, quintin, 2011, 3.5
2, her, quintin, 2013, 4.2
3, easy, scorces, 2005, 1.0
4, hey, nolan, 1997, 4.7
5, who, martin, 2017, 5.0";
let mut sheet = Sheet::load_data_from_str(data);
let result = sheet.map("title", |c| match c {
Cell::String(s) => Cell::String(s.to_uppercase()),
_ => return c,
});
assert!(result.is_ok());
Sourcepub fn drop_rows<F>(&mut self, column: &str, predicate: F)
pub fn drop_rows<F>(&mut self, column: &str, predicate: F)
Removes rows from the table based on a predicate applied to a specific column.
§Panics
Panics if the specified column doesn’t exist.
§Examples
let mut sheet = Sheet::new_sheet();
sheet.load_data("test_data.csv").unwrap();
sheet.drop_rows("Age", |cell| cell.as_int() >= 30); // Removes rows where age is 30 or older
§Generics
The predicate
argument is a generic function that allows for flexible filtering criteria.
It accepts a reference to a Cell
and returns a boolean indicating whether to keep the row.
Sourcepub fn drop_col(&mut self, column: &str) -> i32
pub fn drop_col(&mut self, column: &str) -> i32
Removes a specified column from the table and returns the number of rows affected.
§Panics
Panics if the specified column doesn’t exist.
§Returns
The number of rows that were modified by removing the column.
§Examples
let mut sheet = Sheet::new_sheet();
sheet.load_data("test_data.csv").unwrap();
let rows_affected = sheet.drop_col("id") // Removes the "id" column and returns 5
Sourcepub fn mean(&self, column: &str) -> Result<f64, Box<dyn Error>>
pub fn mean(&self, column: &str) -> Result<f64, Box<dyn Error>>
Calculates the mean (average) of a specified column.
The mean is the sum of all values in a data set divided by the number of values.
§Formula
X̄ = (ΣX) / N
Where:
- X̄ is the mean
- ΣX is the sum of all values in the column
- N is the number of values in the column
§Errors
Returns an error if:
- The specified column doesn’t exist.
- The specified column contains non-numeric values (i.e., not
i64
orf64
).
§Examples
let mut sheet = Sheet::new_sheet();
sheet.load_data("test_data.csv").unwrap();
let re_mean = sheet.mean("release year")?; // Returns the mean of the "Age" column
§Returns
The mean of the specified column as an f64
, or an error if one occurs.
Sourcepub fn variance(&self, column: &str) -> Result<f64, Box<dyn Error>>
pub fn variance(&self, column: &str) -> Result<f64, Box<dyn Error>>
Calculates the variance of a specified column.
Variance measures how far a set of numbers are spread out from their average value. It is calculated as the average of the squared differences from the mean.
§Formula
Var(X) = E[(X - μ)²]
Where:
- Var(X) is the variance
- E denotes the expected value (average)
- X is the random variable (the values in the column)
- μ is the mean of X
§Errors
Returns an error if:
- The specified column doesn’t exist.
- The specified column contains non-numeric values (i.e., not
i64
orf64
).
§Examples
let mut sheet = Sheet::new_sheet();
sheet.load_data("test_data.csv").unwrap();
let re_variance = sheet.variance("release year")?; // Returns the variance of the "release year" column
§Returns
The variance of the specified column as an f64
, or an error if one occurs.
Sourcepub fn median(&self, column: &str) -> &Cell
pub fn median(&self, column: &str) -> &Cell
Calculates the median value of a specified column.
The median is the value that separates the higher half of a data set from the lower half. In this case, it’s the value that falls in the middle of the column when the data is sorted.
§Panics
Panics if:
- The specified column doesn’t exist.
- The specified column is absent for the middle row.
§Examples
let mut sheet = Sheet::new_sheet();
sheet.load_data("test_data.csv").unwrap();
let median_id = sheet.median("id")?; // Returns a &Int(3)
§Returns
A reference to the Cell
containing the median value of the specified column.
Sourcepub fn mode(&self, column: &str) -> Vec<(Cell, i32)>
pub fn mode(&self, column: &str) -> Vec<(Cell, i32)>
mode get the most frequent items of a column
The function gets a vector of the most frequent items in a column, alongside their number of occurences.
§Arguments
columnn
- the name of the column
§Examples
let mut sheet = Sheet::new_sheet();
sheet.load_data("test_data.csv").unwrap();
let multimodal = sheet.mode("director");
println!("mode: {:?}", multimodal) // mode: [(String("quintin"), 2), (String("martin"), 2)]
Sourcepub fn max_float64(&self, column: &str) -> Result<f64, Box<dyn Error>>
pub fn max_float64(&self, column: &str) -> Result<f64, Box<dyn Error>>
Finds the maximum value of a specified column, working with both f64
and i64
values.
§Errors
Returns an error if:
- The specified column doesn’t exist.
- The specified column contains non-numeric values (i.e., not
f64
ori64
).
§Returns
The maximum value in the specified column, either an f64
or an i64
cast to f64
, or an error if one occurs.
Sourcepub fn min_float64(&self, column: &str) -> Result<f64, Box<dyn Error>>
pub fn min_float64(&self, column: &str) -> Result<f64, Box<dyn Error>>
Finds the minimum value of a specified column, working with both f64
and i64
values.
§Errors
Returns an error if:
- The specified column doesn’t exist.
- The specified column contains non-numeric values (i.e., not
f64
ori64
).
§Returns
The minimum value in the specified column, either an f64
or an i64
cast to f64
, or an error if one occurs.
Sourcepub fn describe(&self)
pub fn describe(&self)
Prints general information about the sheet to the standard output in a formatted manner.
This includes:
- The first 5 rows of the sheet.
- A separator line.
- The last 5 rows of the sheet.
- The total number of rows and columns
Sourcepub fn pretty_print(&self)
pub fn pretty_print(&self)
Prints the entire sheet to the standard output in a formatted manner.
Each row is enclosed in parentheses and separated by commas, providing a visual representation of the sheet’s structure and content.