Skip to content

Commit 32bc997

Browse files
authored
Merge pull request #80 from pandas-dev/master
Sync Fork from Upstream Repo
2 parents 76e20e9 + 970499d commit 32bc997

File tree

10 files changed

+45
-76
lines changed

10 files changed

+45
-76
lines changed

pandas/core/base.py

+15-27
Original file line numberDiff line numberDiff line change
@@ -927,16 +927,17 @@ def max(self, axis=None, skipna=True, *args, **kwargs):
927927
nv.validate_max(args, kwargs)
928928
return nanops.nanmax(self._values, skipna=skipna)
929929

930+
@doc(op="max", oppose="min", value="largest")
930931
def argmax(self, axis=None, skipna=True, *args, **kwargs):
931932
"""
932-
Return int position of the largest value in the Series.
933+
Return int position of the {value} value in the Series.
933934
934-
If the maximum is achieved in multiple locations,
935+
If the {op}imum is achieved in multiple locations,
935936
the first row position is returned.
936937
937938
Parameters
938939
----------
939-
axis : {None}
940+
axis : {{None}}
940941
Dummy argument for consistency with Series.
941942
skipna : bool, default True
942943
Exclude NA/null values when showing the result.
@@ -946,21 +947,22 @@ def argmax(self, axis=None, skipna=True, *args, **kwargs):
946947
Returns
947948
-------
948949
int
949-
Row position of the maximum values.
950+
Row position of the {op}imum value.
950951
951952
See Also
952953
--------
953-
numpy.ndarray.argmax : Equivalent method for numpy arrays.
954-
Series.argmin : Similar method, but returning the minimum.
954+
Series.arg{op} : Return position of the {op}imum value.
955+
Series.arg{oppose} : Return position of the {oppose}imum value.
956+
numpy.ndarray.arg{op} : Equivalent method for numpy arrays.
955957
Series.idxmax : Return index label of the maximum values.
956958
Series.idxmin : Return index label of the minimum values.
957959
958960
Examples
959961
--------
960962
Consider dataset containing cereal calories
961963
962-
>>> s = pd.Series({'Corn Flakes': 100.0, 'Almond Delight': 110.0,
963-
... 'Cinnamon Toast Crunch': 120.0, 'Cocoa Puff': 110.0})
964+
>>> s = pd.Series({{'Corn Flakes': 100.0, 'Almond Delight': 110.0,
965+
... 'Cinnamon Toast Crunch': 120.0, 'Cocoa Puff': 110.0}})
964966
>>> s
965967
Corn Flakes 100.0
966968
Almond Delight 110.0
@@ -970,8 +972,11 @@ def argmax(self, axis=None, skipna=True, *args, **kwargs):
970972
971973
>>> s.argmax()
972974
2
975+
>>> s.argmin()
976+
0
973977
974-
The maximum cereal calories is in the third element,
978+
The maximum cereal calories is the third element and
979+
the minimum cereal calories is the first element,
975980
since series is zero-indexed.
976981
"""
977982
nv.validate_minmax_axis(axis)
@@ -1019,25 +1024,8 @@ def min(self, axis=None, skipna=True, *args, **kwargs):
10191024
nv.validate_min(args, kwargs)
10201025
return nanops.nanmin(self._values, skipna=skipna)
10211026

1027+
@doc(argmax, op="min", oppose="max", value="smallest")
10221028
def argmin(self, axis=None, skipna=True, *args, **kwargs):
1023-
"""
1024-
Return a ndarray of the minimum argument indexer.
1025-
1026-
Parameters
1027-
----------
1028-
axis : {None}
1029-
Dummy argument for consistency with Series.
1030-
skipna : bool, default True
1031-
1032-
Returns
1033-
-------
1034-
numpy.ndarray
1035-
1036-
See Also
1037-
--------
1038-
numpy.ndarray.argmin : Return indices of the minimum values along
1039-
the given axis.
1040-
"""
10411029
nv.validate_minmax_axis(axis)
10421030
nv.validate_argmax_with_skipna(skipna, args, kwargs)
10431031
return nanops.nanargmin(self._values, skipna=skipna)

pandas/core/frame.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -890,7 +890,7 @@ def style(self) -> "Styler":
890890
"""
891891

892892
@Appender(_shared_docs["items"])
893-
def items(self) -> Iterable[Tuple[Optional[Hashable], Series]]:
893+
def items(self) -> Iterable[Tuple[Label, Series]]:
894894
if self.columns.is_unique and hasattr(self, "_item_cache"):
895895
for k in self.columns:
896896
yield k, self._get_item_cache(k)
@@ -899,10 +899,10 @@ def items(self) -> Iterable[Tuple[Optional[Hashable], Series]]:
899899
yield k, self._ixs(i, axis=1)
900900

901901
@Appender(_shared_docs["items"])
902-
def iteritems(self) -> Iterable[Tuple[Optional[Hashable], Series]]:
902+
def iteritems(self) -> Iterable[Tuple[Label, Series]]:
903903
yield from self.items()
904904

905-
def iterrows(self) -> Iterable[Tuple[Optional[Hashable], Series]]:
905+
def iterrows(self) -> Iterable[Tuple[Label, Series]]:
906906
"""
907907
Iterate over DataFrame rows as (index, Series) pairs.
908908
@@ -4043,7 +4043,7 @@ def set_index(
40434043
"one-dimensional arrays."
40444044
)
40454045

