### Trim Start Matches Examples Source: https://docs.rs/polars/latest/polars/datatypes/struct.PlSmallStr.html Examples of removing prefixes that match a pattern repeatedly. ```rust assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11"); assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123"); let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12"); ``` -------------------------------- ### Trim start matches example Source: https://docs.rs/polars/latest/polars/datatypes/struct.TimeZone.html Demonstrates trimming characters from the start of a string slice. ```rust let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12"); ``` -------------------------------- ### Column Selection Examples Source: https://docs.rs/polars/latest/polars/prelude/fn.col.html?search=u32+-%3E+bool Examples demonstrating how to select columns using direct names, wildcards, or regex patterns. ```rust // select a column name col("foo") ``` ```rust // select all columns by using a wildcard col("*") ``` ```rust // select specific columns by writing a regular expression that starts with `^` and ends with `$` // only if regex features is activated col("^foo.*$") ``` -------------------------------- ### Created By Field Format Example Source: https://docs.rs/polars/latest/polars/prelude/struct.FileMetadata.html Example format for the created_by field string. ```text parquet-mr version 1.8.0 (build 0fda28af84b9746396014ad6a415b90592a98b3b) ``` -------------------------------- ### Initialize DataFrame for GroupBy examples Source: https://docs.rs/polars/latest/polars/frame/group_by/struct.GroupBy.html Sets up a DataFrame with date, temperature, and rain columns to be used in subsequent aggregation examples. ```rust use polars_core::prelude::*; let dates = &[ "2020-08-21", "2020-08-21", "2020-08-22", "2020-08-23", "2020-08-22", ]; // date format let fmt = "%Y-%m-%d"; // create date series let s0 = DateChunked::parse_from_str_slice("date", dates, fmt) .into_series(); // create temperature series let s1 = Series::new("temp".into(), [20, 10, 7, 9, 1]); // create rain series let s2 = Series::new("rain".into(), [0.2, 0.1, 0.3, 0.1, 0.01]); // create a new DataFrame let df = DataFrame::new_infer_height(vec![s0, s1, s2]).unwrap(); println!("{:?}", df); ``` -------------------------------- ### Trim Matches Examples Source: https://docs.rs/polars/latest/polars/datatypes/struct.PlSmallStr.html Examples of removing prefixes and suffixes that match a pattern repeatedly. ```rust assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar"); assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar"); let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_matches(x), "foo1bar"); ``` ```rust assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar"); ``` -------------------------------- ### Strip Prefix Examples Source: https://docs.rs/polars/latest/polars/datatypes/struct.PlSmallStr.html Examples of removing a prefix exactly once if it exists. ```rust assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar")); assert_eq!("foo:bar".strip_prefix("bar"), None); assert_eq!("foofoo".strip_prefix("foo"), Some("foo")); ``` -------------------------------- ### CollectBatches::start Source: https://docs.rs/polars/latest/polars/prelude/struct.CollectBatches.html?search=std%3A%3Avec Starts running the query if it has not already been started. ```APIDOC ## pub fn start(&mut self) ### Description Starts running the query, if not already started. ### Signature `pub fn start(&mut self)` ``` -------------------------------- ### Trim Prefix Examples Source: https://docs.rs/polars/latest/polars/datatypes/struct.PlSmallStr.html Examples of removing an optional prefix using the nightly-only API. ```rust #![feature(trim_prefix_suffix)] // Prefix present - removes it assert_eq!("foo:bar".trim_prefix("foo:"), "bar"); assert_eq!("foofoo".trim_prefix("foo"), "foo"); ``` -------------------------------- ### Trim End Matches Examples Source: https://docs.rs/polars/latest/polars/datatypes/struct.PlSmallStr.html Examples of removing repeated suffixes that match a specific pattern. ```rust assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar"); assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar"); let x: &[_] = &['1', '2']; assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar"); ``` ```rust assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo"); ``` -------------------------------- ### CloudWriter::start Source: https://docs.rs/polars/latest/polars/prelude/cloud/cloud_writer/struct.CloudWriter.html Starts the cloud writing process. ```APIDOC ## CloudWriter::start ### Description Initiates the writing process for the CloudWriter. ### Signature `pub async fn start(&mut self) -> Result<(), PolarsError>` ``` -------------------------------- ### CloudWriter::start Source: https://docs.rs/polars/latest/polars/prelude/cloud/cloud_writer/struct.CloudWriter.html?search=u32+-%3E+bool Starts the cloud writing process. ```APIDOC ### pub async fn start(&mut self) -> Result<(), PolarsError> Initializes the writing process for the CloudWriter. ``` -------------------------------- ### Create HashSet with Hasher Source: https://docs.rs/polars/latest/polars/datatypes/type.PlHashSet.html Examples of initializing a HashSet with a specific hasher. ```rust use hashbrown::HashSet; use hashbrown::DefaultHashBuilder; let s = DefaultHashBuilder::default(); let mut set = HashSet::with_hasher(s); set.insert(2); ``` ```rust use hashbrown::HashSet; use hashbrown::DefaultHashBuilder; let s = DefaultHashBuilder::default(); let mut set = HashSet::with_capacity_and_hasher(10, s); set.insert(1); ``` -------------------------------- ### Strip Suffix Examples Source: https://docs.rs/polars/latest/polars/datatypes/struct.PlSmallStr.html Examples of removing a suffix exactly once if it exists. ```rust assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar")); assert_eq!("bar:foo".strip_suffix("bar"), None); assert_eq!("foofoo".strip_suffix("foo"), Some("foo")); ``` -------------------------------- ### CollectBatches::start Source: https://docs.rs/polars/latest/polars/prelude/struct.CollectBatches.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes the execution of the query if it has not already been started. ```APIDOC ## pub fn start(&mut self) ### Description Starts running the query associated with the CollectBatches instance, if it is not already running. ``` -------------------------------- ### starts_with Source: https://docs.rs/polars/latest/polars/prelude/cat/struct.CategoricalNameSpace.html?search=std%3A%3Avec Checks if the categorical values start with a specific prefix. ```APIDOC ## pub fn starts_with(self, prefix: String) -> Expr ### Description Returns an expression that evaluates to true if the category string starts with the provided prefix. ### Parameters - **prefix** (String) - The prefix to check against. ### Returns - **Expr** - A boolean expression. ``` -------------------------------- ### explain Source: https://docs.rs/polars/latest/polars/prelude/struct.LazyFrame.html?search= Return a String describing the logical plan. ```APIDOC ## pub fn explain(&self, optimized: bool) -> Result ### Description Return a String describing the logical plan. If `optimized` is `true`, explains the optimized plan. If `optimized` is `false`, explains the naive, un-optimized plan. ``` -------------------------------- ### Box::from_raw Examples Source: https://docs.rs/polars/latest/polars/chunked_array/object/registry/type.BuilderConstructor.html?search=std%3A%3Avec Demonstrates reconstructing a Box from a raw pointer, either from a previous into_raw call or manual allocation. ```rust let x = Box::new(5); let ptr = Box::into_raw(x); let x = unsafe { Box::from_raw(ptr) }; ``` ```rust use std::alloc::{alloc, Layout}; unsafe { let ptr = alloc(Layout::new::()) as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw(ptr); } ``` -------------------------------- ### Manually Create Box from Global Allocator Source: https://docs.rs/polars/latest/polars/chunked_array/object/registry/type.BuilderConstructor.html?search= Shows how to allocate memory manually and wrap it in a Box using from_raw. ```rust use std::alloc::{alloc, Layout}; unsafe { let ptr = alloc(Layout::new::()) as *mut i32; // In general .write is required to avoid attempting to destruct // the (uninitialized) previous contents of `ptr`, though for this // simple example `*ptr = 5` would have worked as well. ptr.write(5); let x = Box::from_raw(ptr); } ``` -------------------------------- ### Strip Circumfix Examples Source: https://docs.rs/polars/latest/polars/datatypes/struct.PlSmallStr.html Examples of removing both a prefix and a suffix exactly once using the nightly-only API. ```rust #![feature(strip_circumfix)] assert_eq!("bar:hello:foo".strip_circumfix("bar:", ":foo"), Some("hello")); assert_eq!("bar:foo".strip_circumfix("foo", "foo"), None); assert_eq!("foo:bar;".strip_circumfix("foo:", ';'), Some("bar")); ``` -------------------------------- ### Importing Polars prelude Source: https://docs.rs/polars/latest/polars/frame/struct.DataFrame.html Common tools are available via the prelude. ```rust use polars_core::prelude::*; // if the crate polars-core is used directly // use polars::prelude::*; if the crate polars is used ``` -------------------------------- ### Queueing Commands with QueueableCommand Source: https://docs.rs/polars/latest/polars/prelude/cloud/cloud_writer/struct.CloudWriterIoTraitWrap.html Demonstrates how to queue multiple print commands and execute them simultaneously by flushing the writer. ```rust use std::io::{self, Write}; use crossterm::{QueueableCommand, style::Print}; fn main() -> io::Result<()> { let mut stdout = io::stdout(); // `Print` will executed executed when `flush` is called. stdout .queue(Print("foo 1\n".to_string()))? .queue(Print("foo 2".to_string()))?; // some other code (no execution happening here) ... // when calling `flush` on `stdout`, all commands will be written to the stdout and therefore executed. stdout.flush()?; Ok(()) // ==== Output ==== // foo 1 // foo 2 } ``` -------------------------------- ### Get subslice safely Source: https://docs.rs/polars/latest/polars/datatypes/struct.PlSmallStr.html Use get to retrieve a subslice without panicking, returning None for invalid indices. ```rust let v = String::from("🗻∈🌏"); assert_eq!(Some("🗻"), v.get(0..4)); // indices not on UTF-8 sequence boundaries assert!(v.get(1..).is_none()); assert!(v.get(..8).is_none()); // out of bounds assert!(v.get(..42).is_none()); ``` -------------------------------- ### CsvReader Initialization Source: https://docs.rs/polars/latest/polars/prelude/struct.CsvReadOptions.html?search=u32+-%3E+bool Methods to finalize the configuration and create a CsvReader instance. ```APIDOC ## CsvReader Initialization ### Description Methods to convert configured CsvReadOptions into a functional CsvReader. ### Methods - **try_into_reader_with_file_path(path: Option) -> Result, PolarsError>**: Creates a reader from a file path. - **into_reader_with_file_handle(reader: R) -> CsvReader**: Creates a reader from a file handle (requires R: MmapBytesReader). ``` -------------------------------- ### pub async fn build_object_store Source: https://docs.rs/polars/latest/polars/prelude/cloud/fn.build_object_store.html?search=std%3A%3Avec Builds an ObjectStore based on the URL and passed in options. Returns the cloud location and an implementation of the object store. ```APIDOC ## Function: build_object_store ### Description Builds an `ObjectStore` based on the URL and passed in options. This function is available when the `polars-io` crate feature is enabled. ### Signature `pub async fn build_object_store(path: PlRefPath, options: Option<&CloudOptions>, glob: bool) -> Result<(CloudLocation, PolarsObjectStore), PolarsError>` ### Parameters - **path** (PlRefPath) - The path or URL for the object store. - **options** (Option<&CloudOptions>) - Optional cloud configuration settings. - **glob** (bool) - Whether to enable globbing for the path. ### Returns - **Result<(CloudLocation, PolarsObjectStore), PolarsError>** - A tuple containing the `CloudLocation` and the `PolarsObjectStore` implementation, or a `PolarsError` if the operation fails. ``` -------------------------------- ### Naive Byte Splitting Example Source: https://docs.rs/polars/latest/polars/prelude/_csv_read_internal/struct.SplitLines.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E An example of a naive approach that fails when CSV fields contain embedded newline characters. ```rust for line in bytes.split(b'\n') { ``` -------------------------------- ### time_ranges(start: Expr, end: Expr, interval: Duration, closed: ClosedWindow) -> Expr Source: https://docs.rs/polars/latest/polars/prelude/fn.time_ranges.html Creates a column of time ranges from a start and stop expression. ```APIDOC ## time_ranges ### Description Creates a column of time ranges from a `start` and `stop` expression. ### Signature `pub fn time_ranges(start: Expr, end: Expr, interval: Duration, closed: ClosedWindow) -> Expr` ### Requirements Available on crate features `dtype-time` and `lazy` only. ### Parameters - **start** (Expr) - The starting expression for the time range. - **end** (Expr) - The ending expression for the time range. - **interval** (Duration) - The duration of each interval. - **closed** (ClosedWindow) - Defines which side of the interval is closed. ``` -------------------------------- ### Create HashMap with Capacity and Hasher Source: https://docs.rs/polars/latest/polars/datatypes/type.PlHashMap.html Demonstrates creating a HashMap with a pre-allocated capacity and a specific hash builder. ```rust use hashbrown::HashMap; use hashbrown::DefaultHashBuilder; let s = DefaultHashBuilder::default(); let mut map = HashMap::with_capacity_and_hasher(10, s); assert_eq!(map.len(), 0); assert!(map.capacity() >= 10); map.insert(1, 2); ``` -------------------------------- ### ParquetObjectStore::from_uri Source: https://docs.rs/polars/latest/polars/prelude/struct.ParquetObjectStore.html?search= Initializes a new ParquetObjectStore instance from a given URI. ```APIDOC ## pub async fn from_uri(uri: PlRefPath, options: Option<&CloudOptions>, metadata: Option>) -> Result ### Description Creates a new ParquetObjectStore instance from the provided URI, optionally accepting cloud configuration and existing file metadata. ### Parameters - **uri** (PlRefPath) - Required - The URI of the Parquet file. - **options** (Option<&CloudOptions>) - Optional - Configuration options for cloud storage access. - **metadata** (Option>) - Optional - Pre-fetched file metadata. ``` -------------------------------- ### linear_space(start: Expr, end: Expr, num_samples: Expr, closed: ClosedInterval) -> Expr Source: https://docs.rs/polars/latest/polars/prelude/fn.linear_space.html?search= Generates a series of equally-spaced points between a start and end expression. ```APIDOC ## linear_space ### Description Generates a series of equally-spaced points. This function is available when the `lazy` crate feature is enabled. ### Signature `pub fn linear_space(start: Expr, end: Expr, num_samples: Expr, closed: ClosedInterval) -> Expr` ### Parameters - **start** (Expr) - The starting value of the sequence. - **end** (Expr) - The ending value of the sequence. - **num_samples** (Expr) - The number of points to generate. - **closed** (ClosedInterval) - Specifies the interval behavior. ### Returns - **Expr** - An expression representing the generated series of points. ``` -------------------------------- ### datetime_range(start, end, interval, num_samples, closed, time_unit, time_zone) Source: https://docs.rs/polars/latest/polars/prelude/fn.datetime_range.html Creates a datetime range expression from the provided start, end, interval, and sample count parameters. ```APIDOC ## Function: datetime_range ### Description Creates a datetime range from `start`, `end`, `interval`, and `num_samples` expressions. This function is available when the `dtype-datetime` and `lazy` crate features are enabled. ### Signature `pub fn datetime_range(start: Option, end: Option, interval: Option, num_samples: Option, closed: ClosedWindow, time_unit: Option, time_zone: Option) -> Result` ### Parameters - **start** (Option) - The starting point of the range. - **end** (Option) - The ending point of the range. - **interval** (Option) - The duration between each point in the range. - **num_samples** (Option) - The number of samples to generate. - **closed** (ClosedWindow) - Defines which boundaries are included in the range. - **time_unit** (Option) - The unit of time for the range. - **time_zone** (Option) - The timezone for the range. ### Returns - **Result** - Returns an expression representing the datetime range or a PolarsError if the operation fails. ``` -------------------------------- ### date_ranges(start, end, interval, num_samples, closed) Source: https://docs.rs/polars/latest/polars/prelude/fn.date_ranges.html Creates a column of date ranges from start, end, interval, and num_samples expressions. This function is available when the 'dtype-date' and 'lazy' features are enabled. ```APIDOC ## Function: date_ranges ### Description Creates a column of date ranges from `start`, `end`, `interval`, and `num_samples` expressions. ### Signature `pub fn date_ranges(start: Option, end: Option, interval: Option, num_samples: Option, closed: ClosedWindow) -> Result` ### Parameters - **start** (Option) - The starting point of the range. - **end** (Option) - The ending point of the range. - **interval** (Option) - The duration between each step in the range. - **num_samples** (Option) - The number of samples to generate. - **closed** (ClosedWindow) - Defines which boundaries are included in the range. ### Requirements - **Crate Features**: `dtype-date`, `lazy` ``` -------------------------------- ### Initialization Methods Source: https://docs.rs/polars/latest/polars/prelude/datatypes/type.TimeChunked.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Methods for creating new instances of the Logical time type. ```APIDOC ## new(name: PlSmallStr, v: T) ### Description Initializes a new Logical instance by name and values. Requires the `dtype-time` crate feature. ``` -------------------------------- ### datetime_ranges(start, end, interval, num_samples, closed, time_unit, time_zone) Source: https://docs.rs/polars/latest/polars/prelude/fn.datetime_ranges.html?search= Creates a column of datetime ranges from start, end, interval, and num_samples expressions. Requires crate features 'dtype-datetime' and 'lazy'. ```APIDOC ## Function: datetime_ranges ### Description Creates a column of datetime ranges from `start`, `end`, `interval`, and `num_samples` expressions. ### Signature `pub fn datetime_ranges(start: Option, end: Option, interval: Option, num_samples: Option, closed: ClosedWindow, time_unit: Option, time_zone: Option) -> Result` ### Parameters - **start** (Option) - The starting datetime expression. - **end** (Option) - The ending datetime expression. - **interval** (Option) - The duration interval between ranges. - **num_samples** (Option) - The number of samples to generate. - **closed** (ClosedWindow) - Defines the closed window behavior. - **time_unit** (Option) - The time unit for the datetime values. - **time_zone** (Option) - The time zone for the datetime values. ### Returns - **Result** - An expression representing the datetime ranges or a PolarsError if the operation fails. ``` -------------------------------- ### Create Dummy Variables Example Source: https://docs.rs/polars/latest/polars/prelude/trait.DataFrameOps.html?search=u32+-%3E+bool Demonstrates the usage of the to_dummies method to convert categorical data into dummy variables. ```rust use polars_core::prelude::*; let df = df! { "id" => &[1, 2, 3, 1, 2, 3, 1, 1], "type" => &["A", "B", "B", "B", "C", "C", "C", "B"], "code" => &["X1", "X2", "X3", "X3", "X2", "X2", "X1", "X1"] }.unwrap(); let dummies = df.to_dummies(None, false, false).unwrap(); println!("{}", dummies); ``` -------------------------------- ### update_view(view: View, start: usize, end: usize, val: &str) -> View Source: https://docs.rs/polars/latest/polars/prelude/fn.update_view.html?search= Updates a View object by replacing the content within the specified start and end indices with the provided string value. ```APIDOC ## update_view ### Description Updates a `View` object by replacing the content within the specified range [start, end) with the provided string value. ### Signature `pub fn update_view(view: View, start: usize, end: usize, val: &str) -> View` ### Requirements - **Crate Feature**: `polars-ops` ### Parameters - **view** (View) - The view object to be updated. - **start** (usize) - The starting index of the range to update. - **end** (usize) - The ending index of the range to update. - **val** (&str) - The string value to insert into the specified range. ``` -------------------------------- ### Trim Prefix and Suffix Examples Source: https://docs.rs/polars/latest/polars/datatypes/struct.PlSmallStr.html Demonstrates removing prefixes and suffixes from string slices, including method chaining. ```rust // Prefix absent - returns original string assert_eq!("foo:bar".trim_prefix("bar"), "foo:bar"); // Method chaining example assert_eq!("".trim_prefix('<').trim_suffix('>'), "https://example.com/"); ``` ```rust #![feature(trim_prefix_suffix)] // Suffix present - removes it assert_eq!("bar:foo".trim_suffix(":foo"), "bar"); assert_eq!("foofoo".trim_suffix("foo"), "foo"); // Suffix absent - returns original string assert_eq!("bar:foo".trim_suffix("bar"), "bar:foo"); // Method chaining example assert_eq!("".trim_prefix('<').trim_suffix('>'), "https://example.com/"); ``` -------------------------------- ### tail Source: https://docs.rs/polars/latest/polars/prelude/struct.Series.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Get the tail of the Series. ```APIDOC ## pub fn tail(&self, length: Option) -> Series ### Description Get the tail of the Series. ``` -------------------------------- ### Sorting a Series with SortOptions Source: https://docs.rs/polars/latest/polars/chunked_array/ops/sort/options/struct.SortOptions.html Example demonstrating how to apply custom sorting options to a Series. ```rust let s = Series::new("a".into(), [Some(5), Some(2), Some(3), Some(4), None].as_ref()); let sorted = s .sort( SortOptions::default() .with_order_descending(true) .with_nulls_last(true) .with_multithreaded(false), ) .unwrap(); assert_eq!( sorted, Series::new("a".into(), [Some(5), Some(4), Some(3), Some(2), None].as_ref()) ); ``` -------------------------------- ### head Source: https://docs.rs/polars/latest/polars/prelude/struct.Series.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Get the head of the Series. ```APIDOC ## pub fn head(&self, length: Option) -> Series ### Description Get the head of the Series. ``` -------------------------------- ### Create DataFrame Source: https://docs.rs/polars/latest/polars/docs/eager/index.html Demonstrates creating DataFrames using the df! macro and from a vector of Columns. ```rust use polars::prelude::*; use polars::df; // use macro let df = df! [ "names" => ["a", "b", "c"], "values" => [1, 2, 3], "values_nulls" => [Some(1), None, Some(3)] ]?; // from a Vec let c1 = Column::new("names".into(), &["a", "b", "c"]); let c2 = Column::new("values".into(), &[Some(1), None, Some(3)]); let df = DataFrame::new_infer_height(vec![c1, c2])?; ``` -------------------------------- ### product Source: https://docs.rs/polars/latest/polars/prelude/struct.Series.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Get the product of an array. ```APIDOC ## pub fn product(&self) -> Result ### Description Get the product of an array. If the DataType is one of {Int8, UInt8, Int16, UInt16} the Series is first cast to Int64 to prevent overflow issues. ``` -------------------------------- ### last Source: https://docs.rs/polars/latest/polars/prelude/struct.LazyFrame.html?search= Get the last row. ```APIDOC ## pub fn last(self) -> LazyFrame ### Description Get the last row. Equivalent to `self.slice(-1, 1)`. ``` -------------------------------- ### Initialize Vector with Custom Allocator Source: https://docs.rs/polars/latest/polars/frame/group_by/type.GroupsSlice.html?search= Demonstrates creating a vector with a specific capacity using the System allocator. ```rust use std::alloc::System; let mut vec = Vec::with_capacity_in(10, System); // The vector contains no items, even though it has capacity for more assert_eq!(vec.len(), 0); assert!(vec.capacity() >= 10); // These are all done without reallocating... for i in 0..10 { vec.push(i); } assert_eq!(vec.len(), 10); assert!(vec.capacity() >= 10); // ...but this may make the vector reallocate vec.push(11); assert_eq!(vec.len(), 11); assert!(vec.capacity() >= 11); // A vector of a zero-sized type will always over-allocate, since no // allocation is necessary let vec_units = Vec::<(), System>::with_capacity_in(10, System); assert_eq!(vec_units.capacity(), usize::MAX); ``` -------------------------------- ### first Source: https://docs.rs/polars/latest/polars/prelude/struct.LazyFrame.html?search= Get the first row. ```APIDOC ## pub fn first(self) -> LazyFrame ### Description Get the first row. Equivalent to `self.slice(0, 1)`. ``` -------------------------------- ### Initialize HashSet with capacity and hasher Source: https://docs.rs/polars/latest/polars/datatypes/type.PlHashSet.html Creates an empty HashSet with a pre-allocated capacity and a custom hasher. ```rust use hashbrown::HashSet; use hashbrown::DefaultHashBuilder; let s = DefaultHashBuilder::default(); let mut set = HashSet::with_capacity_and_hasher(10, s); set.insert(1); ``` -------------------------------- ### starts_with Source: https://docs.rs/polars/latest/polars/prelude/trait.BinaryNameSpaceImpl.html?search=std%3A%3Avec Check if strings starts with a substring. ```APIDOC ## fn starts_with(&self, sub: &[u8]) -> ChunkedArray ### Description Check if strings starts with a substring. ``` -------------------------------- ### new Source: https://docs.rs/polars/latest/polars/prelude/type.StringChunkedBuilder.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Creates a new instance of the builder with a specified name and capacity. ```APIDOC ## pub fn new(name: PlSmallStr, capacity: usize) -> BinViewChunkedBuilder ### Description Creates a new BinViewChunkedBuilder instance. ### Parameters - **name** (PlSmallStr) - The name of the resulting array. - **capacity** (usize) - Number of string elements in the final array. ``` -------------------------------- ### starts_with

