Skip to content

TYP: generic, series, frame #36989

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 4 commits into from
Oct 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
4 changes: 2 additions & 2 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -9311,8 +9311,8 @@ def _AXIS_NAMES(self) -> Dict[int, str]:
ops.add_special_arithmetic_methods(DataFrame)


def _from_nested_dict(data):
new_data = collections.defaultdict(dict)
def _from_nested_dict(data) -> collections.defaultdict:
new_data: collections.defaultdict = collections.defaultdict(dict)
for index, s in data.items():
for col, v in s.items():
new_data[col][index] = v
Expand Down
18 changes: 13 additions & 5 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@
if TYPE_CHECKING:
from pandas._libs.tslibs import BaseOffset

from pandas.core.frame import DataFrame
from pandas.core.resample import Resampler
from pandas.core.series import Series
from pandas.core.window.indexers import BaseIndexer
Expand All @@ -130,7 +131,7 @@
)


def _single_replace(self, to_replace, method, inplace, limit):
def _single_replace(self: "Series", to_replace, method, inplace, limit):
"""
Replaces values in a Series using the fill method specified when no
replacement value is given in the replace method
Expand Down Expand Up @@ -541,6 +542,7 @@ def _get_cleaned_column_resolvers(self) -> Dict[str, ABCSeries]:
from pandas.core.computation.parsing import clean_column_name

if isinstance(self, ABCSeries):
self = cast("Series", self)
return {clean_column_name(self.name): self}

return {
Expand Down Expand Up @@ -1995,9 +1997,10 @@ def _repr_data_resource_(self):
"""
if config.get_option("display.html.table_schema"):
data = self.head(config.get_option("display.max_rows"))
payload = json.loads(
data.to_json(orient="table"), object_pairs_hook=collections.OrderedDict
)

as_json = data.to_json(orient="table")
as_json = cast(str, as_json)
payload = json.loads(as_json, object_pairs_hook=collections.OrderedDict)
return payload

# ----------------------------------------------------------------------
Expand Down Expand Up @@ -3113,6 +3116,7 @@ def to_latex(
if multirow is None:
multirow = config.get_option("display.latex.multirow")

self = cast("DataFrame", self)
formatter = DataFrameFormatter(
self,
columns=columns,
Expand Down Expand Up @@ -3830,7 +3834,7 @@ def _check_setitem_copy(self, stacklevel=4, t="setting", force=False):
# the copy weakref
if self._is_copy is not None and not isinstance(self._is_copy, str):
r = self._is_copy()
if not gc.get_referents(r) or r.shape == self.shape:
if not gc.get_referents(r) or (r is not None and r.shape == self.shape):
self._is_copy = None
return

Expand Down Expand Up @@ -6684,6 +6688,7 @@ def replace(
return self.apply(
_single_replace, args=(to_replace, method, inplace, limit)
)
self = cast("Series", self)
return _single_replace(self, to_replace, method, inplace, limit)

if not is_dict_like(to_replace):
Expand Down Expand Up @@ -7265,10 +7270,13 @@ def asof(self, where, subset=None):
nulls = self.isna() if is_series else self[subset].isna().any(1)
if nulls.all():
if is_series:
self = cast("Series", self)
return self._constructor(np.nan, index=where, name=self.name)
elif is_list:
self = cast("DataFrame", self)
return self._constructor(np.nan, index=where, columns=self.columns)
else:
self = cast("DataFrame", self)
return self._constructor_sliced(
np.nan, index=self.columns, name=where[0]
)
Expand Down
11 changes: 8 additions & 3 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1789,12 +1789,17 @@ def count(self, level=None):
"""
if level is None:
return notna(self.array).sum()
elif not isinstance(self.index, MultiIndex):
raise ValueError("Series.count level is only valid with a MultiIndex")
Copy link
Contributor

Choose a reason for hiding this comment

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

is this hit in a test?

Copy link
Member Author

Choose a reason for hiding this comment

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

no. ill add one in my just started collected-followups branch


index = self.index
assert isinstance(index, MultiIndex) # for mypy

if isinstance(level, str):
level = self.index._get_level_number(level)
level = index._get_level_number(level)

lev = self.index.levels[level]
level_codes = np.array(self.index.codes[level], subok=False, copy=True)
lev = index.levels[level]
level_codes = np.array(index.codes[level], subok=False, copy=True)

mask = level_codes == -1
if mask.any():
Expand Down
8 changes: 8 additions & 0 deletions pandas/tests/series/methods/test_count.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
import numpy as np
import pytest

import pandas as pd
from pandas import Categorical, MultiIndex, Series
import pandas._testing as tm


class TestSeriesCount:
def test_count_level_without_multiindex(self):
ser = pd.Series(range(3))

msg = "Series.count level is only valid with a MultiIndex"
with pytest.raises(ValueError, match=msg):
ser.count(level=1)

def test_count(self, datetime_series):
assert datetime_series.count() == len(datetime_series)

Expand Down
3 changes: 0 additions & 3 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -208,9 +208,6 @@ check_untyped_defs=False
[mypy-pandas.core.reshape.merge]
check_untyped_defs=False

[mypy-pandas.core.series]
check_untyped_defs=False

[mypy-pandas.core.window.common]
check_untyped_defs=False

Expand Down