4046-
missing: List[Optional[Hashable]] = []
4046+
missing: List[Label] = []
40474047
for col in keys:
40484048
if isinstance(
40494049
col, (ABCIndexClass, ABCSeries, np.ndarray, list, abc.Iterator)
@@ -4082,7 +4082,7 @@ def set_index(
40824082
else:
40834083
arrays.append(self.index)
40844084

4085-
to_remove: List[Optional[Hashable]] = []
4085+
to_remove: List[Label] = []
40864086
for col in keys:
40874087
if isinstance(col, ABCMultiIndex):
40884088
for n in range(col.nlevels):
@@ -4137,7 +4137,7 @@ def reset_index(
41374137
drop: bool = False,
41384138
inplace: bool = False,
41394139
col_level: Hashable = 0,
4140-
col_fill: Optional[Hashable] = "",
4140+
col_fill: Label = "",
41414141
) -> Optional["DataFrame"]:
41424142
"""
41434143
Reset the index, or a level of it.

pandas/core/generic.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -9729,7 +9729,7 @@ def describe_1d(data):
97299729

97309730
ldesc = [describe_1d(s) for _, s in data.items()]
97319731
# set a convenient order for rows
9732-
names: List[Optional[Hashable]] = []
9732+
names: List[Label] = []
97339733
ldesc_indexes = sorted((x.index for x in ldesc), key=len)
97349734
for idxnames in ldesc_indexes:
97359735
for name in idxnames:

pandas/core/indexes/base.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from datetime import datetime
22
import operator
33
from textwrap import dedent
4-
from typing import TYPE_CHECKING, Any, FrozenSet, Hashable, Optional, Union
4+
from typing import TYPE_CHECKING, Any, FrozenSet, Hashable, Union
55
import warnings
66

77
import numpy as np
@@ -2163,7 +2163,7 @@ def dropna(self, how="any"):
21632163
21642164
Returns
21652165
-------
2166-
valid : Index
2166+
Index
21672167
"""
21682168
if how not in ("any", "all"):
21692169
raise ValueError(f"invalid how option: {how}")
@@ -5546,7 +5546,7 @@ def default_index(n):
55465546
return RangeIndex(0, n, name=None)
55475547

55485548

5549-
def maybe_extract_name(name, obj, cls) -> Optional[Hashable]:
5549+
def maybe_extract_name(name, obj, cls) -> Label:
55505550
"""
55515551
If no name is passed, then extract it from data, validating hashability.
55525552
"""

pandas/core/reshape/concat.py

+6-10
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@
22
Concat routines.
33
"""
44

5-
from typing import Hashable, Iterable, List, Mapping, Optional, Union, overload
5+
from typing import Iterable, List, Mapping, Union, overload
66

77
import numpy as np
88

9-
from pandas._typing import FrameOrSeriesUnion
9+
from pandas._typing import FrameOrSeriesUnion, Label
1010

1111
from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
1212

@@ -32,7 +32,7 @@
3232

3333
@overload
3434
def concat(
35-
objs: Union[Iterable["DataFrame"], Mapping[Optional[Hashable], "DataFrame"]],
35+
objs: Union[Iterable["DataFrame"], Mapping[Label, "DataFrame"]],
3636
axis=0,
3737
join: str = "outer",
3838
ignore_index: bool = False,
@@ -48,9 +48,7 @@ def concat(
4848

4949
@overload
5050
def concat(
51-
objs: Union[
52-
Iterable[FrameOrSeriesUnion], Mapping[Optional[Hashable], FrameOrSeriesUnion]
53-
],
51+
objs: Union[Iterable[FrameOrSeriesUnion], Mapping[Label, FrameOrSeriesUnion]],
5452
axis=0,
5553
join: str = "outer",
5654
ignore_index: bool = False,
@@ -65,9 +63,7 @@ def concat(
6563

6664

6765
def concat(
68-
objs: Union[
69-
Iterable[FrameOrSeriesUnion], Mapping[Optional[Hashable], FrameOrSeriesUnion]
70-
],
66+
objs: Union[Iterable[FrameOrSeriesUnion], Mapping[Label, FrameOrSeriesUnion]],
7167
axis=0,
7268
join="outer",
7369
ignore_index: bool = False,
@@ -536,7 +532,7 @@ def _get_concat_axis(self) -> Index:
536532
idx = ibase.default_index(len(self.objs))
537533
return idx
538534
elif self.keys is None:
539-
names: List[Optional[Hashable]] = [None] * len(self.objs)
535+
names: List[Label] = [None] * len(self.objs)
540536
num = 0
541537
has_names = False
542538
for i, x in enumerate(self.objs):

pandas/core/series.py

+1-5
Original file line numberDiff line numberDiff line change
@@ -692,11 +692,7 @@ def __array_ufunc__(
692692
inputs = tuple(extract_array(x, extract_numpy=True) for x in inputs)
693693
result = getattr(ufunc, method)(*inputs, **kwargs)
694694

695-
name: Label
696-
if len(set(names)) == 1:
697-
name = names[0]
698-
else:
699-
name = None
695+
name = names[0] if len(set(names)) == 1 else None
700696

701697
def construct_return(result):
702698
if lib.is_scalar(result):

pandas/core/strings.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -572,7 +572,7 @@ def str_replace(arr, pat, repl, n=-1, case=None, flags=0, regex=True):
572572
r"""
573573
Replace occurrences of pattern/regex in the Series/Index with
574574
some other string. Equivalent to :meth:`str.replace` or
575-
:func:`re.sub`.
575+
:func:`re.sub`, depending on the regex value.
576576
577577
Parameters
578578
----------

pandas/core/tools/numeric.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ def to_numeric(arg, errors="raise", downcast=None):
3535
Parameters
3636
----------
3737
arg : scalar, list, tuple, 1-d array, or Series
38+
Argument to be converted.
3839
errors : {'ignore', 'raise', 'coerce'}, default 'raise'
3940
- If 'raise', then invalid parsing will raise an exception.
4041
- If 'coerce', then invalid parsing will be set as NaN.
@@ -61,7 +62,8 @@ def to_numeric(arg, errors="raise", downcast=None):
6162
6263
Returns
6364
-------
64-
ret : numeric if parsing succeeded.
65+
ret
66+
Numeric if parsing succeeded.
6567
Return type depends on input. Series if Series, otherwise ndarray.
6668
6769
See Also

pandas/io/excel/_base.py

+5-8
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import abc
2-
from datetime import date, datetime, timedelta
2+
import datetime
33
from io import BytesIO
44
import os
55
from textwrap import fill
@@ -28,7 +28,6 @@
2828
_pop_header_name,
2929
get_writer,
3030
)
31-
from pandas.io.formats.printing import pprint_thing
3231
from pandas.io.parsers import TextParser
3332

3433
_read_excel_doc = (
@@ -742,11 +741,11 @@ def _value_with_fmt(self, val):
742741
val = float(val)
743742
elif is_bool(val):
744743
val = bool(val)
745-
elif isinstance(val, datetime):
744+
elif isinstance(val, datetime.datetime):
746745
fmt = self.datetime_format
747-
elif isinstance(val, date):
746+
elif isinstance(val, datetime.date):
748747
fmt = self.date_format
749-
elif isinstance(val, timedelta):
748+
elif isinstance(val, datetime.timedelta):
750749
val = val.total_seconds() / float(86400)
751750
fmt = "0"
752751
else:
@@ -763,9 +762,7 @@ def check_extension(cls, ext):
763762
if ext.startswith("."):
764763
ext = ext[1:]
765764
if not any(ext in extension for extension in cls.supported_extensions):
766-
msg = "Invalid extension for engine"
767-
f"'{pprint_thing(cls.engine)}': '{pprint_thing(ext)}'"
768-
raise ValueError(msg)
765+
raise ValueError(f"Invalid extension for engine '{cls.engine}': '{ext}'")
769766
else:
770767
return True
771768

pandas/io/pytables.py

+4-14
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,7 @@
88
import itertools
99
import os
1010
import re
11-
from typing import (
12-
TYPE_CHECKING,
13-
Any,
14-
Dict,
15-
Hashable,
16-
List,
17-
Optional,
18-
Tuple,
19-
Type,
20-
Union,
21-
)
11+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, Union
2212
import warnings
2313

2414
import numpy as np
@@ -27,7 +17,7 @@
2717

2818
from pandas._libs import lib, writers as libwriters
2919
from pandas._libs.tslibs import timezones
30-
from pandas._typing import ArrayLike, FrameOrSeries
20+
from pandas._typing import ArrayLike, FrameOrSeries, Label
3121
from pandas.compat._optional import import_optional_dependency
3222
from pandas.errors import PerformanceWarning
3323
from pandas.util._decorators import cache_readonly
@@ -2811,7 +2801,7 @@ def read_multi_index(
28112801

28122802
levels = []
28132803
codes = []
2814-
names: List[Optional[Hashable]] = []
2804+
names: List[Label] = []
28152805
for i in range(nlevels):
28162806
level_key = f"{key}_level{i}"
28172807
node = getattr(self.group, level_key)
@@ -2976,7 +2966,7 @@ class SeriesFixed(GenericFixed):
29762966
pandas_kind = "series"
29772967
attributes = ["name"]
29782968

2979-
name: Optional[Hashable]
2969+
name: Label
29802970

29812971
@property
29822972
def shape(self):

0 commit comments

Comments
 (0)