Skip to content

Commit

Permalink
support negative index
Browse files Browse the repository at this point in the history
  • Loading branch information
barak1412 committed Sep 17, 2024
1 parent aa35c03 commit efd3ac3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 13 deletions.
9 changes: 5 additions & 4 deletions crates/polars-core/src/chunked_array/struct_/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crate::chunked_array::ChunkedArray;
use crate::prelude::sort::arg_sort_multiple::{_get_rows_encoded_arr, _get_rows_encoded_ca};
use crate::prelude::*;
use crate::series::Series;
use crate::utils::Container;
use crate::utils::{slice_offsets, Container};

pub type StructChunked = ChunkedArray<StructType>;

Expand Down Expand Up @@ -373,12 +373,13 @@ impl StructChunked {
.ok_or_else(|| polars_err!(StructFieldNotFound: "{}", name))
}
pub fn field_by_index(&self, field_idx: i64) -> PolarsResult<Series> {
if field_idx < 0 || field_idx >= (self.struct_fields().len() as i64) {
if field_idx >= (self.struct_fields().len() as i64) {
polars_bail!(
OutOfBounds: "Given field index {} is Out Of Bound", field_idx
OutOfBounds: "Given field index {} is out of bound", field_idx
)
}
Ok(self.field_as_series(field_idx as usize))
let (field_idx, _) = slice_offsets(field_idx, 0, self.struct_fields().len());
Ok(self.field_as_series(field_idx))
}
pub(crate) fn set_outer_validity(&mut self, validity: Option<Bitmap>) {
assert_eq!(self.chunks().len(), 1);
Expand Down
18 changes: 9 additions & 9 deletions py-polars/tests/unit/operations/namespaces/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,17 +103,17 @@ def test_empty_list_eval_schema_5734() -> None:


def test_field_by_index_18732() -> None:
df = pl.DataFrame({"foo": [{"a": 1}, {"a": 2}]})
df = pl.DataFrame({"foo": [{"a": 1, "b": 2}, {"a": 2, "b": 1}]})

# lower bound
with pytest.raises(OutOfBoundsError, match=r"Given field index -1 is Out Of Bound"):
df.filter(pl.col.foo.struct[-1] == 1)

# upper bound
with pytest.raises(OutOfBoundsError, match=r"Given field index 1 is Out Of Bound"):
df.filter(pl.col.foo.struct[1] == 1)
# illegal upper bound
with pytest.raises(OutOfBoundsError, match=r"Given field index 2 is out of bound"):
df.filter(pl.col.foo.struct[2] == 1)

# legal
expected_df = pl.DataFrame({"foo": [{"a": 1}]})
expected_df = pl.DataFrame({"foo": [{"a": 1, "b": 2}]})
result_df = df.filter(pl.col.foo.struct[0] == 1)
assert_frame_equal(expected_df, result_df)

expected_df = pl.DataFrame({"foo": [{"a": 2, "b": 1}]})
result_df = df.filter(pl.col.foo.struct[-1] == 1)
assert_frame_equal(expected_df, result_df)

0 comments on commit efd3ac3

Please sign in to comment.