Struct DataFrame

Source
pub struct DataFrame {
    pub columns: Vec<Box<dyn SeriesTrait>>,
    /* private fields */
}
Expand description

高性能数据处理框架的核心数据结构 DataFrame。

DataFrame 是一个二维表格数据结构,类似于电子表格或数据库表, 由多个具有相同长度的列(Series)组成。每列可以包含不同类型的数据。

§特性

  • 类型安全: 使用 Rust 的类型系统确保数据类型安全
  • 高性能: 利用 Rayon 实现并行处理
  • 内存高效: 零拷贝操作和智能内存管理
  • 丰富的操作: 支持过滤、连接、分组、排序等操作

§示例

use axion::dataframe::DataFrame;
use axion::series::Series;
 
// 创建一个简单的 DataFrame
let name_series = Series::new("姓名".to_string(), vec!["张三", "李四", "王五"]);
let age_series = Series::new("年龄".to_string(), vec![25, 30, 35]);
 
let df = DataFrame::new(vec![
    Box::new(name_series),
    Box::new(age_series),
])?;
 
println!("{}", df);

Fields§

§columns: Vec<Box<dyn SeriesTrait>>

存储所有列的向量,每列都是一个实现了 SeriesTrait 的对象

Implementations§

Source§

impl DataFrame

Source

pub fn new(columns: Vec<Box<dyn SeriesTrait>>) -> AxionResult<Self>

从列向量创建新的 DataFrame。

§参数
  • columns - 实现了 SeriesTrait 的列向量
§返回值

成功时返回新创建的 DataFrame,失败时返回错误

§错误
  • AxionError::MismatchedLengths - 当列长度不一致时
  • AxionError::DuplicateColumnName - 当存在重复列名时
§示例
let columns = vec![
    Box::new(Series::new("A".to_string(), vec![1, 2, 3])),
    Box::new(Series::new("B".to_string(), vec![4, 5, 6])),
];
let df = DataFrame::new(columns)?;
Source

pub fn new_empty() -> Self

创建一个空的 DataFrame。

§返回值

返回一个没有行和列的 DataFrame

§示例
let empty_df = DataFrame::new_empty();
assert_eq!(empty_df.shape(), (0, 0));
Source

pub fn shape(&self) -> (usize, usize)

获取 DataFrame 的形状(行数,列数)。

§返回值

返回一个元组 (行数, 列数)

§示例
let (rows, cols) = df.shape();
println!("DataFrame 有 {} 行 {} 列", rows, cols);
Source

pub fn height(&self) -> usize

获取 DataFrame 的行数。

Source

pub fn width(&self) -> usize

获取 DataFrame 的列数。

Source

pub fn columns_names(&self) -> Vec<&str>

获取所有列名的向量。

§返回值

返回包含所有列名的字符串切片向量

Source

pub fn dtypes(&self) -> Vec<DataType>

获取所有列的数据类型。

§返回值

返回包含所有列数据类型的向量

Source

pub fn schema(&self) -> &HashMap<String, DataType>

获取 DataFrame 的模式(列名到数据类型的映射)。

Source

pub fn column(&self, name: &str) -> AxionResult<&dyn SeriesTrait>

根据列名获取列的引用。

§参数
  • name - 要查找的列名
§返回值

成功时返回列的引用,失败时返回 ColumnNotFound 错误

Source

pub fn column_mut<'a>( &'a mut self, name: &str, ) -> AxionResult<&'a mut dyn SeriesTrait>

根据列名获取列的可变引用。

Source

pub fn column_at(&self, index: usize) -> AxionResult<&dyn SeriesTrait>

根据索引获取列的引用。

§参数
  • index - 列的索引位置
Source

pub fn column_at_mut( &mut self, index: usize, ) -> AxionResult<&mut dyn SeriesTrait>

根据索引获取列的可变引用。

Source

pub fn add_column(&mut self, series: Box<dyn SeriesTrait>) -> AxionResult<()>

向 DataFrame 添加一个新列。

§参数
  • series - 要添加的列,必须实现 SeriesTrait
§错误
  • AxionError::MismatchedLengths - 新列长度与现有行数不匹配
  • AxionError::DuplicateColumnName - 列名已存在
§示例
let new_col = Series::new("新列".to_string(), vec![1, 2, 3]);
df.add_column(Box::new(new_col))?;
Source

pub fn drop_column(&mut self, name: &str) -> AxionResult<Box<dyn SeriesTrait>>

从 DataFrame 中删除指定列。

§参数
  • name - 要删除的列名
§返回值

返回被删除的列

§错误
  • AxionError::ColumnNotFound - 指定列不存在
Source

pub fn rename_column( &mut self, old_name: &str, new_name: &str, ) -> AxionResult<()>

重命名 DataFrame 中的列。

§参数
  • old_name - 当前列名
  • new_name - 新列名
§错误
  • AxionError::ColumnNotFound - 原列名不存在
  • AxionError::DuplicateColumnName - 新列名已存在
Source

pub fn downcast_column<T>(&self, name: &str) -> AxionResult<&Series<T>>
where T: DataTypeTrait + 'static, Series<T>: 'static,

将列向下转型为特定类型的 Series。

