Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/crates/polars-plan/src/plans/python/utils.rs
6940 views
1
use polars_core::error::{PolarsResult, polars_err};
2
use polars_core::frame::DataFrame;
3
use polars_core::schema::SchemaRef;
4
use polars_ffi::version_0::SeriesExport;
5
use pyo3::intern;
6
use pyo3::prelude::*;
7
8
pub fn python_df_to_rust(py: Python, df: Bound<PyAny>) -> PolarsResult<DataFrame> {
9
let err = |_| polars_err!(ComputeError: "expected a polars.DataFrame; got {}", df);
10
let pydf = df.getattr(intern!(py, "_df")).map_err(err)?;
11
12
let width = pydf.call_method0(intern!(py, "width")).unwrap();
13
let width = width.extract::<usize>().unwrap();
14
15
// Don't resize the Vec<> so that the drop of the SeriesExport will not be caleld.
16
let mut export: Vec<SeriesExport> = Vec::with_capacity(width);
17
let location = export.as_mut_ptr();
18
19
let _ = pydf
20
.call_method1(intern!(py, "_export_columns"), (location as usize,))
21
.unwrap();
22
23
unsafe { polars_ffi::version_0::import_df(location, width) }
24
}
25
26
pub(crate) fn python_schema_to_rust(py: Python, schema: Bound<PyAny>) -> PolarsResult<SchemaRef> {
27
let err = |_| polars_err!(ComputeError: "expected a polars.Schema; got {}", schema);
28
let df = schema.call_method0("to_frame").map_err(err)?;
29
python_df_to_rust(py, df).map(|df| df.schema().clone())
30
}
31
32