Skip to content

fix frame, generic, series.py #38169

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 2 commits into from
Nov 30, 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
24 changes: 12 additions & 12 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,27 +172,27 @@
# ---------------------------------------------------------------------
# Docstring templates

_shared_doc_kwargs = dict(
axes="index, columns",
klass="DataFrame",
axes_single_arg="{0 or 'index', 1 or 'columns'}",
axis="""axis : {0 or 'index', 1 or 'columns'}, default 0
_shared_doc_kwargs = {
"axes": "index, columns",
"klass": "DataFrame",
"axes_single_arg": "{0 or 'index', 1 or 'columns'}",
"axis": """axis : {0 or 'index', 1 or 'columns'}, default 0
If 0 or 'index': apply function to each column.
If 1 or 'columns': apply function to each row.""",
optional_by="""
"optional_by": """
by : str or list of str
Name or list of names to sort by.

- if `axis` is 0 or `'index'` then `by` may contain index
levels and/or column labels.
- if `axis` is 1 or `'columns'` then `by` may contain column
levels and/or index labels.""",
optional_labels="""labels : array-like, optional
"optional_labels": """labels : array-like, optional
New labels / index to conform the axis specified by 'axis' to.""",
optional_axis="""axis : int or str, optional
"optional_axis": """axis : int or str, optional
Axis to target. Can be either the axis name ('index', 'columns')
or number (0, 1).""",
)
}

_numeric_only_doc = """numeric_only : boolean, default None
Include only float, int, boolean data. If None, will attempt to use
Expand Down Expand Up @@ -524,7 +524,7 @@ def __init__(
return

mgr = self._init_mgr(
data, axes=dict(index=index, columns=columns), dtype=dtype, copy=copy
data, axes={"index": index, "columns": columns}, dtype=dtype, copy=copy
)

elif isinstance(data, dict):
Expand Down Expand Up @@ -2902,7 +2902,7 @@ def transpose(self, *args, copy: bool = False) -> DataFrame:
1 object
dtype: object
"""
nv.validate_transpose(args, dict())
nv.validate_transpose(args, {})
# construct the args

dtypes = list(self.dtypes)
Expand Down Expand Up @@ -7358,7 +7358,7 @@ def unstack(self, level=-1, fill_value=None):

return result.__finalize__(self, method="unstack")

