Skip to content

TST/REF: collect indexing tests by method #37729

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

Merged
merged 7 commits into from
Nov 10, 2020
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
17 changes: 17 additions & 0 deletions pandas/tests/frame/indexing/test_getitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
CategoricalIndex,
DataFrame,
MultiIndex,
Series,
Timestamp,
get_dummies,
period_range,
)
import pandas._testing as tm
from pandas.core.arrays import SparseArray


class TestGetitem:
Expand Down Expand Up @@ -50,6 +52,21 @@ def test_getitem_list_of_labels_categoricalindex_cols(self):
result = dummies[list(dummies.columns)]
tm.assert_frame_equal(result, expected)

def test_getitem_sparse_column_return_type_and_dtype(self):
# https://github.com/pandas-dev/pandas/issues/23559
data = SparseArray([0, 1])
df = DataFrame({"A": data})
expected = Series(data, name="A")
result = df["A"]
tm.assert_series_equal(result, expected)

# Also check iloc and loc while we're here
result = df.iloc[:, 0]
tm.assert_series_equal(result, expected)

result = df.loc[:, "A"]
tm.assert_series_equal(result, expected)


class TestGetitemCallable:
def test_getitem_callable(self, float_frame):
Expand Down
19 changes: 0 additions & 19 deletions pandas/tests/frame/indexing/test_sparse.py

This file was deleted.

18 changes: 18 additions & 0 deletions pandas/tests/indexing/test_at.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ def test_at_timezone():
tm.assert_frame_equal(result, expected)


class TestAtSetItem:
def test_at_setitem_mixed_index_assignment(self):
# GH#19860
ser = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2])
ser.at["a"] = 11
assert ser.iat[0] == 11
ser.at[1] = 22
assert ser.iat[3] == 22


class TestAtWithDuplicates:
def test_at_with_duplicate_axes_requires_scalar_lookup(self):
# GH#33041 check that falling back to loc doesn't allow non-scalar
Expand Down Expand Up @@ -108,3 +118,11 @@ def test_at_frame_raises_key_error2(self):
df.at["a", 0]
with pytest.raises(KeyError, match="^0$"):
df.loc["a", 0]

def test_at_getitem_mixed_index_no_fallback(self):
# GH#19860
ser = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2])
with pytest.raises(KeyError, match="^0$"):
ser.at[0]
with pytest.raises(KeyError, match="^4$"):
ser.at[4]
75 changes: 11 additions & 64 deletions pandas/tests/indexing/test_floats.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,9 @@
import re

import numpy as np
import pytest

from pandas import DataFrame, Float64Index, Index, Int64Index, RangeIndex, Series
import pandas._testing as tm

# We pass through the error message from numpy
_slice_iloc_msg = re.escape(
"only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) "
"and integer or boolean arrays are valid indices"
)


def gen_obj(klass, index):
if klass is Series:
Expand Down Expand Up @@ -40,24 +32,6 @@ def check(self, result, original, indexer, getitem):

tm.assert_almost_equal(result, expected)

def test_scalar_error(self, series_with_simple_index):

# GH 4892
# float_indexers should raise exceptions
# on appropriate Index types & accessors
# this duplicates the code below
# but is specifically testing for the error
# message

s = series_with_simple_index

msg = "Cannot index by location index with a non-integer key"
with pytest.raises(TypeError, match=msg):
s.iloc[3.0]

with pytest.raises(IndexError, match=_slice_iloc_msg):
s.iloc[3.0] = 0

@pytest.mark.parametrize(
"index_func",
[
Expand All @@ -69,40 +43,32 @@ def test_scalar_error(self, series_with_simple_index):
tm.makePeriodIndex,
],
)
@pytest.mark.parametrize("klass", [Series, DataFrame])
def test_scalar_non_numeric(self, index_func, klass):
def test_scalar_non_numeric(self, index_func, frame_or_series):

# GH 4892
# float_indexers should raise exceptions
# on appropriate Index types & accessors

i = index_func(5)
s = gen_obj(klass, i)
s = gen_obj(frame_or_series, i)

# getting
with pytest.raises(KeyError, match="^3.0$"):
s[3.0]

