Skip to content

Commit 0c69bd0

Browse files
committed
Merge remote-tracking branch 'upstream/master' into na-array-ufunc
2 parents bf8680f + 665e4b1 commit 0c69bd0

Some content is hidden

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

49 files changed

+463
-440
lines changed

ci/azure/posix.yml

+7-9
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: |

pandas/_libs/parsers.pyx

+4-3
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

+6-1
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

+2-2
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

+6-5
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/ops/__init__.py

+2-1
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

+4-19
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

+2-23
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,
@@ -96,10 +94,7 @@ def should_series_dispatch(left, right, op):
9694

9795

9896
def dispatch_to_extension_op(
99-
op,
100-
left: Union[ABCExtensionArray, np.ndarray],
101-
right: Any,
102-
keep_null_freq: bool = False,
97+
op, left: Union[ABCExtensionArray, np.ndarray], right: Any,
10398
):
10499
"""
105100
Assume that left or right is a Series backed by an ExtensionArray,
@@ -110,9 +105,6 @@ def dispatch_to_extension_op(
110105
op : binary operator
111106
left : ExtensionArray or np.ndarray
112107
right : object
113-
keep_null_freq : bool, default False
114-
Whether to re-raise a NullFrequencyError unchanged, as opposed to
115-
catching and raising TypeError.
116108
117109
Returns
118110
-------
@@ -130,18 +122,5 @@ def dispatch_to_extension_op(
130122

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

pandas/core/ops/methods.py

+2-3
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/io/formats/css.py

+6-7
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):

pandas/io/formats/excel.py

+9-10
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ def build_xlstyle(self, props):
9191
"font": self.build_font(props),
9292
"number_format": self.build_number_format(props),
9393
}
94+
9495
# TODO: handle cell width and height: needs support in pandas.io.excel
9596

9697
def remove_none(d):
@@ -132,12 +133,10 @@ def build_border(self, props):
132133
return {
133134
side: {
134135
"style": self._border_style(
135-
props.get("border-{side}-style".format(side=side)),
136-
props.get("border-{side}-width".format(side=side)),
137-
),
138-
"color": self.color_to_excel(
139-
props.get("border-{side}-color".format(side=side))
136+
props.get(f"border-{side}-style"),
137+
props.get(f"border-{side}-width"),
140138
),
139+
"color": self.color_to_excel(props.get(f"border-{side}-color")),
141140
}
142141
for side in ["top", "right", "bottom", "left"]
143142
}
@@ -427,7 +426,7 @@ def _format_value(self, val):
427426
if missing.isposinf_scalar(val):
428427
val = self.inf_rep
429428
elif missing.isneginf_scalar(val):
430-
val = "-{inf}".format(inf=self.inf_rep)
429+
val = f"-{self.inf_rep}"
431430
elif self.float_format is not None:
432431
val = float(self.float_format % val)
433432
if getattr(val, "tzinfo", None) is not None:
@@ -509,8 +508,8 @@ def _format_header_regular(self):
509508
if has_aliases:
510509
if len(self.header) != len(self.columns):
511510
raise ValueError(
512-
"Writing {cols} cols but got {alias} "
513-
"aliases".format(cols=len(self.columns), alias=len(self.header))
511+
f"Writing {len(self.columns)} cols but got {len(self.header)} "
512+
"aliases"
514513
)
515514
else:
516515
colnames = self.header
@@ -718,8 +717,8 @@ def write(
718717
if num_rows > self.max_rows or num_cols > self.max_cols:
719718
raise ValueError(
720719
"This sheet is too large! Your sheet size is: "
721-
+ "{}, {} ".format(num_rows, num_cols)
722-
+ "Max sheet size is: {}, {}".format(self.max_rows, self.max_cols)
720+
f"{num_rows}, {num_cols} "
721+
f"Max sheet size is: {self.max_rows}, {self.max_cols}"
723722
)
724723

725724
if isinstance(writer, ExcelWriter):

0 commit comments

Comments
 (0)