§类型参数
  • T - 目标数据类型
§参数
  • name - 列名
§返回值

成功时返回指定类型的 Series 引用

Source

pub fn is_empty(&self) -> bool

检查 DataFrame 是否为空。

§返回值

如果没有行或没有列则返回 true

Source

pub fn head(&self, n: usize) -> DataFrame

获取 DataFrame 的前 n 行。

§参数
  • n - 要获取的行数
§返回值

返回包含前 n 行的新 DataFrame

Source

pub fn tail(&self, n: usize) -> DataFrame

获取 DataFrame 的后 n 行。

§参数
  • n - 要获取的行数
Source

pub fn select(&self, names: &[&str]) -> AxionResult<DataFrame>

选择指定的列创建新的 DataFrame。

§参数
  • names - 要选择的列名数组
§返回值

返回只包含指定列的新 DataFrame

Source

pub fn drop(&self, name_to_drop: &str) -> AxionResult<DataFrame>

删除指定列后创建新的 DataFrame。

§参数
  • name_to_drop - 要删除的列名
Source

pub fn filter(&self, mask: &Series<bool>) -> AxionResult<DataFrame>

根据布尔掩码过滤 DataFrame 行。

§参数
  • mask - 布尔类型的 Series,true 表示保留该行
§返回值

返回过滤后的新 DataFrame

§错误
  • AxionError::MismatchedLengths - 掩码长度与 DataFrame 行数不匹配
Source

pub fn par_filter(&self, mask: &Series<bool>) -> AxionResult<DataFrame>

并行过滤 DataFrame 行,提供更好的性能。

该方法使用 Rayon 并行处理每一列的过滤操作, 在处理大型数据集时能显著提升性能。

§参数
  • mask - 布尔类型的 Series,true 表示保留该行
§返回值

返回过滤后的新 DataFrame

Source

pub fn inner_join( &self, right: &DataFrame, left_on: &str, right_on: &str, ) -> AxionResult<DataFrame>

内连接操作。

只保留两个 DataFrame 中连接键都存在的行。

§参数
  • right - 右侧 DataFrame
  • left_on - 左侧连接键列名
  • right_on - 右侧连接键列名
§返回值

返回连接后的新 DataFrame

Source

pub fn left_join( &self, right: &DataFrame, left_on: &str, right_on: &str, ) -> AxionResult<DataFrame>

左连接操作。

保留左侧 DataFrame 的所有行,如果右侧没有匹配则填充空值。

Source

pub fn right_join( &self, right: &DataFrame, left_on: &str, right_on: &str, ) -> AxionResult<DataFrame>

右连接操作。

保留右侧 DataFrame 的所有行,如果左侧没有匹配则填充空值。

Source

pub fn outer_join( &self, right: &DataFrame, left_on: &str, right_on: &str, ) -> AxionResult<DataFrame>

外连接操作。

保留两个 DataFrame 的所有行,没有匹配的地方填充空值。

Source

pub fn groupby<'a>(&'a self, keys: &[&str]) -> AxionResult<GroupBy<'a>>

创建分组操作对象。

§参数
  • keys - 用于分组的列名数组
§返回值

返回 GroupBy 对象,可用于执行聚合操作

§示例
let grouped = df.groupby(&["类别"])?;
let result = grouped.sum()?;
Source

pub fn sort(&self, by: &[&str], descending: &[bool]) -> AxionResult<DataFrame>

对 DataFrame 进行排序。

§参数
  • by - 用于排序的列名数组
  • descending - 对应每列的排序方向,true 为降序,false 为升序
§返回值

返回排序后的新 DataFrame

§错误
  • AxionError::InvalidArgument - 列名数组和排序方向数组长度不匹配
  • AxionError::UnsupportedOperation - 尝试对不支持排序的数据类型进行排序
§示例
// 按年龄升序,姓名降序排序
let sorted_df = df.sort(&["年龄", "姓名"], &[false, true])?;
Source

pub fn to_csv( &self, filepath: impl AsRef<Path>, options: Option<WriteCsvOptions>, ) -> AxionResult<()>

将 DataFrame 导出为 CSV 文件。

§参数
  • filepath - 输出文件路径
  • options - 可选的 CSV 写入配置
§错误
  • AxionError::IoError - 文件创建或写入失败
§示例
use axion::io::csv::WriteCsvOptions;
 
// 使用默认配置导出
df.to_csv("output.csv", None)?;
 
// 使用自定义配置导出
let options = WriteCsvOptions {
    has_header: true,
    delimiter: b';',
    ..Default::default()
};
df.to_csv("output.csv", Some(options))?;
Source

pub fn to_csv_writer<W: Write>( &self, writer: &mut W, options: Option<WriteCsvOptions>, ) -> AxionResult<()>

将 DataFrame 写入到实现了 Write trait 的写入器中。

这是核心的 CSV 写入逻辑。

§参数
  • writer - 实现了 std::io::Write 的写入器
  • options - 可选的 CSV 写入配置

Trait Implementations§

Source§

impl Clone for DataFrame

Source§

fn clone(&self) -> DataFrame

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DataFrame

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for DataFrame

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for DataFrame

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.