msg = "Cannot index by location index with a non-integer key"
with pytest.raises(TypeError, match=msg):
s.iloc[3.0]

with pytest.raises(KeyError, match="^3.0$"):
s.loc[3.0]

# contains
assert 3.0 not in s

# setting with a float fails with iloc
with pytest.raises(IndexError, match=_slice_iloc_msg):
s.iloc[3.0] = 0

# setting with an indexer
if s.index.inferred_type in ["categorical"]:
# Value or Type Error
pass
elif s.index.inferred_type in ["datetime64", "timedelta64", "period"]:

# FIXME: dont leave commented-out
# these should prob work
# and are inconsistent between series/dataframe ATM
# for idxr in [lambda x: x]:
Expand Down Expand Up @@ -151,10 +117,6 @@ def test_scalar_with_mixed(self):
with pytest.raises(KeyError, match="^1.0$"):
s2[1.0]

msg = "Cannot index by location index with a non-integer key"
with pytest.raises(TypeError, match=msg):
s2.iloc[1.0]

with pytest.raises(KeyError, match=r"^1\.0$"):
s2.loc[1.0]

Expand All @@ -171,9 +133,6 @@ def test_scalar_with_mixed(self):
expected = 2
assert result == expected

msg = "Cannot index by location index with a non-integer key"
with pytest.raises(TypeError, match=msg):
s3.iloc[1.0]
with pytest.raises(KeyError, match=r"^1\.0$"):
s3.loc[1.0]

Expand All @@ -182,14 +141,13 @@ def test_scalar_with_mixed(self):
assert result == expected

@pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex])
@pytest.mark.parametrize("klass", [Series, DataFrame])
def test_scalar_integer(self, index_func, klass):
def test_scalar_integer(self, index_func, frame_or_series):

# test how scalar float indexers work on int indexes

# integer index
i = index_func(5)
obj = gen_obj(klass, i)
obj = gen_obj(frame_or_series, i)

# coerce to equal int
for idxr, getitem in [(lambda x: x.loc, False), (lambda x: x, True)]:
Expand Down Expand Up @@ -226,12 +184,11 @@ def compare(x, y):
# coerce to equal int
assert 3.0 in obj

@pytest.mark.parametrize("klass", [Series, DataFrame])
def test_scalar_float(self, klass):
def test_scalar_float(self, frame_or_series):

# scalar float indexers work on a float index
index = Index(np.arange(5.0))
s = gen_obj(klass, index)
s = gen_obj(frame_or_series, index)

# assert all operations except for iloc are ok
indexer = index[3]
Expand Down Expand Up @@ -262,14 +219,6 @@ def test_scalar_float(self, klass):
result = s2.iloc[3]
self.check(result, s, 3, False)

# iloc raises with a float
msg = "Cannot index by location index with a non-integer key"
with pytest.raises(TypeError, match=msg):
s.iloc[3.0]

with pytest.raises(IndexError, match=_slice_iloc_msg):
s2.iloc[3.0] = 0

@pytest.mark.parametrize(
"index_func",
[
Expand All @@ -281,15 +230,14 @@ def test_scalar_float(self, klass):
],
)
@pytest.mark.parametrize("l", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)])
@pytest.mark.parametrize("klass", [Series, DataFrame])
def test_slice_non_numeric(self, index_func, l, klass):
def test_slice_non_numeric(self, index_func, l, frame_or_series):

# GH 4892
# float_indexers should raise exceptions
# on appropriate Index types & accessors

index = index_func(5)
s = gen_obj(klass, index)
s = gen_obj(frame_or_series, index)

# getitem
msg = (
Expand Down Expand Up @@ -509,12 +457,11 @@ def test_float_slice_getitem_with_integer_index_raises(self, l, index_func):
s[l]

@pytest.mark.parametrize("l", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)])
@pytest.mark.parametrize("klass", [Series, DataFrame])
def test_slice_float(self, l, klass):
def test_slice_float(self, l, frame_or_series):

# same as above, but for floats
index = Index(np.arange(5.0)) + 0.1
s = gen_obj(klass, index)
s = gen_obj(frame_or_series, index)

expected = s.iloc[3:4]
for idxr in [lambda x: x.loc, lambda x: x]:
Expand Down
Loading