Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
16 changes: 16 additions & 0 deletions bigframes/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,22 @@ def to_numpy(self, dtype=None, *, allow_large_results=None, **kwargs) -> np.ndar
def __len__(self):
return self.shape[0]

def item(self):
"""
Return the first element of the underlying data as a Python scalar.

Returns:
scalar: The first element of the Index.

Raises:
ValueError: If the Index does not contain exactly one element.
"""
peeked = self.to_series().peek(2)
if len(peeked) == 1:
return peeked.iloc[0]
else:
raise ValueError("can only convert an array of size 1 to a Python scalar")


def _should_create_datetime_index(block: blocks.Block) -> bool:
if len(block.index.dtypes) != 1:
Expand Down
16 changes: 16 additions & 0 deletions bigframes/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -960,6 +960,22 @@ def peek(
as_series.name = self.name
return as_series

def item(self):
"""
Return the first element of the underlying data as a Python scalar.

Returns:
scalar: The first element of the Series.

Raises:
ValueError: If the Series does not contain exactly one element.
"""
peeked = self.peek(2)
if len(peeked) == 1:
return peeked.iloc[0]
else:
raise ValueError("can only convert an array of size 1 to a Python scalar")

def nlargest(self, n: int = 5, keep: str = "first") -> Series:
if keep not in ("first", "last", "all"):
raise ValueError("'keep must be one of 'first', 'last', or 'all'")
Expand Down
20 changes: 20 additions & 0 deletions tests/system/small/test_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,3 +458,23 @@ def test_multiindex_repr_includes_all_names(session):
)
index = session.read_pandas(df).set_index(["A", "B"]).index
assert "names=['A', 'B']" in repr(index)


def test_index_item(session):
# Test with a single item
idx_single = bpd.Index([42], session=session)
assert idx_single.item() == 42

# Test with multiple items
idx_multiple = bpd.Index([1, 2, 3], session=session)
with pytest.raises(
ValueError, match="can only convert an array of size 1 to a Python scalar"
):
idx_multiple.item()

# Test with an empty Index
idx_empty = bpd.Index([], dtype="Int64", session=session)
with pytest.raises(
ValueError, match="can only convert an array of size 1 to a Python scalar"
):
idx_empty.item()
20 changes: 20 additions & 0 deletions tests/system/small/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -4636,3 +4636,23 @@ def test_series_to_pandas_dry_run(scalars_df_index):

assert isinstance(result, pd.Series)
assert len(result) > 0


def test_series_item(session):
# Test with a single item
s_single = bigframes.pandas.Series([42], session=session)
assert s_single.item() == 42

# Test with multiple items
s_multiple = bigframes.pandas.Series([1, 2, 3], session=session)
with pytest.raises(
ValueError, match="can only convert an array of size 1 to a Python scalar"
):
s_multiple.item()

# Test with an empty Series
s_empty = bigframes.pandas.Series([], dtype="Int64", session=session)
with pytest.raises(
ValueError, match="can only convert an array of size 1 to a Python scalar"
):
s_empty.item()
23 changes: 23 additions & 0 deletions third_party/bigframes_vendored/pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1087,6 +1087,29 @@ def unique(self, level: Hashable | int | None = None):
"""
raise NotImplementedError(constants.ABSTRACT_METHOD_ERROR_MESSAGE)

def item(self, *args, **kwargs):
"""
Return the first element of the underlying data as a Python scalar.

Returns
-------
scalar
The first element of Index.

Raises
------
ValueError
If the data is not length = 1.

Examples
--------
>>> import bigframes.pandas as bpd
>>> s = bpd.Series([1], index=['a'])
>>> s.index.item()
'a'
"""
raise NotImplementedError(constants.ABSTRACT_METHOD_ERROR_MESSAGE)

def to_numpy(self, dtype, *, allow_large_results=None):
"""
A NumPy ndarray representing the values in this Series or Index.
Expand Down
23 changes: 23 additions & 0 deletions third_party/bigframes_vendored/pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -4933,6 +4933,29 @@ def kurt(self):
"""
raise NotImplementedError(constants.ABSTRACT_METHOD_ERROR_MESSAGE)

def item(self: Series, *args, **kwargs):
"""
Return the first element of the underlying data as a Python scalar.

Returns
-------
scalar
The first element of Series.

Raises
------
ValueError
If the data is not length = 1.

Examples
--------
>>> import bigframes.pandas as bpd
>>> s = bpd.Series([1])
>>> s.item()
1
"""
raise NotImplementedError(constants.ABSTRACT_METHOD_ERROR_MESSAGE)

def items(self):
"""
Lazily iterate over (index, value) tuples.
Expand Down