Skip to content

Commit 6f78520

Browse files
committed
CLN: avoid storing unnecessary variable
1 parent f7b868c commit 6f78520

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

57 files changed

+485
-508
lines changed

ci/azure/posix.yml

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -44,15 +44,13 @@ jobs:
4444
PATTERN: "not slow and not network"
4545
LOCALE_OVERRIDE: "zh_CN.UTF-8"
4646

47-
# Disabled for NumPy object-dtype warning.
48-
# https://github.com/pandas-dev/pandas/issues/30043
49-
# py37_np_dev:
50-
# ENV_FILE: ci/deps/azure-37-numpydev.yaml
51-
# CONDA_PY: "37"
52-
# PATTERN: "not slow and not network"
53-
# TEST_ARGS: "-W error"
54-
# PANDAS_TESTING_MODE: "deprecate"
55-
# EXTRA_APT: "xsel"
47+
py37_np_dev:
48+
ENV_FILE: ci/deps/azure-37-numpydev.yaml
49+
CONDA_PY: "37"
50+
PATTERN: "not slow and not network"
51+
TEST_ARGS: "-W error"
52+
PANDAS_TESTING_MODE: "deprecate"
53+
EXTRA_APT: "xsel"
5654

5755
steps:
5856
- script: |

doc/source/whatsnew/v1.0.0.rst

100644100755
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more.
535535
- :meth:`Series.plot` no longer accepts positional arguments, pass keyword arguments instead (:issue:`30003`)
536536
- :meth:`DataFrame.hist` and :meth:`Series.hist` no longer allows ``figsize="default"``, specify figure size by passinig a tuple instead (:issue:`30003`)
537537
- Floordiv of integer-dtyped array by :class:`Timedelta` now raises ``TypeError`` (:issue:`21036`)
538+
- :class:`TimedeltaIndex` and :class:`DatetimeIndex` no longer accept non-nanosecond dtype strings like "timedelta64" or "datetime64", use "timedelta64[ns]" and "datetime64[ns]" instead (:issue:`24806`)
538539
- :func:`pandas.api.types.infer_dtype` argument ``skipna`` defaults to ``True`` instead of ``False`` (:issue:`24050`)
539540
- Removed the previously deprecated :attr:`Series.ix` and :attr:`DataFrame.ix` (:issue:`26438`)
540541
- Removed the previously deprecated :meth:`Index.summary` (:issue:`18217`)
@@ -634,6 +635,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more.
634635
- Removed the previously deprecated keyword "data" from :func:`andrews_curves`, use "frame" instead (:issue:`6956`)
635636
- Removed the previously deprecated keyword "data" from :func:`parallel_coordinates`, use "frame" instead (:issue:`6956`)
636637
- Removed the previously deprecated keyword "colors" from :func:`parallel_coordinates`, use "color" instead (:issue:`6956`)
638+
- Removed the previously deprecated keywords "verbose" and "private_key" from :func:`read_gbq` (:issue:`30200`)
637639
-
638640

639641
.. _whatsnew_1000.performance:
@@ -825,7 +827,7 @@ Groupby/resample/rolling
825827
- Bug in :meth:`DataFrameGroupBy.rolling().quantile()` ignoring ``interpolation`` keyword argument (:issue:`28779`)
826828
- Bug in :meth:`DataFrame.groupby` where ``any``, ``all``, ``nunique`` and transform functions would incorrectly handle duplicate column labels (:issue:`21668`)
827829
- Bug in :meth:`DataFrameGroupBy.agg` with timezone-aware datetime64 column incorrectly casting results to the original dtype (:issue:`29641`)
828-
-
830+
- Bug in :meth:`DataFrame.groupby` when using axis=1 and having a single level columns index (:issue:`30208`)
829831

830832
Reshaping
831833
^^^^^^^^^

pandas/_libs/parsers.pyx

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -657,7 +657,7 @@ cdef class TextReader:
657657

658658
if isinstance(source, str):
659659
encoding = sys.getfilesystemencoding() or "utf-8"
660-
660+
usource = source
661661
source = source.encode(encoding)
662662

663663
if self.memory_map:
@@ -677,10 +677,11 @@ cdef class TextReader:
677677

678678
if ptr == NULL:
679679
if not os.path.exists(source):
680+
680681
raise FileNotFoundError(
681682
ENOENT,
682-
f'File {source} does not exist',
683-
source)
683+
f'File {usource} does not exist',
684+
usource)
684685
raise IOError('Initializing from file failed')
685686

686687
self.parser.source = ptr

pandas/core/arrays/numpy_.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,12 @@ def _is_boolean(self):
7272

