Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(python): Implement Struct support for Series.to_numpy #16383

Merged
merged 3 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion py-polars/src/interop/numpy/to_numpy_df.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ impl PyDataFrame {
}
}

fn df_to_numpy(
pub(super) fn df_to_numpy(
py: Python,
df: &DataFrame,
order: IndexOrder,
Expand Down
29 changes: 14 additions & 15 deletions py-polars/src/interop/numpy/to_numpy_series.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,12 @@ use pyo3::intern;
use pyo3::prelude::*;
use pyo3::types::PySlice;

use super::to_numpy_df::df_to_numpy;
use super::utils::{
create_borrowed_np_array, polars_dtype_to_np_temporal_dtype, reshape_numpy_array,
};
use crate::conversion::chunked_array::{decimal_to_pyobject_iter, time_to_pyobject_iter};
use crate::conversion::ObjectValue;
use crate::error::PyPolarsErr;
use crate::raise_err;
use crate::series::PySeries;

#[pymethods]
Expand Down Expand Up @@ -50,7 +49,7 @@ pub(super) fn series_to_numpy(
if s.is_empty() {
// Take this path to ensure a writable array.
// This does not actually copy data for an empty Series.
return series_to_numpy_with_copy(py, s, true);
return Ok(series_to_numpy_with_copy(py, s, true));
}
if let Some((mut arr, writable_flag)) = try_series_to_numpy_view(py, s, false, allow_copy) {
if writable && !writable_flag {
Expand All @@ -70,7 +69,7 @@ pub(super) fn series_to_numpy(
));
}

series_to_numpy_with_copy(py, s, writable)
Ok(series_to_numpy_with_copy(py, s, writable))
}

/// Create a NumPy view of the given Series.
Expand Down Expand Up @@ -206,9 +205,9 @@ fn array_series_to_numpy_view(py: Python, s: &Series, writable: bool) -> PyObjec
/// Convert a Series to a NumPy ndarray, copying data in the process.
///
/// This method will cast integers to floats so that `null = np.nan`.
fn series_to_numpy_with_copy(py: Python, s: &Series, writable: bool) -> PyResult<PyObject> {
fn series_to_numpy_with_copy(py: Python, s: &Series, writable: bool) -> PyObject {
use DataType::*;
let out = match s.dtype() {
match s.dtype() {
Int8 => numeric_series_to_numpy::<Int8Type, f32>(py, s),
Int16 => numeric_series_to_numpy::<Int16Type, f32>(py, s),
Int32 => numeric_series_to_numpy::<Int32Type, f64>(py, s),
Expand Down Expand Up @@ -276,6 +275,12 @@ fn series_to_numpy_with_copy(py: Python, s: &Series, writable: bool) -> PyResult
},
List(_) => list_series_to_numpy(py, s, writable),
Array(_, _) => array_series_to_numpy(py, s, writable),
Struct(_) => {
let ca = s.struct_().unwrap();
let df = ca.clone().unnest();
// TODO: How should we determine the IndexOrder here?
df_to_numpy(py, &df, IndexOrder::Fortran, writable, true).unwrap()
stinodego marked this conversation as resolved.
Show resolved Hide resolved
},
#[cfg(feature = "object")]
Object(_, _) => {
let ca = s
Expand All @@ -290,14 +295,8 @@ fn series_to_numpy_with_copy(py: Python, s: &Series, writable: bool) -> PyResult
let values = std::iter::repeat(f32::NAN).take(n);
PyArray1::from_iter_bound(py, values).into_py(py)
},
dt => {
raise_err!(
format!("`to_numpy` not supported for dtype {dt:?}"),
ComputeError
);
},
};
Ok(out)
Unknown(_) | BinaryOffset => unreachable!(),
}
}

/// Convert numeric types to f32 or f64 with NaN representing a null value.
Expand Down Expand Up @@ -389,7 +388,7 @@ fn list_series_to_numpy(py: Python, s: &Series, writable: bool) -> PyObject {
fn array_series_to_numpy(py: Python, s: &Series, writable: bool) -> PyObject {
let ca = s.array().unwrap();
let s_inner = ca.get_inner();
let np_array_flat = series_to_numpy_with_copy(py, &s_inner, writable).unwrap();
let np_array_flat = series_to_numpy_with_copy(py, &s_inner, writable);

// Reshape to the original shape.
let DataType::Array(_, width) = s.dtype() else {
Expand Down
11 changes: 11 additions & 0 deletions py-polars/tests/unit/interop/numpy/test_to_numpy_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,17 @@ def test_series_to_numpy_list(chunked: bool) -> None:
assert_allow_copy_false_raises(s)


def test_series_to_numpy_struct_numeric_supertype() -> None:
values = [{"a": 1, "b": 2.0}, {"a": 3, "b": 4.0}, {"a": 5, "b": None}]
s = pl.Series(values)
result = s.to_numpy(use_pyarrow=False)

expected = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, np.nan]])
assert_array_equal(result, expected)
assert result.dtype == np.float64
assert_allow_copy_false_raises(s)


def test_to_numpy_null() -> None:
s = pl.Series([None, None], dtype=pl.Null)
result = s.to_numpy(use_pyarrow=False)
Expand Down