@Appender(_shared_docs["melt"] % dict(caller="df.melt(", other="melt"))
@Appender(_shared_docs["melt"] % {"caller": "df.melt(", "other": "melt"})
def melt(
self,
id_vars=None,
Expand Down
60 changes: 30 additions & 30 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,15 +128,15 @@
# goal is to be able to define the docs close to function, while still being
# able to share
_shared_docs = {**_shared_docs}
_shared_doc_kwargs = dict(
axes="keywords for axes",
klass="Series/DataFrame",
axes_single_arg="int or labels for object",
args_transpose="axes to permute (int or label for object)",
optional_by="""
_shared_doc_kwargs = {
"axes": "keywords for axes",
"klass": "Series/DataFrame",
"axes_single_arg": "int or labels for object",
"args_transpose": "axes to permute (int or label for object)",
"optional_by": """
by : str or list of str
Name or list of names to sort by""",
)
}


bool_t = bool # Need alias because NDFrame has def bool:
Expand Down Expand Up @@ -484,7 +484,7 @@ def _get_block_manager_axis(cls, axis: Axis) -> int:
def _get_axis_resolvers(self, axis: str) -> Dict[str, Union[Series, MultiIndex]]:
# index or columns
axis_index = getattr(self, axis)
d = dict()
d = {}
prefix = axis[0]

for i, name in enumerate(axis_index.names):
Expand Down Expand Up @@ -1946,14 +1946,14 @@ def __array_ufunc__(
@final
def __getstate__(self) -> Dict[str, Any]:
meta = {k: getattr(self, k, None) for k in self._metadata}
return dict(
_mgr=self._mgr,
_typ=self._typ,
_metadata=self._metadata,
attrs=self.attrs,
_flags={k: self.flags[k] for k in self.flags._keys},
return {
"_mgr": self._mgr,
"_typ": self._typ,
"_metadata": self._metadata,
"attrs": self.attrs,
"_flags": {k: self.flags[k] for k in self.flags._keys},
**meta,
)
}

@final
def __setstate__(self, state):
Expand All @@ -1967,7 +1967,7 @@ def __setstate__(self, state):
if typ is not None:
attrs = state.get("_attrs", {})
object.__setattr__(self, "_attrs", attrs)
flags = state.get("_flags", dict(allows_duplicate_labels=True))
flags = state.get("_flags", {"allows_duplicate_labels": True})
object.__setattr__(self, "_flags", Flags(self, **flags))

# set in the order of internal names
Expand Down Expand Up @@ -7409,7 +7409,7 @@ def isna(self: FrameOrSeries) -> FrameOrSeries:

>>> df = pd.DataFrame(dict(age=[5, 6, np.NaN],
... born=[pd.NaT, pd.Timestamp('1939-05-27'),
... pd.Timestamp('1940-04-25')],
... pd.Timestamp('1940-04-25')],
... name=['Alfred', 'Batman', ''],
... toy=[None, 'Batmobile', 'Joker']))
>>> df
Expand Down Expand Up @@ -7476,7 +7476,7 @@ def notna(self: FrameOrSeries) -> FrameOrSeries:

>>> df = pd.DataFrame(dict(age=[5, 6, np.NaN],
... born=[pd.NaT, pd.Timestamp('1939-05-27'),
... pd.Timestamp('1940-04-25')],
... pd.Timestamp('1940-04-25')],
... name=['Alfred', 'Batman', ''],
... toy=[None, 'Batmobile', 'Joker']))
>>> df
Expand Down Expand Up @@ -8196,8 +8196,8 @@ def resample(
For DataFrame objects, the keyword `on` can be used to specify the
column instead of the index for resampling.

>>> d = dict({'price': [10, 11, 9, 13, 14, 18, 17, 19],
... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]})
>>> d = {'price': [10, 11, 9, 13, 14, 18, 17, 19],
... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]}
Comment on lines -8199 to +8200
Copy link
Member

Choose a reason for hiding this comment

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

Good catch here!

>>> df = pd.DataFrame(d)
>>> df['week_starting'] = pd.date_range('01/01/2018',
... periods=8,
Expand All @@ -8222,8 +8222,8 @@ def resample(
specify on which level the resampling needs to take place.

>>> days = pd.date_range('1/1/2000', periods=4, freq='D')
>>> d2 = dict({'price': [10, 11, 9, 13, 14, 18, 17, 19],
... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]})
>>> d2 = {'price': [10, 11, 9, 13, 14, 18, 17, 19],
... 'volume': [50, 60, 40, 100, 50, 100, 40, 50]}
>>> df2 = pd.DataFrame(d2,
... index=pd.MultiIndex.from_product([days,
... ['morning',
Expand Down Expand Up @@ -10470,10 +10470,10 @@ def pct_change(
Percentage change in French franc, Deutsche Mark, and Italian lira from
1980-01-01 to 1980-03-01.

>>> df = pd.DataFrame(dict(
... FR=[4.0405, 4.0963, 4.3149],
... GR=[1.7246, 1.7482, 1.8519],
... IT=[804.74, 810.01, 860.13]),
>>> df = pd.DataFrame({
... 'FR': [4.0405, 4.0963, 4.3149],
... 'GR': [1.7246, 1.7482, 1.8519],
... 'IT': [804.74, 810.01, 860.13]},
... index=['1980-01-01', '1980-02-01', '1980-03-01'])
>>> df
FR GR IT
Expand All @@ -10490,10 +10490,10 @@ def pct_change(
Percentage of change in GOOG and APPL stock volume. Shows computing
the percentage change between columns.

>>> df = pd.DataFrame(dict([
... ('2016', [1769950, 30586265]),
... ('2015', [1500923, 40912316]),
... ('2014', [1371819, 41403351])]),
>>> df = pd.DataFrame({
... '2016': [1769950, 30586265],
... '2015': [1500923, 40912316],
... '2014': [1371819, 41403351]},
... index=['GOOG', 'APPL'])
>>> df
2016 2015 2014
Expand Down
28 changes: 14 additions & 14 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,21 +105,21 @@

__all__ = ["Series"]

_shared_doc_kwargs = dict(
axes="index",
klass="Series",
axes_single_arg="{0 or 'index'}",
axis="""axis : {0 or 'index'}
_shared_doc_kwargs = {
"axes": "index",
"klass": "Series",
"axes_single_arg": "{0 or 'index'}",
"axis": """axis : {0 or 'index'}
Parameter needed for compatibility with DataFrame.""",
inplace="""inplace : boolean, default False
"inplace": """inplace : boolean, default False
If True, performs operation inplace and returns None.""",
unique="np.ndarray",
duplicated="Series",
optional_by="",
optional_mapper="",
optional_labels="",
optional_axis="",
)
"unique": "np.ndarray",
"duplicated": "Series",
"optional_by": "",
"optional_mapper": "",
"optional_labels": "",
"optional_axis": "",
}


def _coerce_method(converter):
Expand Down Expand Up @@ -1101,7 +1101,7 @@ def repeat(self, repeats, axis=None) -> "Series":
2 c
dtype: object
"""
nv.validate_repeat(tuple(), dict(axis=axis))
nv.validate_repeat(tuple(), {"axis": axis})
new_index = self.index.repeat(repeats)
new_values = self._values.repeat(repeats)
return self._constructor(new_values, index=new_index).__finalize__(
Expand Down