7373
@classmethod
7474
def construct_from_string(cls, string):
75-
return cls(np.dtype(string))
75+
try:
76+
return cls(np.dtype(string))
77+
except TypeError as err:
78+
raise TypeError(
79+
f"Cannot construct a 'PandasDtype' from '{string}'"
80+
) from err
7681

7782
def construct_array_type(cls):
7883
return PandasArray

pandas/core/arrays/sparse/dtype.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ def construct_from_string(cls, string):
199199
-------
200200
SparseDtype
201201
"""
202-
msg = f"Could not construct SparseDtype from '{string}'"
202+
msg = f"Cannot construct a 'SparseDtype' from '{string}'"
203203
if string.startswith("Sparse"):
204204
try:
205205
sub_type, has_fill_value = cls._parse_subtype(string)
@@ -208,7 +208,7 @@ def construct_from_string(cls, string):
208208
else:
209209
result = SparseDtype(sub_type)
210210
msg = (
211-
f"Could not construct SparseDtype from '{string}'.\n\nIt "
211+
f"Cannot construct a 'SparseDtype' from '{string}'.\n\nIt "
212212
"looks like the fill_value in the string is not "
213213
"the default for the dtype. Non-default fill_values "
214214
"are not supported. Use the 'SparseDtype()' "

pandas/core/dtypes/dtypes.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -732,7 +732,7 @@ def construct_from_string(cls, string: str_type):
732732
datetime64[ns, UTC]
733733
"""
734734
if isinstance(string, str):
735-
msg = "Could not construct DatetimeTZDtype from '{string}'"
735+
msg = f"Cannot construct a 'DatetimeTZDtype' from '{string}'"
736736
match = cls._match.match(string)
737737
if match:
738738
d = match.groupdict()
@@ -743,10 +743,10 @@ def construct_from_string(cls, string: str_type):
743743
# pytz timezone (actually pytz.UnknownTimeZoneError).
744744
# TypeError if we pass a nonsense tz;
745745
# ValueError if we pass a unit other than "ns"
746-
raise TypeError(msg.format(string=string)) from err
747-
raise TypeError(msg.format(string=string))
746+
raise TypeError(msg) from err
747+
raise TypeError(msg)
748748

749-
raise TypeError("Could not construct DatetimeTZDtype")
749+
raise TypeError("Cannot construct a 'DatetimeTZDtype'")
750750

751751
def __str__(self) -> str_type:
752752
return "datetime64[{unit}, {tz}]".format(unit=self.unit, tz=self.tz)
@@ -883,7 +883,7 @@ def construct_from_string(cls, string):
883883
return cls(freq=string)
884884
except ValueError:
885885
pass
886-
raise TypeError("could not construct PeriodDtype")
886+
raise TypeError(f"Cannot construct a 'PeriodDtype' from '{string}'")
887887

888888
def __str__(self) -> str_type:
889889
return self.name
@@ -1054,6 +1054,7 @@ def construct_from_string(cls, string):
10541054
return cls(string)
10551055

