Skip to content

fix issues 302, 314, 320, 321 #327

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 1 commit into from
Sep 24, 2022
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
3 changes: 2 additions & 1 deletion pandas-stubs/_libs/tslibs/offsets.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,8 @@ class BusinessHour(BusinessMixin):
offset: timedelta = ...,
): ...

class WeekOfMonthMixin(SingleConstructorOffset): ...
class WeekOfMonthMixin(SingleConstructorOffset):
def __init__(self, n: int = ..., weekday: Literal[0, 1, 2, 3, 4, 5, 6] = ...): ...

class YearOffset(SingleConstructorOffset):
def __init__(
Expand Down
24 changes: 11 additions & 13 deletions pandas-stubs/core/frame.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ from pandas.core.groupby.grouper import Grouper
from pandas.core.indexes.base import Index
from pandas.core.indexing import (
_iLocIndexer,
_IndexSliceTuple,
_LocIndexer,
)
from pandas.core.resample import Resampler
Expand Down Expand Up @@ -150,28 +151,25 @@ class _LocIndexerFrame(_LocIndexer):
@overload
def __getitem__(
self,
idx: tuple[int | StrLike | tuple[HashableT, ...], int | StrLike],
idx: tuple[int | StrLike | tuple[ScalarT, ...], int | StrLike],
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HashableT included slice and if it is a slice in the tuple, we are not getting a scalar with .loc

) -> Scalar: ...
@overload
def __getitem__(
self,
idx: ScalarT
| tuple[IndexType | MaskType | tuple[slice, ...], ScalarT | None]
| tuple[IndexType | MaskType | _IndexSliceTuple, ScalarT | None]
| None,
) -> Series: ...
@overload
def __setitem__(
self,
idx: MaskType
| StrLike
| tuple[MaskType | Index | Sequence[ScalarT] | Scalar | slice, ...]
| list[ScalarT],
idx: MaskType | StrLike | _IndexSliceTuple | list[ScalarT],
value: S1 | ArrayLike | Series | DataFrame,
) -> None: ...
@overload
def __setitem__(
self,
idx: tuple[tuple[HashableT | Scalar | slice, ...], HashableT],
idx: tuple[_IndexSliceTuple, HashableT],
value: S1 | ArrayLike | Series[S1] | list,
) -> None: ...

Expand Down Expand Up @@ -550,10 +548,10 @@ class DataFrame(NDFrame, OpsMixin):
@overload
def drop(
self,
labels: Hashable | Sequence[Hashable] = ...,
labels: Hashable | Sequence[Hashable] | Index = ...,
*,
axis: Axis = ...,
index: Hashable | Sequence[Hashable] = ...,
index: Hashable | Sequence[Hashable] | Index = ...,
columns: Hashable | Sequence[Hashable] | Index = ...,
level: Level | None = ...,
inplace: Literal[True],
Expand All @@ -562,10 +560,10 @@ class DataFrame(NDFrame, OpsMixin):
@overload
def drop(
self,
labels: Hashable | Sequence[Hashable] = ...,
labels: Hashable | Sequence[Hashable] | Index = ...,
*,
axis: Axis = ...,
index: Hashable | Sequence[Hashable] = ...,
index: Hashable | Sequence[Hashable] | Index = ...,
columns: Hashable | Sequence[Hashable] | Index = ...,
level: Level | None = ...,
inplace: Literal[False] = ...,
Expand All @@ -574,10 +572,10 @@ class DataFrame(NDFrame, OpsMixin):
@overload
def drop(
self,
labels: Hashable | Sequence[Hashable] = ...,
labels: Hashable | Sequence[Hashable] | Index = ...,
*,
axis: Axis = ...,
index: Hashable | Sequence[Hashable] = ...,
index: Hashable | Sequence[Hashable] | Index = ...,
columns: Hashable | Sequence[Hashable] | Index = ...,
level: Level | None = ...,
inplace: bool = ...,
Expand Down
15 changes: 2 additions & 13 deletions pandas-stubs/core/indexes/accessors.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -183,16 +183,6 @@ class _DatetimeRoundingMethods(Generic[_DTRoundingMethodReturnType]):
| Timedelta = ...,
) -> _DTRoundingMethodReturnType: ...

class _TZConversionMethods:
def tz_localize(
self,
tz: str | None,
ambiguous: Literal["raise", "infer", "NaT"] | np_ndarray_bool = ...,
nonexistent: Literal["shift_forward", "shift_backward", "NaT", "raise"]
| Timedelta = ...,
) -> DatetimeArray: ...
def tz_convert(self, tz: str | None) -> TimestampSeries: ...

_DTNormalizeReturnType = TypeVar(
"_DTNormalizeReturnType", TimestampSeries, DatetimeIndex
)
Expand All @@ -217,8 +207,8 @@ class _DatetimeLikeNoTZMethods(
ambiguous: Literal["raise", "infer", "NaT"] | np_ndarray_bool = ...,
nonexistent: Literal["shift_forward", "shift_backward", "NaT", "raise"]
| Timedelta = ...,
) -> DatetimeArray: ...
def tz_convert(self, tz: str | None) -> TimestampSeries: ...
) -> _DTNormalizeReturnType: ...
def tz_convert(self, tz: str | None) -> _DTNormalizeReturnType: ...
def normalize(self) -> _DTNormalizeReturnType: ...
def strftime(self, date_format: str) -> _DTStrKindReturnType: ...
def month_name(self, locale: str | None = ...) -> _DTStrKindReturnType: ...
Expand Down Expand Up @@ -264,7 +254,6 @@ class DatetimeProperties(
_DTStrKindReturnType,
_DTToPeriodReturnType,
],
_TZConversionMethods,
Generic[
_DTFieldOpsReturnType,
_DTBoolOpsReturnType,
Expand Down
1 change: 0 additions & 1 deletion pandas-stubs/core/indexes/datetimes.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ from pandas.core.dtypes.dtypes import DatetimeTZDtype
from pandas.tseries.offsets import BaseOffset

class DatetimeIndex(DatetimeTimedeltaMixin, DatetimeIndexProperties):
tz: tzinfo | None
def __init__(
self,
data: ArrayLike | AnyArrayLike | list | tuple,
Expand Down
10 changes: 5 additions & 5 deletions pandas-stubs/core/indexing.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ from pandas._typing import (
ScalarT,
)

_IndexSliceTuple = Union[
slice, tuple[Union[Index, MaskType, Scalar, list[ScalarT], slice], ...]
]
_IndexSliceTuple = tuple[Union[Index, MaskType, Scalar, list[ScalarT], slice], ...]

_IndexSliceTupleT = TypeVar("_IndexSliceTupleT", bound=_IndexSliceTuple)
_IndexSliceUnion = Union[slice, _IndexSliceTuple]

_IndexSliceUnionT = TypeVar("_IndexSliceUnionT", bound=_IndexSliceUnion)

class _IndexSlice:
def __getitem__(self, arg: _IndexSliceTupleT) -> _IndexSliceTupleT: ...
def __getitem__(self, arg: _IndexSliceUnionT) -> _IndexSliceUnionT: ...

IndexSlice: _IndexSlice

Expand Down
18 changes: 9 additions & 9 deletions pandas-stubs/core/series.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -727,35 +727,35 @@ class Series(IndexOpsMixin, NDFrame, Generic[S1]):
@overload
def drop(
self,
labels: Hashable | list[HashableT] = ...,
labels: Hashable | list[HashableT] | Index = ...,
*,
axis: Axis = ...,
index: Hashable | list[HashableT] = ...,
columns: Hashable | list[HashableT] = ...,
index: Hashable | list[HashableT] | Index = ...,
columns: Hashable | list[HashableT] | Index = ...,
level: Level | None = ...,
inplace: Literal[True],
errors: IgnoreRaise = ...,
) -> None: ...
@overload
def drop(
self,
labels: Hashable | list[HashableT] = ...,
labels: Hashable | list[HashableT] | Index = ...,
*,
axis: Axis = ...,
index: Hashable | list[HashableT] = ...,
columns: Hashable | list[HashableT] = ...,
index: Hashable | list[HashableT] | Index = ...,
columns: Hashable | list[HashableT] | Index = ...,
level: Level | None = ...,
inplace: Literal[False] = ...,
errors: IgnoreRaise = ...,
) -> Series: ...
@overload
def drop(
self,
labels: Hashable | list[HashableT] = ...,
labels: Hashable | list[HashableT] | Index = ...,
*,
axis: Axis = ...,
index: Hashable | list[HashableT] = ...,
columns: Hashable | list[HashableT] = ...,
index: Hashable | list[HashableT] | Index = ...,
columns: Hashable | list[HashableT] | Index = ...,
level: Level | None = ...,
inplace: bool = ...,
errors: IgnoreRaise = ...,
Expand Down
29 changes: 20 additions & 9 deletions tests/test_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,16 +244,20 @@ def test_types_setting() -> None:

def test_types_drop() -> None:
df = pd.DataFrame(data={"col1": [1, 2], "col2": [3, 4]})
res: pd.DataFrame = df.drop("col1", axis=1)
res2: pd.DataFrame = df.drop(columns=["col1"])
res3: pd.DataFrame = df.drop([0])
res4: pd.DataFrame = df.drop(index=[0])
res5: pd.DataFrame = df.drop(columns=["col1"])
res6: pd.DataFrame = df.drop(index=1)
res7: pd.DataFrame = df.drop(labels=0)
res8: None = df.drop([0, 0], inplace=True)
check(assert_type(df.drop("col1", axis=1), pd.DataFrame), pd.DataFrame)
check(assert_type(df.drop(columns=["col1"]), pd.DataFrame), pd.DataFrame)
check(assert_type(df.drop([0]), pd.DataFrame), pd.DataFrame)
check(assert_type(df.drop(index=[0]), pd.DataFrame), pd.DataFrame)
check(assert_type(df.drop(columns=["col1"]), pd.DataFrame), pd.DataFrame)
check(assert_type(df.drop(index=1), pd.DataFrame), pd.DataFrame)
check(assert_type(df.drop(labels=0), pd.DataFrame), pd.DataFrame)
assert assert_type(df.drop([0, 0], inplace=True), None) is None
to_drop: list[str] = ["col1"]
res9: pd.DataFrame = df.drop(columns=to_drop)
check(assert_type(df.drop(columns=to_drop), pd.DataFrame), pd.DataFrame)
# GH 302
check(assert_type(df.drop(pd.Index([1])), pd.DataFrame), pd.DataFrame)
check(assert_type(df.drop(index=pd.Index([1])), pd.DataFrame), pd.DataFrame)
check(assert_type(df.drop(columns=pd.Index(["col1"])), pd.DataFrame), pd.DataFrame)


def test_types_dropna() -> None:
Expand Down Expand Up @@ -1262,6 +1266,8 @@ def test_indexslice_setitem():
s = pd.Series([-1, -2])
df.loc[pd.IndexSlice[2, :]] = s.values
df.loc[pd.IndexSlice[2, :], "z"] = [200, 300]
# GH 314
df.loc[pd.IndexSlice[pd.Index([2, 3]), :], "z"] = 99


def test_indexslice_getitem():
Expand All @@ -1284,6 +1290,11 @@ def test_indexslice_getitem():
assert_type(df.loc[pd.IndexSlice[[2, 4], [20, 40]], :], pd.DataFrame),
pd.DataFrame,
)
# GH 314
check(
assert_type(df.loc[pd.IndexSlice[pd.Index([2, 4]), :], "z"], pd.Series),
pd.Series,
)


def test_compute_values():
Expand Down
4 changes: 4 additions & 0 deletions tests/test_series.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,10 @@ def test_types_drop() -> None:
check(assert_type(s.drop(0, axis=0), pd.Series), pd.Series)
assert assert_type(s.drop([0, 1], inplace=True, errors="raise"), None) is None
assert assert_type(s.drop([0, 1], inplace=True, errors="ignore"), None) is None
# GH 302
s = pd.Series([0, 1, 2])
check(assert_type(s.drop(pd.Index([0, 1])), pd.Series), pd.Series)
check(assert_type(s.drop(index=pd.Index([0, 1])), pd.Series), pd.Series)


def test_types_drop_multilevel() -> None:
Expand Down
23 changes: 12 additions & 11 deletions tests/test_timefuncs.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,8 +336,8 @@ def test_series_dt_accessors() -> None:
check(assert_type(s0.dt.isocalendar(), pd.DataFrame), pd.DataFrame)
check(assert_type(s0.dt.to_period("D"), "PeriodSeries"), pd.Series, pd.Period)
check(assert_type(s0.dt.to_pydatetime(), np.ndarray), np.ndarray, dt.datetime)
local_dtarray = s0.dt.tz_localize("UTC")
slocal = pd.Series(local_dtarray)
slocal = s0.dt.tz_localize("UTC")
check(assert_type(slocal, "TimestampSeries"), pd.Series, pd.Timestamp)
check(
assert_type(slocal.dt.tz_convert("EST"), "TimestampSeries"),
pd.Series,
Expand Down Expand Up @@ -414,7 +414,7 @@ def test_datetimeindex_accessors() -> None:
check(assert_type(i0.is_leap_year, npt.NDArray[np.bool_]), np.ndarray, np.bool_)
check(assert_type(i0.daysinmonth, IntegerIndex), IntegerIndex, int)
check(assert_type(i0.days_in_month, IntegerIndex), IntegerIndex, int)
assert assert_type(i0.tz, Optional[dt.tzinfo]) is None
assert assert_type(i0.tz, Optional[Union[dt.tzinfo, BaseTzInfo]]) is None
check(assert_type(i0.freq, Optional[BaseOffset]), BaseOffset)
check(assert_type(i0.isocalendar(), pd.DataFrame), pd.DataFrame)
check(assert_type(i0.to_period("D"), pd.PeriodIndex), pd.PeriodIndex, pd.Period)
Expand All @@ -423,14 +423,10 @@ def test_datetimeindex_accessors() -> None:
np.ndarray,
dt.datetime,
)
local_dtarray = i0.tz_localize("UTC")
slocal = pd.Series(local_dtarray)
check(
assert_type(slocal.dt.tz_convert("EST"), "TimestampSeries"),
pd.Series,
pd.Timestamp,
)
check(assert_type(slocal.dt.tz, Optional[Union[dt.tzinfo, BaseTzInfo]]), BaseTzInfo)
slocal = i0.tz_localize("UTC")
check(assert_type(slocal, pd.DatetimeIndex), pd.DatetimeIndex)
check(assert_type(slocal.tz_convert("EST"), pd.DatetimeIndex), pd.DatetimeIndex)
check(assert_type(slocal.tz, Optional[Union[dt.tzinfo, BaseTzInfo]]), BaseTzInfo)
check(assert_type(i0.normalize(), pd.DatetimeIndex), pd.DatetimeIndex, pd.Timestamp)
check(assert_type(i0.strftime("%Y"), pd.Index), pd.Index, str)
check(assert_type(i0.round("D"), pd.DatetimeIndex), pd.DatetimeIndex, pd.Timestamp)
Expand Down Expand Up @@ -517,6 +513,11 @@ def test_some_offsets() -> None:
),
pd.DatetimeIndex,
)
# GH 320
tswm1 = pd.Timestamp("9/23/2022") + pd.offsets.WeekOfMonth(2, 3)
check(assert_type(tswm1, pd.Timestamp), pd.Timestamp)
tswm2 = pd.Timestamp("9/23/2022") + pd.offsets.LastWeekOfMonth(2, 3)
check(assert_type(tswm2, pd.Timestamp), pd.Timestamp)


def test_types_to_numpy() -> None:
Expand Down