1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
use std::fmt::{self, Display}; use std::collections::HashMap; use std::ops::Index; #[cfg(feature = "serde")] use serde::{Serialize, Deserialize}; use crate::{ Column, Rows, fmt::left_pad, }; /// [`Column`](enum.Column.html) id used to lookup and describe columns in a [`DataFrame`](struct.DataFrame.html) pub type Header = String; /// A 2D matrix of cells of mixed types useful for exploratory data analysis. /// /// ## Basic Concept /// /// A `DataFrame` consists of 0 or more [`Column`]s in a specific order. The DataFrame /// keeps track of a [`Header`] associated with each of its columns. The `Header` can /// be used to display the whole `DataFrame` or it can be used to lookup a single `Column`. /// /// [`Row`]s can be constructed by gathering up one cell from all columns at the same /// position. Since `Row`s are composed of many possibly different types, in the normal case, /// each cell in the column is of a different type which can't be known until runtime. /// Tubular tries to make this as ergonomic as possible, but working with Rows will always /// be a bit more ceremonius than working with Columns. /// /// Here's how to think about the structure of a `DataFrame`: /// /// ```no-run /// DataFrame /// /// + - - - -+- - - - + - - - -+ /// | Header | Header | Header | /// + - - - -+- - - - + - - - -+ /// | Column | Column | Column | /// | bool | u32 | String | /// | ------ | ------ | ------ | /// | |cell| | |cell| | |cell| | /// | ------ | ------ | ------ | /// | |cell| | |cell| | |cell| | /// | ------ | ------ | ------ | /// | ================================ /// | |cell| |cell| |cell | Row | /// | |bool| |u32 | |String| | /// | ================================ /// | ------ | ------ | ------ | /// | |cell| | |cell| | |cell| | /// | ------ | ------ | ------ | /// + - - - -+- - - - + - - - -+ /// /// ``` /// /// ## Constructing a DataFrame /// /// `DataFrame` implements `Default`, which is generally the easiest way to /// create one from scratch: /// /// ``` /// use tubular::DataFrame; /// /// let df = DataFrame::default(); /// ``` /// /// To add columns, use [`push()`](#method.push): /// /// ``` /// # use tubular::DataFrame; /// # let mut df = DataFrame::default(); /// df.push("Fruits", &["apple", "banana", "pear"]); /// ``` /// /// Although you could try using Serde to load a DataFrame, the current implementation /// is very basic and not likely to work as you expect. /// /// ## Exploring /// /// The easiest way to figure out what's in a `DataFrame` is to print it out: /// /// ``` /// # use tubular::DataFrame; /// # let mut df = DataFrame::default(); /// # df.push("Fruits", &["apple", "banana", "pear"]); /// # df.push("Organic", &[true, false, true]); /// # df.push("Quantity", &[16, 30, 10]); /// println!("{}", &df); /// ``` /// /// The result will be a table looking something like this: /// /// ```no-run /// Fruits Organic Quantity /// apple true 16 /// banana false 30 /// pear true 10 /// ``` /// /// ## Iteration /// /// `DataFrame`s can be used in `for` loops to iterate one column at a time: /// /// ``` /// # use tubular::DataFrame; /// # let mut df = DataFrame::default(); /// # df.push("Fruits", &["apple", "banana", "pear"]); /// # df.push("Organic", &[true, false, true]); /// # df.push("Quantity", &[16, 30, 10]); /// for column in &df { /// println!("{:?}", column); /// } /// ``` /// /// [`Column`]: enum.Column.html /// [`Header`]: type.Header.html /// [`Row`]: struct.Row.html #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[derive(Default, Debug, Clone, PartialEq)] pub struct DataFrame { columns: HashMap<Header, Column>, order: Vec<Header>, } impl DataFrame { /// Adds a new `Column` to the end of the `DataFrame`. /// /// Any iterator over items that implement [`ColumnType`](trait.ColumnType.html) /// can be passed as argument for the new column: /// /// ``` /// use tubular::DataFrame; /// use std::sync::mpsc::channel; /// use std::thread; /// /// let mut df = DataFrame::default(); /// /// // Add normal "list"-like iterators to a DataFrame /// df.push("Fruits", &["apple", "banana", "pear"]); /// df.push("Organic", vec![true, false, true]); /// df.push("Quantity", [16, 30, 10].iter()); /// /// // Or other less obvious sequences /// df.push("Sku", 1..4); /// df.push("Log Lines", "192.12.78.1 - 200\n25.31.197.245 - 200\n78.95.83.123 - 304".lines()); /// df.push("Words", "abc1def2ghi".split(char::is_numeric)); /// /// // ...Or real crazy iterators /// let (sender, recv) = channel(); /// thread::spawn(move || { /// sender.send(10.3).unwrap(); /// sender.send(97.2).unwrap(); /// sender.send(-15.3).unwrap(); /// }); /// df.push("Temperatures", recv); /// ``` pub fn push(&mut self, header: impl Into<Header>, column: impl Into<Column>) { let header = header.into(); let column = column.into(); self.order.push(header.clone()); self.columns.insert(header, column); } /// Returns the number of `Column`s in the `DataFrame` /// /// ``` /// use tubular::DataFrame; /// let mut df = DataFrame::default(); /// df.push("Words", "abc1def2ghi".split(char::is_numeric)); /// assert_eq!(df.len(), 1); /// ``` pub fn len(&self) -> usize { self.order.len() } /// Provides all the headers /// /// ``` /// use tubular::DataFrame; /// let mut df = DataFrame::default(); /// df.push("Fruits", &["apple", "banana", "pear"]); /// df.push("Organic", &[true, false, true]); /// df.push("Quantity", &[16, 30, 10]); /// assert_eq!(df.headers(), &vec![ /// "Fruits".to_string(), /// "Organic".to_string(), /// "Quantity".to_string() /// ]); /// ``` pub fn headers(&self) -> &Vec<Header> { &self.order } /// Returns the number of rows in the `DataFrame`. /// /// NOTE: This method is unstable is likely to be removed or changed semantically /// in the near future. pub fn row_len(&self) -> usize { if self.columns.len() == 0 { return 0; } self[0].len() } /// Allows iteration over [`Row`](struct.Row.html) objects /// /// ``` /// use tubular::DataFrame; /// let mut df = DataFrame::default(); /// df.push("Fruits", &["apple"]); /// df.push("Organic", &[true]); /// df.push("Quantity", &[16]); /// for row in df.rows() { /// assert_eq!(row.column_name::<String>("Fruits"), "apple"); /// assert_eq!(row.column_name::<bool>("Organic"), &true); /// assert_eq!(row.column_name::<i32>("Quantity"), &16); /// } pub fn rows(&self) -> Rows { From::from(self) } } impl Index<&'static str> for DataFrame { type Output = Column; fn index(&self, index: &'static str) -> &Self::Output { &self.columns[index] } } impl Index<String> for DataFrame { type Output = Column; fn index(&self, index: String) -> &Self::Output { &self.columns[&index] } } impl Index<usize> for DataFrame { type Output = Column; fn index(&self, index: usize) -> &Self::Output { &self.columns[&self.order[index]] } } impl Display for DataFrame { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let headers = self.headers(); let table_height = self.row_len() + 1; let mut lines: Vec<String> = std::iter::repeat(String::new()).take(table_height).collect(); for (header, column) in headers.iter().zip(self) { let width = column.display_width().max(header.len()) + 1; let strings: Vec<String> = (&column).into(); lines[0] += &left_pad(header, width); for (index, cell) in strings.iter().enumerate() { lines[index + 1] += &left_pad(cell, width); } } write!(f, "{}", lines.join("\n")) } } impl<'d> IntoIterator for &'d DataFrame { type IntoIter = IntoIter<'d>; type Item = Column; fn into_iter(self) -> IntoIter<'d> { IntoIter { df: self, index: 0, } } } pub struct IntoIter<'d> { index: usize, df: &'d DataFrame, } impl<'d> Iterator for IntoIter<'d> { type Item = Column; fn next(&mut self) -> Option<Column> { if self.index >= self.df.len() { return None; } let index = self.index; self.index += 1; Some(self.df[index].clone()) } }