cfpyo3_bindings/df/
meta.rs

1use super::DataFrameF64;
2use cfpyo3_core::df::{ColumnsDtype, DataFrame, IndexDtype};
3use numpy::{
4    ndarray::{ArrayView1, ArrayView2},
5    IntoPyArray, PyArray1, PyArray2, PyArrayMethods,
6};
7use pyo3::prelude::*;
8
9impl DataFrameF64 {
10    pub fn to_core<'py>(&'py self, py: Python<'py>) -> DataFrame<'py, f64> {
11        let index = self.get_index_array(py);
12        let columns = self.get_columns_array(py);
13        let values = self.get_values_array(py);
14        DataFrame::new_view(index, columns, values)
15    }
16    pub fn from_core(py: Python, df: DataFrame<f64>) -> Self {
17        match df {
18            DataFrame::View(_) => {
19                panic!("`DataFrameF64::from_core` should be called with an `OwnedDataFrame`")
20            }
21            DataFrame::Owned(df) => DataFrameF64 {
22                index: df.index.into_pyarray(py).unbind(),
23                columns: df.columns.into_pyarray(py).unbind(),
24                values: df.values.into_pyarray(py).unbind(),
25            },
26        }
27    }
28    pub(crate) fn get_index_array<'py>(&'py self, py: Python<'py>) -> ArrayView1<'py, IndexDtype> {
29        unsafe { self.index.bind(py).as_array() }
30    }
31    pub(crate) fn get_columns_array<'py>(
32        &'py self,
33        py: Python<'py>,
34    ) -> ArrayView1<'py, ColumnsDtype> {
35        unsafe { self.columns.bind(py).as_array() }
36    }
37    pub(crate) fn get_values_array<'py>(&'py self, py: Python<'py>) -> ArrayView2<'py, f64> {
38        unsafe { self.values.bind(py).as_array() }
39    }
40}
41
42#[pymethods]
43impl DataFrameF64 {
44    #[staticmethod]
45    fn new(
46        index: Py<PyArray1<IndexDtype>>,
47        columns: Py<PyArray1<ColumnsDtype>>,
48        values: Py<PyArray2<f64>>,
49    ) -> Self {
50        DataFrameF64 {
51            index,
52            columns,
53            values,
54        }
55    }
56
57    #[getter]
58    fn index(&self, py: Python) -> Py<PyArray1<IndexDtype>> {
59        self.index.clone_ref(py)
60    }
61
62    #[getter]
63    fn columns(&self, py: Python) -> Py<PyArray1<ColumnsDtype>> {
64        self.columns.clone_ref(py)
65    }
66
67    #[getter]
68    fn values(&self, py: Python) -> Py<PyArray2<f64>> {
69        self.values.clone_ref(py)
70    }
71
72    #[getter]
73    fn shape(&self, py: Python) -> (usize, usize) {
74        (
75            self.get_index_array(py).len(),
76            self.get_columns_array(py).len(),
77        )
78    }
79
80    fn with_data(&self, py: Python, values: Py<PyArray2<f64>>) -> Self {
81        DataFrameF64 {
82            index: self.index.clone_ref(py),
83            columns: self.columns.clone_ref(py),
84            values,
85        }
86    }
87}