(pat: P) -> bool Source: https://docs.rs/polars/latest/polars/datatypes/struct.TimeZone.html?search=std%3A%3Avec Checks if the string starts with the given pattern. ```APIDOC ## pub fn starts_with

(&self, pat: P) -> bool ### Description Returns `true` if the given pattern matches a prefix of this string slice. ``` -------------------------------- ### tail Source: https://docs.rs/polars/latest/polars/prelude/struct.LazyFrame.html?search= Get the last n rows. ```APIDOC ## pub fn tail(self, n: u32) -> LazyFrame ### Description Get the last `n` rows. Equivalent to `self.slice(-(n as i64), n)`. ``` -------------------------------- ### get Source: https://docs.rs/polars/latest/polars/frame/struct.DataFrame.html Retrieves a row from the DataFrame by index. ```APIDOC ## pub fn get(&self, idx: usize) -> Option>> ### Description Get a row in the `DataFrame`. Beware this is slow. ``` -------------------------------- ### linear_spaces(start: Expr, end: Expr, num_samples: Expr, closed: ClosedInterval, as_array: bool) -> Result Source: https://docs.rs/polars/latest/polars/prelude/fn.linear_spaces.html Creates a column of linearly-spaced sequences from 'start', 'end', and 'num_samples' expressions. This function is available when the 'lazy' feature is enabled. ```APIDOC ## Function: linear_spaces ### Description Create a column of linearly-spaced sequences from 'start', 'end', and 'num_samples' expressions. ### Signature `pub fn linear_spaces(start: Expr, end: Expr, num_samples: Expr, closed: ClosedInterval, as_array: bool) -> Result` ### Parameters - **start** (Expr) - The starting value expression. - **end** (Expr) - The ending value expression. - **num_samples** (Expr) - The number of samples expression. - **closed** (ClosedInterval) - Defines the interval closure. - **as_array** (bool) - Whether to return as an array. ### Requirements - **Feature Flag**: Requires the `lazy` crate feature. ``` -------------------------------- ### Start a lazy computation Source: https://docs.rs/polars/latest/polars/docs/lazy/index.html Demonstrates initializing a LazyFrame from an eager DataFrame, a CSV file, or a Parquet file. ```rust use polars::prelude::*; use polars::df; let df = df![ "a" => [1, 2, 3], "b" => [None, Some("a"), Some("b")] ]?; // from an eager DataFrame let lf: LazyFrame = df.lazy(); // scan a csv file lazily let lf: LazyFrame = LazyCsvReader::new("some_path") .with_has_header(true) .finish()?; // scan a parquet file lazily let lf: LazyFrame = LazyFrame::scan_parquet("some_path", Default::default())?; ``` -------------------------------- ### Writeable::try_new Source: https://docs.rs/polars/latest/polars/prelude/file/enum.Writeable.html?search=std%3A%3Avec Initializes a new Writeable instance based on the provided path and cloud configuration. ```APIDOC ## pub fn try_new(path: PlRefPath, cloud_options: Option<&CloudOptions>, cloud_upload_chunk_size: usize, cloud_upload_concurrency: usize, io_metrics: Option>) -> Result ### Description Creates a new Writeable instance, abstracting over local or cloud file destinations. ### Parameters - **path** (PlRefPath) - The target file path. - **cloud_options** (Option<&CloudOptions>) - Configuration for cloud storage. - **cloud_upload_chunk_size** (usize) - Chunk size for cloud uploads. - **cloud_upload_concurrency** (usize) - Concurrency level for cloud uploads. - **io_metrics** (Option>) - Optional metrics tracking for I/O operations. ``` -------------------------------- ### tokio_mkdir_recursive Source: https://docs.rs/polars/latest/polars/prelude/mkdir/fn.tokio_mkdir_recursive.html?search= Asynchronously creates a directory and all its parent components. ```APIDOC ## Function: tokio_mkdir_recursive ### Description Creates a directory and all of its parent components asynchronously. This function is part of the `polars::prelude` module. ### Signature `pub async fn tokio_mkdir_recursive(path: &PlRefPath) -> Result<(), Error>` ### Requirements - **Feature Flag**: `polars-io` ### Parameters - **path** (&PlRefPath) - The path to the directory to be created. ``` -------------------------------- ### tokio_mkdir_recursive Source: https://docs.rs/polars/latest/polars/prelude/mkdir/fn.tokio_mkdir_recursive.html?search=std%3A%3Avec Asynchronously creates a directory and all its parent components. ```APIDOC ## Function: tokio_mkdir_recursive ### Description Asynchronously creates a directory and all its parent components. This function is available only when the `polars-io` crate feature is enabled. ### Signature `pub async fn tokio_mkdir_recursive(path: &PlRefPath) -> Result<(), Error>` ### Parameters - **path** (&PlRefPath) - The path to the directory to be created. ### Returns - **Result<(), Error>** - Returns `Ok(())` if the directory was created successfully, or an `Error` if the operation failed. ``` -------------------------------- ### size_bytes Source: https://docs.rs/polars/latest/polars/prelude/trait.BinaryNameSpaceImpl.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Get the size of the binary values in bytes. ```APIDOC ## fn size_bytes(&self) -> ChunkedArray ### Description Get the size of the binary values in bytes. ``` -------------------------------- ### from_uri Source: https://docs.rs/polars/latest/polars/prelude/struct.IpcReaderAsync.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes a new IpcReaderAsync instance from a given URI and optional cloud configuration. ```APIDOC ### pub async fn from_uri(uri: PlRefPath, cloud_options: Option<&CloudOptions>) -> Result Initializes an asynchronous IPC reader for the specified URI. Requires the `polars-io` feature. ``` -------------------------------- ### get Source: https://docs.rs/polars/latest/polars/prelude/struct.ScratchHashMap.html?search=std%3A%3Avec Clears the HashMap and returns a mutable reference to it. ```APIDOC ## pub fn get(&mut self) -> &mut HashMap ### Description Clears the current ScratchHashMap and returns a mutable reference to the underlying HashMap. ### Signature `pub fn get(&mut self) -> &mut HashMap` ``` -------------------------------- ### last Source: https://docs.rs/polars/latest/polars/prelude/struct.NullChunked.html?search=std%3A%3Avec Get the last element of the Series as a Scalar. ```APIDOC ## fn last(&self) -> Scalar ``` -------------------------------- ### Create HashMap with Hasher Source: https://docs.rs/polars/latest/polars/datatypes/type.PlHashMap.html Demonstrates creating a HashMap with a specific hash builder. ```rust use hashbrown::HashMap; use hashbrown::DefaultHashBuilder; let s = DefaultHashBuilder::default(); let mut map = HashMap::with_hasher(s); assert_eq!(map.len(), 0); assert_eq!(map.capacity(), 0); map.insert(1, 2); ``` -------------------------------- ### first Source: https://docs.rs/polars/latest/polars/prelude/struct.NullChunked.html?search=std%3A%3Avec Get the first element of the Series as a Scalar. ```APIDOC ## fn first(&self) -> Scalar ``` -------------------------------- ### pub fn mkdir_recursive(path: &PlRefPath) -> Result<(), Error> Source: https://docs.rs/polars/latest/polars/prelude/mkdir/fn.mkdir_recursive.html Creates a directory and all its parent components if they do not exist. ```APIDOC ## Function: mkdir_recursive ### Description Creates a directory and all its parent components if they do not exist. This function is available only when the `polars-io` crate feature is enabled. ### Signature `pub fn mkdir_recursive(path: &PlRefPath) -> Result<(), Error>` ### Parameters - **path** (&PlRefPath) - The path to the directory to be created. ### Returns - **Result<(), Error>** - Returns `Ok(())` if the directory was created successfully, or an `Error` if the operation failed. ``` -------------------------------- ### get Source: https://docs.rs/polars/latest/polars/prelude/struct.NullChunked.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves a single value from the array by its index. ```APIDOC ## fn get(&self, index: usize) -> Result, PolarsError> ### Description Get a single value by index. Don’t use this operation for loops as a runtime cast is needed for every iteration. ``` -------------------------------- ### CompatLevel::newest Source: https://docs.rs/polars/latest/polars/datatypes/struct.CompatLevel.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Returns the newest compatibility level. ```APIDOC ## pub const fn newest() -> CompatLevel ### Description Returns the newest compatibility level. ``` -------------------------------- ### last(self) -> LazyFrame Source: https://docs.rs/polars/latest/polars/prelude/struct.LazyFrame.html Get the last row. ```APIDOC ## last(self) -> LazyFrame ### Description Get the last row. Equivalent to `self.slice(-1, 1)`. ``` -------------------------------- ### first(self) -> LazyFrame Source: https://docs.rs/polars/latest/polars/prelude/struct.LazyFrame.html Get the first row. ```APIDOC ## first(self) -> LazyFrame ### Description Get the first row. Equivalent to `self.slice(0, 1)`. ``` -------------------------------- ### Box::new_uninit Source: https://docs.rs/polars/latest/polars/prelude/type.ArrayRef.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Constructs a new box with uninitialized contents. ```APIDOC ## pub fn new_uninit() -> Box> ### Description Constructs a new box with uninitialized contents. ``` -------------------------------- ### to_dot Source: https://docs.rs/polars/latest/polars/prelude/struct.LazyFrame.html?search= Get a dot language representation of the LogicalPlan. ```APIDOC ## pub fn to_dot(&self, optimized: bool) -> Result ### Description Get a dot language representation of the LogicalPlan. ### Parameters - **optimized** (bool) - Whether to return the representation of the optimized plan. ``` -------------------------------- ### PrefilterMaskSetting::init_from_env Source: https://docs.rs/polars/latest/polars/prelude/_internal/enum.PrefilterMaskSetting.html?search=std%3A%3Avec Initializes a new PrefilterMaskSetting instance based on environment variables. ```APIDOC ## fn init_from_env() -> PrefilterMaskSetting ### Description Initializes the PrefilterMaskSetting configuration by reading from the environment. ### Returns - **PrefilterMaskSetting** - The configured setting instance. ``` -------------------------------- ### get Source: https://docs.rs/polars/latest/polars/prelude/struct.Arc.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves the bytes stored at the specified location. ```APIDOC ## async fn get(&self, location: &Path) -> Result ### Description Return the bytes that are stored at the specified location. ### Parameters - **location** (&Path) - Required - The path of the object to retrieve. ``` -------------------------------- ### Initialization Methods Source: https://docs.rs/polars/latest/polars/prelude/type.Int32Chunked.html?search= Methods for initializing ChunkedArray instances. ```APIDOC ## Initialization Methods ### from_iter_values(name: PlSmallStr, it: impl Iterator::Native>) -> ChunkedArray Create a new ChunkedArray from an iterator. ### from_slice(name: PlSmallStr, v: &[::Native]) -> ChunkedArray Create a new ChunkedArray from a slice. ### from_slice_options(name: PlSmallStr, opt_v: &[Option<::Native>]) -> ChunkedArray Create a new ChunkedArray from a slice of options. ### from_iter_options(name: PlSmallStr, it: impl Iterator::Native>>) -> ChunkedArray Create a new ChunkedArray from an iterator of options. ``` -------------------------------- ### insert_full Source: https://docs.rs/polars/latest/polars/datatypes/type.PlIndexSet.html?search=std%3A%3Avec Insert a value into the set and get its index. ```APIDOC ## pub fn insert_full(&mut self, value: T) -> (usize, bool) ### Description Insert the value into the set, and get its index. Returns the index and a boolean indicating if it was a new insertion. ### Parameters - **value** (T) - Required - The value to insert. ``` -------------------------------- ### DataFrame Initialization Source: https://docs.rs/polars/latest/polars/frame/struct.DataFrame.html Methods for creating a new DataFrame instance, including empty initialization, construction from a vector of columns, and using the df! macro. ```APIDOC ## DataFrame::empty() ### Description Creates an empty DataFrame with shape (0, 0). ## DataFrame::new_infer_height(columns: Vec) ### Description Constructs a DataFrame from a vector of columns, inferring the height from the column lengths. ## df!(...) ### Description A macro for convenient DataFrame construction using key-value pairs. ``` -------------------------------- ### Compare Arc for Ordering Source: https://docs.rs/polars/latest/polars/chunked_array/object/registry/type.ObjectArrayGetter.html?search= Demonstrates partial comparison and relational operators for Arc instances. ```rust use std::sync::Arc; use std::cmp::Ordering; let five = Arc::new(5); assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6))); ``` ```rust use std::sync::Arc; let five = Arc::new(5); assert!(five < Arc::new(6)); ``` ```rust use std::sync::Arc; let five = Arc::new(5); assert!(five <= Arc::new(5)); ``` ```rust use std::sync::Arc; let five = Arc::new(5); assert!(five > Arc::new(4)); ``` ```rust use std::sync::Arc; let five = Arc::new(5); assert!(five >= Arc::new(5)); ``` -------------------------------- ### get Source: https://docs.rs/polars/latest/polars/datatypes/type.PlHashMap.html?search=std%3A%3Avec Returns a reference to the value corresponding to the key. ```APIDOC ## pub fn get(&self, k: &Q) -> Option<&V> ### Description Returns a reference to the value corresponding to the key. The key may be any borrowed form of the map’s key type, but `Hash` and `Eq` on the borrowed form must match those for the key type. ``` -------------------------------- ### get_opts Source: https://docs.rs/polars/latest/polars/chunked_array/object/registry/type.ObjectArrayGetter.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Performs a get request with the specified options. ```APIDOC ## fn get_opts ### Description Performs a get request with the specified options. ### Signature `fn get_opts<'life0, 'life1, 'async_trait>(&'life0 self, location: &'life1 Path, options: GetOptions) -> Pin> + Send + 'async_trait>>` ``` -------------------------------- ### pub fn mkdir_recursive(path: &PlRefPath) -> Result<(), Error> Source: https://docs.rs/polars/latest/polars/prelude/mkdir/fn.mkdir_recursive.html?search= Creates a directory and all its parent components recursively. ```APIDOC ## Function: mkdir_recursive ### Description Creates a directory and all its parent components recursively. This function is available when the `polars-io` feature is enabled. ### Signature `pub fn mkdir_recursive(path: &PlRefPath) -> Result<(), Error>` ### Parameters - **path** (&PlRefPath) - The path to the directory to be created. ### Returns - **Result<(), Error>** - Returns `Ok(())` if the directory was created successfully, or an `Error` if the operation failed. ``` -------------------------------- ### slice Source: https://docs.rs/polars/latest/polars/prelude/struct.CategoricalNameSpace.html?search=std%3A%3Avec Slices the categorical values starting from a given offset. ```APIDOC ### pub fn slice(self, offset: i64, length: Option) -> Expr Returns an expression that slices the categorical values starting at the specified offset with an optional length. ``` -------------------------------- ### pub fn mkdir_recursive(path: &PlRefPath) -> Result<(), Error> Source: https://docs.rs/polars/latest/polars/prelude/mkdir/fn.mkdir_recursive.html?search=std%3A%3Avec Creates a directory and all its parent components recursively. ```APIDOC ## Function: mkdir_recursive ### Description Creates a directory and all its parent components recursively. This function is part of the `polars::prelude` module. ### Signature `pub fn mkdir_recursive(path: &PlRefPath) -> Result<(), Error>` ### Requirements - **Crate Feature**: `polars-io` ### Parameters - **path** (&PlRefPath) - The path to the directory to be created. ### Returns - **Result<(), Error>** - Returns `Ok(())` if the directory was created successfully, or an `Error` if the operation failed. ``` -------------------------------- ### pub fn repeat(&self, n: usize) -> String Source: https://docs.rs/polars/latest/polars/prelude/datatypes/struct.TimeZone.html?search=u32+-%3E+bool Creates a new String by repeating the original string n times. ```APIDOC ## pub fn repeat(&self, n: usize) -> String ### Description Creates a new String by repeating a string n times. ### Parameters - **&self** - The string slice to repeat. - **n** (usize) - The number of times to repeat the string. ### Panics This function will panic if the resulting capacity would overflow. ### Returns - **String** - A new String containing the repeated sequence. ``` -------------------------------- ### Check for prefix Source: https://docs.rs/polars/latest/polars/datatypes/struct.PlSmallStr.html Checks if the string starts with a specific pattern. ```rust let bananas = "bananas"; assert!(bananas.starts_with("bana")); assert!(!bananas.starts_with("nana")); ``` ```rust let bananas = "bananas"; // Note that both of these assert successfully. assert!(bananas.starts_with(&['b', 'a', 'n', 'a'])); assert!(bananas.starts_with(&['a', 'b', 'c', 'd'])); ``` -------------------------------- ### Iterate over ChunkedArray Source: https://docs.rs/polars/latest/polars/chunked_array/struct.ChunkedArray.html Examples of forward and backward iteration over a ChunkedArray. ```rust fn iter_forward(ca: &Float32Chunked) { ca.iter() .for_each(|opt_v| println!("{:?}", opt_v)) } fn iter_backward(ca: &Float32Chunked) { ca.iter() .rev() .for_each(|opt_v| println!("{:?}", opt_v)) } ``` -------------------------------- ### init_from_env Source: https://docs.rs/polars/latest/polars/prelude/_internal/enum.PrefilterMaskSetting.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Initializes a PrefilterMaskSetting instance based on environment variables. ```APIDOC ## pub fn init_from_env() -> PrefilterMaskSetting ### Description Initializes the PrefilterMaskSetting from the current environment configuration. ### Returns - **PrefilterMaskSetting** - The initialized setting instance. ``` -------------------------------- ### last_non_null Source: https://docs.rs/polars/latest/polars/prelude/struct.NullChunked.html?search=std%3A%3Avec Get the last non-null element of the Series as a Scalar. ```APIDOC ## fn last_non_null(&self) -> Scalar ``` -------------------------------- ### init_from_env Source: https://docs.rs/polars/latest/polars/prelude/_internal/enum.PrefilterMaskSetting.html?search=u32+-%3E+bool Initializes a PrefilterMaskSetting instance based on environment variables. ```APIDOC ## pub fn init_from_env() -> PrefilterMaskSetting ### Description Initializes the PrefilterMaskSetting configuration by reading from the environment. ### Returns - **PrefilterMaskSetting** - The configured setting based on environment variables. ```