Skip to content

Commit c149414

Browse files
authored
match getitem behavior to pandas with empty bool array (#341)
1 parent 127f913 commit c149414

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/nested_pandas/nestedframe/core.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from pandas._typing import Any, AnyAll, Axis, Hashable, IndexLabel, Mapping
1414
from pandas.api.extensions import no_default
1515
from pandas.core.computation.eval import Expr, ensure_scope
16+
from pandas.core.dtypes.common import is_bool_dtype
1617
from pandas.core.dtypes.inference import is_list_like
1718

1819
from nested_pandas.nestedframe.expr import (
@@ -253,6 +254,8 @@ def _getitem_str(self, item):
253254
def _is_key_list(self, item):
254255
if not is_list_like(item):
255256
return False
257+
if is_bool_dtype(item):
258+
return False
256259
for k in item:
257260
if not isinstance(k, str):
258261
return False

tests/nested_pandas/nestedframe/test_nestedframe.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,28 @@ def test_get_nested_columns_errors():
256256
base[["a", "nested.a", "wrong.b"]]
257257

258258

259+
def test_getitem_empty_bool_array():
260+
"""Test that __getitem__ works as expected with an empty boolean array"""
261+
base = NestedFrame(data={"a": [1, 2, 3], "b": [2, 4, 6]}, index=[0, 1, 2])
262+
263+
nested = pd.DataFrame(
264+
data={"c": [0, 2, 4, 1, 4, 3, 1, 4, 1], "d": [5, 4, 7, 5, 3, 1, 9, 3, 4]},
265+
index=[0, 0, 0, 1, 1, 1, 2, 2, 2],
266+
)
267+
268+
base = base.add_nested(nested, "nested")
269+
270+
bool_index = np.array([], dtype=bool)
271+
272+
with pytest.raises(ValueError, match="Item wrong length"):
273+
_ = base[bool_index]
274+
275+
df = base.iloc[:0][bool_index]
276+
assert len(df) == 0
277+
assert np.all(df.columns == base.columns)
278+
assert df.dtypes.equals(base.dtypes)
279+
280+
259281
def test_set_or_replace_nested_col():
260282
"""Test that __setitem__ can set or replace a column in an existing nested structure"""
261283

0 commit comments

Comments
 (0)