10561056
msg = (
1057+
f"Cannot construct a 'IntervalDtype' from '{string}'.\n\n"
10571058
"Incorrectly formatted string passed to constructor. "
10581059
"Valid formats include Interval or Interval[dtype] "
10591060
"where dtype is numeric, datetime, or timedelta"

pandas/core/frame.py

Lines changed: 0 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1433,8 +1433,6 @@ def to_gbq(
14331433
location=None,
14341434
progress_bar=True,
14351435
credentials=None,
1436-
verbose=None,
1437-
private_key=None,
14381436
):
14391437
"""
14401438
Write a DataFrame to a Google BigQuery table.
@@ -1509,21 +1507,6 @@ def to_gbq(
15091507
*New in version 0.8.0 of pandas-gbq*.
15101508
15111509
.. versionadded:: 0.24.0
1512-
verbose : bool, deprecated
1513-
Deprecated in pandas-gbq version 0.4.0. Use the `logging module
1514-
to adjust verbosity instead
1515-
<https://pandas-gbq.readthedocs.io/en/latest/intro.html#logging>`__.
1516-
private_key : str, deprecated
1517-
Deprecated in pandas-gbq version 0.8.0. Use the ``credentials``
1518-
parameter and
1519-
:func:`google.oauth2.service_account.Credentials.from_service_account_info`
1520-
or
1521-
:func:`google.oauth2.service_account.Credentials.from_service_account_file`
1522-
instead.
1523-
1524-
Service account private key in JSON format. Can be file path
1525-
or string contents. This is useful for remote server
1526-
authentication (eg. Jupyter/IPython notebook on remote host).
15271510
15281511
See Also
15291512
--------
@@ -1544,8 +1527,6 @@ def to_gbq(
15441527
location=location,
15451528
progress_bar=progress_bar,
15461529
credentials=credentials,
1547-
verbose=verbose,
1548-
private_key=private_key,
15491530
)
15501531

15511532
@classmethod

pandas/core/groupby/grouper.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -491,8 +491,11 @@ def get_grouper(
491491
raise ValueError("multiple levels only valid with MultiIndex")
492492

493493
if isinstance(level, str):
494-
if obj.index.name != level:
495-
raise ValueError(f"level name {level} is not the name of the index")
494+
if obj._get_axis(axis).name != level:
495+
raise ValueError(
496+
f"level name {level} is not the name "
497+
f"of the {obj._get_axis_name(axis)}"
498+
)
496499
elif level > 0 or level < -1:
497500
raise ValueError("level > 0 or level < -1 only valid with MultiIndex")
498501

pandas/core/ops/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -462,7 +462,8 @@ def wrapper(left, right):
462462
res_name = get_op_result_name(left, right)
463463

464464
lvalues = extract_array(left, extract_numpy=True)
465-
result = arithmetic_op(lvalues, right, op, str_rep)
465+
rvalues = extract_array(right, extract_numpy=True)
466+
result = arithmetic_op(lvalues, rvalues, op, str_rep)
466467

467468
return _construct_result(left, result, index=left.index, name=res_name)
468469

pandas/core/ops/array_ops.py

Lines changed: 4 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -24,17 +24,14 @@
2424
)
2525
from pandas.core.dtypes.generic import (
2626
ABCDatetimeArray,
27-
ABCDatetimeIndex,
2827
ABCExtensionArray,
2928
ABCIndex,
3029
ABCIndexClass,
3130
ABCSeries,
3231
ABCTimedeltaArray,
33-
ABCTimedeltaIndex,
3432
)
3533
from pandas.core.dtypes.missing import isna, notna
3634

37-
from pandas.core.construction import extract_array
3835
from pandas.core.ops import missing
3936
from pandas.core.ops.dispatch import dispatch_to_extension_op, should_extension_dispatch
4037
from pandas.core.ops.invalid import invalid_comparison
@@ -178,22 +175,10 @@ def arithmetic_op(
178175

179176
from pandas.core.ops import maybe_upcast_for_op
180177

181-
keep_null_freq = isinstance(
182-
right,
183-
(
184-
ABCDatetimeIndex,
185-
ABCDatetimeArray,
186-
ABCTimedeltaIndex,
187-
ABCTimedeltaArray,
188-
Timestamp,
189-
),
190-
)
191-
192-
# NB: We assume that extract_array has already been called on `left`, but
193-
# cannot make the same assumption about `right`. This is because we need
194-
# to define `keep_null_freq` before calling extract_array on it.
178+
# NB: We assume that extract_array has already been called
179+
# on `left` and `right`.
195180
lvalues = left
196-
rvalues = extract_array(right, extract_numpy=True)
181+
rvalues = right
197182

198183
rvalues = maybe_upcast_for_op(rvalues, lvalues.shape)
199184

@@ -203,7 +188,7 @@ def arithmetic_op(
203188
# TimedeltaArray, DatetimeArray, and Timestamp are included here
204189
# because they have `freq` attribute which is handled correctly
205190
# by dispatch_to_extension_op.
206-
res_values = dispatch_to_extension_op(op, lvalues, rvalues, keep_null_freq)
191+
res_values = dispatch_to_extension_op(op, lvalues, rvalues)
207192

208193
else:
209194
with np.errstate(all="ignore"):

pandas/core/ops/dispatch.py

Lines changed: 2 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@
55

66
import numpy as np
77

8-
from pandas.errors import NullFrequencyError
9-
108
from pandas.core.dtypes.common import (
119
is_datetime64_dtype,
1210
is_extension_array_dtype,
@@ -97,10 +95,7 @@ def should_series_dispatch(left, right, op):
9795

9896

9997
def dispatch_to_extension_op(
100-
op,
101-
left: Union[ABCExtensionArray, np.ndarray],
102-
right: Any,
103-
keep_null_freq: bool = False,
98+
op, left: Union[ABCExtensionArray, np.ndarray], right: Any,
10499
):
105100
"""
106101
Assume that left or right is a Series backed by an ExtensionArray,
@@ -111,9 +106,6 @@ def dispatch_to_extension_op(
111106
op : binary operator
112107
left : ExtensionArray or np.ndarray
113108
right : object
114-
keep_null_freq : bool, default False
115-
Whether to re-raise a NullFrequencyError unchanged, as opposed to
116-
catching and raising TypeError.
117109
118110
Returns
119111
-------
@@ -131,20 +123,7 @@ def dispatch_to_extension_op(
131123

132124
# The op calls will raise TypeError if the op is not defined
133125
# on the ExtensionArray
134-
135-
try:
136-
res_values = op(left, right)
137-
except NullFrequencyError:
138-
# DatetimeIndex and TimedeltaIndex with freq == None raise ValueError
139-
# on add/sub of integers (or int-like). We re-raise as a TypeError.
140-
if keep_null_freq:
141-
# TODO: remove keep_null_freq after Timestamp+int deprecation
142-
# GH#22535 is enforced
143-
raise
144-
raise TypeError(
145-
"incompatible type for a datetime/timedelta "
146-
"operation [{name}]".format(name=op.__name__)
147-
)
126+
res_values = op(left, right)
148127
return res_values
149128

150129

pandas/core/ops/methods.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -162,7 +162,6 @@ def _create_methods(cls, arith_method, comp_method, bool_method, special):
162162
have_divmod = issubclass(cls, ABCSeries)
163163
# divmod is available for Series
164164

165-
# yapf: disable
166165
new_methods = dict(
167166
add=arith_method(cls, operator.add, special),
168167
radd=arith_method(cls, radd, special),
@@ -181,8 +180,8 @@ def _create_methods(cls, arith_method, comp_method, bool_method, special):
181180
rtruediv=arith_method(cls, rtruediv, special),
182181
rfloordiv=arith_method(cls, rfloordiv, special),
183182
rpow=arith_method(cls, rpow, special),
184-
rmod=arith_method(cls, rmod, special))
185-
# yapf: enable
183+
rmod=arith_method(cls, rmod, special),
184+
)
186185
new_methods["div"] = new_methods["truediv"]
187186
new_methods["rdiv"] = new_methods["rtruediv"]
188187
if have_divmod:

pandas/core/tools/datetimes.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -322,13 +322,13 @@ def _convert_listlike_datetimes(
322322
if isinstance(arg, IntegerArray):
323323
# Send only non-na values to array_with_unit_to_datetime
324324
mask_na = arg.isna()
325-
result_np, tz_parsed = tslib.array_with_unit_to_datetime(
325+
result, tz_parsed = tslib.array_with_unit_to_datetime(
326326
np.compress(np.logical_not(mask_na), arg), unit, errors=errors
327327
)
328328
# Insert na values back in proper positions
329329
ins_index = np.ravel(np.argwhere(mask_na))
330330
ins_index -= range(ins_index.shape[0])
331-
result = np.insert(result_np, ins_index, None)
331+
result = np.insert(result, ins_index, None)
332332
else:
333333
result, tz_parsed = tslib.array_with_unit_to_datetime(
334334
arg, unit, errors=errors

pandas/io/excel/_base.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -903,5 +903,9 @@ def __exit__(self, exc_type, exc_value, traceback):
903903
self.close()
904904

905905
def __del__(self):
906-
# Ensure we don't leak file descriptors
907-
self.close()
906+
# Ensure we don't leak file descriptors, but put in try/except in case
907+
# attributes are already deleted
908+
try:
909+
self.close()
910+
except AttributeError:
911+
pass

pandas/io/formats/css.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,7 @@ def expand(self, prop, value):
1818
mapping = self.SIDE_SHORTHANDS[len(tokens)]
1919
except KeyError:
2020
warnings.warn(
21-
'Could not expand "{prop}: {val}"'.format(prop=prop, val=value),
22-
CSSWarning,
21+
f'Could not expand "{prop}: {value}"', CSSWarning,
2322
)
2423
return
2524
for key, idx in zip(self.SIDES, mapping):
@@ -110,14 +109,14 @@ def __call__(self, declarations_str, inherited=None):
110109

111110
# 3. TODO: resolve other font-relative units
112111
for side in self.SIDES:
113-
prop = "border-{side}-width".format(side=side)
112+
prop = f"border-{side}-width"
114113
if prop in props:
115114
props[prop] = self.size_to_pt(
116115
props[prop], em_pt=font_size, conversions=self.BORDER_WIDTH_RATIOS
117116
)
118117
for prop in [
119-
"margin-{side}".format(side=side),
120-
"padding-{side}".format(side=side),
118+
f"margin-{side}",
119+
f"padding-{side}",
121120
]:
122121
if prop in props:
123122
# TODO: support %
@@ -206,9 +205,9 @@ def _error():
206205

207206
val = round(val, 5)
208207
if int(val) == val:
209-
size_fmt = "{fmt:d}pt".format(fmt=int(val))
208+
size_fmt = f"{int(val):d}pt"
210209
else:
211-
size_fmt = "{fmt:f}pt".format(fmt=val)
210+
size_fmt = f"{val:f}pt"
212211
return size_fmt
213212

214213
def atomize(self, declarations):

0 commit comments

Comments
 (0)