title stringlengths 1 185 | diff stringlengths 0 32.2M | body stringlengths 0 123k ⌀ | url stringlengths 57 58 | created_at stringlengths 20 20 | closed_at stringlengths 20 20 | merged_at stringlengths 20 20 ⌀ | updated_at stringlengths 20 20 |
|---|---|---|---|---|---|---|---|
DEPR: box arg in to_datetime | diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index a646c4aa03687..29139a0a14991 100644
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -538,6 +538,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more.
- Removed the previously deprecated :meth:`Series.compound` and :meth:`DataFrame.compound` (:issue:`26405`)
- Changed the the default value of `inplace` in :meth:`DataFrame.set_index` and :meth:`Series.set_axis`. It now defaults to ``False`` (:issue:`27600`)
- Removed the previously deprecated :attr:`Series.cat.categorical`, :attr:`Series.cat.index`, :attr:`Series.cat.name` (:issue:`24751`)
+- :func:`to_datetime` no longer accepts "box" argument, always returns :class:`DatetimeIndex` or :class:`Index`, :class:`Series`, or :class:`DataFrame` (:issue:`24486`)
- Removed the previously deprecated ``time_rule`` keyword from (non-public) :func:`offsets.generate_range`, which has been moved to :func:`core.arrays._ranges.generate_range` (:issue:`24157`)
- :meth:`DataFrame.loc` or :meth:`Series.loc` with listlike indexers and missing labels will no longer reindex (:issue:`17295`)
- :meth:`DataFrame.to_excel` and :meth:`Series.to_excel` with non-existent columns will no longer reindex (:issue:`17295`)
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py
index 3dfafd04dff0a..e9e5959454807 100644
--- a/pandas/core/tools/datetimes.py
+++ b/pandas/core/tools/datetimes.py
@@ -14,7 +14,6 @@
parse_time_string,
)
from pandas._libs.tslibs.strptime import array_strptime
-from pandas.util._decorators import deprecate_kwarg
from pandas.core.dtypes.common import (
ensure_object,
@@ -45,12 +44,6 @@
# types used in annotations
ArrayConvertible = Union[list, tuple, ArrayLike, ABCSeries]
-
-# ---------------------------------------------------------------------
-
-# ---------------------------------------------------------------------
-# types used in annotations
-
Scalar = Union[int, float, str]
DatetimeScalar = TypeVar("DatetimeScalar", Scalar, datetime)
DatetimeScalarOrArrayConvertible = Union[
@@ -154,7 +147,7 @@ def _maybe_cache(arg, format, cache, convert_listlike):
unique_dates = unique(arg)
if len(unique_dates) < len(arg):
- cache_dates = convert_listlike(unique_dates, True, format)
+ cache_dates = convert_listlike(unique_dates, format)
cache_array = Series(cache_dates, index=unique_dates)
return cache_array
@@ -169,7 +162,7 @@ def _box_as_indexlike(
Parameters
----------
dt_array: 1-d array
- array of datetimes to be boxed
+ Array of datetimes to be wrapped in an Index.
tz : object
None or 'utc'
name : string, default None
@@ -192,37 +185,30 @@ def _box_as_indexlike(
def _convert_and_box_cache(
arg: DatetimeScalarOrArrayConvertible,
cache_array: ABCSeries,
- box: bool,
name: Optional[str] = None,
-) -> Union[ABCIndex, np.ndarray]:
+) -> ABCIndexClass:
"""
- Convert array of dates with a cache and box the result
+ Convert array of dates with a cache and wrap the result in an Index.
Parameters
----------
arg : integer, float, string, datetime, list, tuple, 1-d array, Series
cache_array : Series
Cache of converted, unique dates
- box : boolean
- True boxes result as an Index-like, False returns an ndarray
name : string, default None
Name for a DatetimeIndex
Returns
-------
- result : datetime of converted dates
- - Index-like if box=True
- - ndarray if box=False
+ result : Index-like of converted dates
"""
from pandas import Series
result = Series(arg).map(cache_array)
- if box:
- return _box_as_indexlike(result, utc=None, name=name)
- return result.values
+ return _box_as_indexlike(result, utc=None, name=name)
-def _return_parsed_timezone_results(result, timezones, box, tz, name):
+def _return_parsed_timezone_results(result, timezones, tz, name):
"""
Return results from array_strptime if a %z or %Z directive was passed.
@@ -232,8 +218,6 @@ def _return_parsed_timezone_results(result, timezones, box, tz, name):
int64 date representations of the dates
timezones : ndarray
pytz timezone objects
- box : boolean
- True boxes result as an Index-like, False returns an ndarray
tz : object
None or pytz timezone object
name : string, default None
@@ -241,11 +225,7 @@ def _return_parsed_timezone_results(result, timezones, box, tz, name):
Returns
-------
- tz_result : ndarray of parsed dates with timezone
- Returns:
-
- - Index-like if box=True
- - ndarray of Timestamps if box=False
+ tz_result : Index-like of parsed dates with timezone
"""
if tz is not None:
raise ValueError(
@@ -256,16 +236,13 @@ def _return_parsed_timezone_results(result, timezones, box, tz, name):
tz_results = np.array(
[Timestamp(res).tz_localize(zone) for res, zone in zip(result, timezones)]
)
- if box:
- from pandas import Index
+ from pandas import Index
- return Index(tz_results, name=name)
- return tz_results
+ return Index(tz_results, name=name)
def _convert_listlike_datetimes(
arg,
- box,
format,
name=None,
tz=None,
@@ -284,8 +261,6 @@ def _convert_listlike_datetimes(
----------
arg : list, tuple, ndarray, Series, Index
date to be parced
- box : boolean
- True boxes result as an Index-like, False returns an ndarray
name : object
None or string for the Index name
tz : object
@@ -305,11 +280,7 @@ def _convert_listlike_datetimes(
Returns
-------
- ndarray of parsed dates
- Returns:
-
- - Index-like if box=True
- - ndarray of Timestamps if box=False
+ Index-like of parsed dates
"""
from pandas import DatetimeIndex
from pandas.core.arrays import DatetimeArray
@@ -330,7 +301,7 @@ def _convert_listlike_datetimes(
return arg
elif is_datetime64_ns_dtype(arg):
- if box and not isinstance(arg, (DatetimeArray, DatetimeIndex)):
+ if not isinstance(arg, (DatetimeArray, DatetimeIndex)):
try:
return DatetimeIndex(arg, tz=tz, name=name)
except ValueError:
@@ -346,26 +317,25 @@ def _convert_listlike_datetimes(
raise ValueError("cannot specify both format and unit")
arg = getattr(arg, "values", arg)
result, tz_parsed = tslib.array_with_unit_to_datetime(arg, unit, errors=errors)
- if box:
- if errors == "ignore":
- from pandas import Index
+ if errors == "ignore":
+ from pandas import Index
- result = Index(result, name=name)
+ result = Index(result, name=name)
+ else:
+ result = DatetimeIndex(result, name=name)
+ # GH 23758: We may still need to localize the result with tz
+ # GH 25546: Apply tz_parsed first (from arg), then tz (from caller)
+ # result will be naive but in UTC
+ try:
+ result = result.tz_localize("UTC").tz_convert(tz_parsed)
+ except AttributeError:
+ # Regular Index from 'ignore' path
+ return result
+ if tz is not None:
+ if result.tz is None:
+ result = result.tz_localize(tz)
else:
- result = DatetimeIndex(result, name=name)
- # GH 23758: We may still need to localize the result with tz
- # GH 25546: Apply tz_parsed first (from arg), then tz (from caller)
- # result will be naive but in UTC
- try:
- result = result.tz_localize("UTC").tz_convert(tz_parsed)
- except AttributeError:
- # Regular Index from 'ignore' path
- return result
- if tz is not None:
- if result.tz is None:
- result = result.tz_localize(tz)
- else:
- result = result.tz_convert(tz)
+ result = result.tz_convert(tz)
return result
elif getattr(arg, "ndim", 1) > 1:
raise TypeError(
@@ -416,7 +386,7 @@ def _convert_listlike_datetimes(
)
if "%Z" in format or "%z" in format:
return _return_parsed_timezone_results(
- result, timezones, box, tz, name
+ result, timezones, tz, name
)
except tslibs.OutOfBoundsDatetime:
if errors == "raise":
@@ -463,20 +433,12 @@ def _convert_listlike_datetimes(
)
if tz_parsed is not None:
- if box:
- # We can take a shortcut since the datetime64 numpy array
- # is in UTC
- return DatetimeIndex._simple_new(result, name=name, tz=tz_parsed)
- else:
- # Convert the datetime64 numpy array to an numpy array
- # of datetime objects
- result = [Timestamp(ts, tz=tz_parsed).to_pydatetime() for ts in result]
- return np.array(result, dtype=object)
+ # We can take a shortcut since the datetime64 numpy array
+ # is in UTC
+ return DatetimeIndex._simple_new(result, name=name, tz=tz_parsed)
- if box:
- utc = tz == "utc"
- return _box_as_indexlike(result, utc=utc, name=name)
- return result
+ utc = tz == "utc"
+ return _box_as_indexlike(result, utc=utc, name=name)
def _adjust_to_origin(arg, origin, unit):
@@ -558,14 +520,12 @@ def _adjust_to_origin(arg, origin, unit):
return arg
-@deprecate_kwarg(old_arg_name="box", new_arg_name=None)
def to_datetime(
arg,
errors="raise",
dayfirst=False,
yearfirst=False,
utc=None,
- box=True,
format=None,
exact=True,
unit=None,
@@ -603,15 +563,6 @@ def to_datetime(
utc : bool, default None
Return UTC DatetimeIndex if True (converting any tz-aware
datetime.datetime objects as well).
- box : bool, default True
- - If True returns a DatetimeIndex or Index-like object
- - If False returns ndarray of values.
-
- .. deprecated:: 0.25.0
- Use :meth:`Series.to_numpy` or :meth:`Timestamp.to_datetime64`
- instead to get an ndarray of values or numpy.datetime64,
- respectively.
-
format : str, default None
The strftime to parse time, eg "%d/%m/%Y", note that "%f" will parse
all the way up to nanoseconds.
@@ -764,25 +715,25 @@ def to_datetime(
if not cache_array.empty:
result = arg.map(cache_array)
else:
- values = convert_listlike(arg._values, True, format)
+ values = convert_listlike(arg._values, format)
result = arg._constructor(values, index=arg.index, name=arg.name)
elif isinstance(arg, (ABCDataFrame, abc.MutableMapping)):
- result = _assemble_from_unit_mappings(arg, errors, box, tz)
+ result = _assemble_from_unit_mappings(arg, errors, tz)
elif isinstance(arg, ABCIndexClass):
cache_array = _maybe_cache(arg, format, cache, convert_listlike)
if not cache_array.empty:
- result = _convert_and_box_cache(arg, cache_array, box, name=arg.name)
+ result = _convert_and_box_cache(arg, cache_array, name=arg.name)
else:
convert_listlike = partial(convert_listlike, name=arg.name)
- result = convert_listlike(arg, box, format)
+ result = convert_listlike(arg, format)
elif is_list_like(arg):
cache_array = _maybe_cache(arg, format, cache, convert_listlike)
if not cache_array.empty:
- result = _convert_and_box_cache(arg, cache_array, box)
+ result = _convert_and_box_cache(arg, cache_array)
else:
- result = convert_listlike(arg, box, format)
+ result = convert_listlike(arg, format)
else:
- result = convert_listlike(np.array([arg]), box, format)[0]
+ result = convert_listlike(np.array([arg]), format)[0]
return result
@@ -813,7 +764,7 @@ def to_datetime(
}
-def _assemble_from_unit_mappings(arg, errors, box, tz):
+def _assemble_from_unit_mappings(arg, errors, tz):
"""
assemble the unit specified fields from the arg (DataFrame)
Return a Series for actual parsing
@@ -826,10 +777,6 @@ def _assemble_from_unit_mappings(arg, errors, box, tz):
- If 'raise', then invalid parsing will raise an exception
- If 'coerce', then invalid parsing will be set as NaT
- If 'ignore', then invalid parsing will return the input
- box : boolean
-
- - If True, return a DatetimeIndex
- - If False, return an array
tz : None or 'utc'
Returns
@@ -904,8 +851,6 @@ def coerce(values):
"cannot assemble the datetimes [{value}]: "
"{error}".format(value=value, error=e)
)
- if not box:
- return values.values
return values
diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py
index 4e5d624eba844..ded559f16ad5d 100644
--- a/pandas/tests/indexes/datetimes/test_tools.py
+++ b/pandas/tests/indexes/datetimes/test_tools.py
@@ -921,22 +921,6 @@ def test_iso_8601_strings_with_same_offset(self):
result = DatetimeIndex([ts_str] * 2)
tm.assert_index_equal(result, expected)
- def test_iso_8601_strings_same_offset_no_box(self):
- # GH 22446
- data = ["2018-01-04 09:01:00+09:00", "2018-01-04 09:02:00+09:00"]
-
- with tm.assert_produces_warning(FutureWarning):
- result = pd.to_datetime(data, box=False)
-
- expected = np.array(
- [
- datetime(2018, 1, 4, 9, 1, tzinfo=pytz.FixedOffset(540)),
- datetime(2018, 1, 4, 9, 2, tzinfo=pytz.FixedOffset(540)),
- ],
- dtype=object,
- )
- tm.assert_numpy_array_equal(result, expected)
-
def test_iso_8601_strings_with_different_offsets(self):
# GH 17697, 11736
ts_strings = ["2015-11-18 15:30:00+05:30", "2015-11-18 16:30:00+06:30", NaT]
@@ -1024,16 +1008,6 @@ def test_timestamp_utc_true(self, ts, expected):
result = to_datetime(ts, utc=True)
assert result == expected
- def test_to_datetime_box_deprecated(self):
- expected = np.datetime64("2018-09-09")
-
- # Deprecated - see GH24416
- with tm.assert_produces_warning(FutureWarning):
- pd.to_datetime(expected, box=False)
-
- result = pd.to_datetime(expected).to_datetime64()
- assert result == expected
-
@pytest.mark.parametrize("dt_str", ["00010101", "13000101", "30000101", "99990101"])
def test_to_datetime_with_format_out_of_bounds(self, dt_str):
# GH 9107
@@ -1345,16 +1319,6 @@ def test_dataframe_dtypes(self, cache):
with pytest.raises(ValueError):
to_datetime(df, cache=cache)
- def test_dataframe_box_false(self):
- # GH 23760
- df = pd.DataFrame({"year": [2015, 2016], "month": [2, 3], "day": [4, 5]})
-
- with tm.assert_produces_warning(FutureWarning):
- result = pd.to_datetime(df, box=False)
-
- expected = np.array(["2015-02-04", "2016-03-05"], dtype="datetime64[ns]")
- tm.assert_numpy_array_equal(result, expected)
-
def test_dataframe_utc_true(self):
# GH 23760
df = pd.DataFrame({"year": [2015, 2016], "month": [2, 3], "day": [4, 5]})
| xref #24486 | https://api.github.com/repos/pandas-dev/pandas/pulls/30111 | 2019-12-06T16:14:54Z | 2019-12-06T17:18:33Z | 2019-12-06T17:18:32Z | 2019-12-06T18:37:21Z |
CLN: Refactor test_base - part1 | diff --git a/pandas/tests/indexes/test_frozen.py b/pandas/tests/indexes/test_frozen.py
index 9f6b0325b7b33..40f69ee868a90 100644
--- a/pandas/tests/indexes/test_frozen.py
+++ b/pandas/tests/indexes/test_frozen.py
@@ -1,10 +1,69 @@
+import re
+
import pytest
from pandas.core.indexes.frozen import FrozenList
-from pandas.tests.test_base import CheckImmutable, CheckStringMixin
-class TestFrozenList(CheckImmutable, CheckStringMixin):
+class CheckImmutableMixin:
+ mutable_regex = re.compile("does not support mutable operations")
+
+ def check_mutable_error(self, *args, **kwargs):
+ # Pass whatever function you normally would to pytest.raises
+ # (after the Exception kind).
+ with pytest.raises(TypeError):
+ self.mutable_regex(*args, **kwargs)
+
+ def test_no_mutable_funcs(self):
+ def setitem():
+ self.container[0] = 5
+
+ self.check_mutable_error(setitem)
+
+ def setslice():
+ self.container[1:2] = 3
+
+ self.check_mutable_error(setslice)
+
+ def delitem():
+ del self.container[0]
+
+ self.check_mutable_error(delitem)
+
+ def delslice():
+ del self.container[0:3]
+
+ self.check_mutable_error(delslice)
+ mutable_methods = getattr(self, "mutable_methods", [])
+
+ for meth in mutable_methods:
+ self.check_mutable_error(getattr(self.container, meth))
+
+ def test_slicing_maintains_type(self):
+ result = self.container[1:2]
+ expected = self.lst[1:2]
+ self.check_result(result, expected)
+
+ def check_result(self, result, expected, klass=None):
+ klass = klass or self.klass
+ assert isinstance(result, klass)
+ assert result == expected
+
+
+class CheckStringMixin:
+ def test_string_methods_dont_fail(self):
+ repr(self.container)
+ str(self.container)
+ bytes(self.container)
+
+ def test_tricky_container(self):
+ if not hasattr(self, "unicode_container"):
+ pytest.skip("Need unicode_container to test with this")
+ repr(self.unicode_container)
+ str(self.unicode_container)
+
+
+class TestFrozenList(CheckImmutableMixin, CheckStringMixin):
mutable_methods = ("extend", "pop", "remove", "insert")
unicode_container = FrozenList(["\u05d0", "\u05d1", "c"])
diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py
index 5c9a119400319..6e5f5b729d102 100644
--- a/pandas/tests/test_base.py
+++ b/pandas/tests/test_base.py
@@ -1,6 +1,5 @@
from datetime import datetime, timedelta
from io import StringIO
-import re
import sys
import numpy as np
@@ -40,64 +39,6 @@
import pandas.util.testing as tm
-class CheckStringMixin:
- def test_string_methods_dont_fail(self):
- repr(self.container)
- str(self.container)
- bytes(self.container)
-
- def test_tricky_container(self):
- if not hasattr(self, "unicode_container"):
- pytest.skip("Need unicode_container to test with this")
- repr(self.unicode_container)
- str(self.unicode_container)
-
-
-class CheckImmutable:
- mutable_regex = re.compile("does not support mutable operations")
-
- def check_mutable_error(self, *args, **kwargs):
- # Pass whatever function you normally would to pytest.raises
- # (after the Exception kind).
- with pytest.raises(TypeError):
- self.mutable_regex(*args, **kwargs)
-
- def test_no_mutable_funcs(self):
- def setitem():
- self.container[0] = 5
-
- self.check_mutable_error(setitem)
-
- def setslice():
- self.container[1:2] = 3
-
- self.check_mutable_error(setslice)
-
- def delitem():
- del self.container[0]
-
- self.check_mutable_error(delitem)
-
- def delslice():
- del self.container[0:3]
-
- self.check_mutable_error(delslice)
- mutable_methods = getattr(self, "mutable_methods", [])
-
- for meth in mutable_methods:
- self.check_mutable_error(getattr(self.container, meth))
-
- def test_slicing_maintains_type(self):
- result = self.container[1:2]
- expected = self.lst[1:2]
- self.check_result(result, expected)
-
- def check_result(self, result, expected, klass=None):
- klass = klass or self.klass
- assert isinstance(result, klass)
- assert result == expected
-
-
class TestPandasDelegate:
class Delegator:
_properties = ["foo"]
| part of #23877
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
| https://api.github.com/repos/pandas-dev/pandas/pulls/30110 | 2019-12-06T16:12:57Z | 2019-12-06T18:47:58Z | 2019-12-06T18:47:57Z | 2019-12-06T18:47:58Z |
Fixing 'names' doc for 'read_csv' | diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 7403e6d254d03..aeade1d5ed2c2 100755
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -119,9 +119,9 @@
``skip_blank_lines=True``, so ``header=0`` denotes the first line of
data rather than the first line of the file.
names : array-like, optional
- List of column names to use. If file contains no header row, then you
- should explicitly pass ``header=None``. Duplicates in this list are not
- allowed.
+ List of column names to use. If the file contains a header row,
+ then you should explicitly pass ``header=0`` to override the column names.
+ Duplicates in this list are not allowed.
index_col : int, str, sequence of int / str, or False, default ``None``
Column(s) to use as the row labels of the ``DataFrame``, either given as
string name or column index. If a sequence of int / str is given, a
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
I think there is a bug in the docs. This Jupyter notebook shows that the code does not work as expected from the docs https://gist.github.com/bessarabov/5e42bbb359fb86aaa87aed6c12a95bc9
So I've fixed the doc to match behaviour.
| https://api.github.com/repos/pandas-dev/pandas/pulls/30109 | 2019-12-06T15:52:58Z | 2019-12-08T17:29:44Z | 2019-12-08T17:29:43Z | 2019-12-08T17:30:52Z |
%s changed to fstring, single quotes in f string changed to double qu… | diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx
index a6503c00a41bb..ca1d096e75c12 100644
--- a/pandas/_libs/tslibs/period.pyx
+++ b/pandas/_libs/tslibs/period.pyx
@@ -1209,8 +1209,7 @@ def period_format(int64_t value, int freq, object fmt=None):
elif freq_group == 4000: # WK
left = period_asfreq(value, freq, 6000, 0)
right = period_asfreq(value, freq, 6000, 1)
- return '%s/%s' % (period_format(left, 6000),
- period_format(right, 6000))
+ return f"{period_format(left, 6000)}/{period_format(right, 6000)}"
elif (freq_group == 5000 # BUS
or freq_group == 6000): # DAY
fmt = b'%Y-%m-%d'
@@ -1227,7 +1226,7 @@ def period_format(int64_t value, int freq, object fmt=None):
elif freq_group == 12000: # NANOSEC
fmt = b'%Y-%m-%d %H:%M:%S.%n'
else:
- raise ValueError(f'Unknown freq: {freq}')
+ raise ValueError(f"Unknown freq: {freq}")
return _period_strftime(value, freq, fmt)
@@ -1275,15 +1274,15 @@ cdef object _period_strftime(int64_t value, int freq, object fmt):
if i == 0:
repl = str(quarter)
elif i == 1: # %f, 2-digit year
- repl = f'{(year % 100):02d}'
+ repl = f"{(year % 100):02d}"
elif i == 2:
repl = str(year)
elif i == 3:
- repl = f'{(value % 1_000):03d}'
+ repl = f"{(value % 1_000):03d}"
elif i == 4:
- repl = f'{(value % 1_000_000):06d}'
+ repl = f"{(value % 1_000_000):06d}"
elif i == 5:
- repl = f'{(value % 1_000_000_000):09d}'
+ repl = f"{(value % 1_000_000_000):09d}"
result = result.replace(str_extra_fmts[i], repl)
@@ -1391,7 +1390,7 @@ def get_period_field_arr(int code, int64_t[:] arr, int freq):
func = _get_accessor_func(code)
if func is NULL:
- raise ValueError(f'Unrecognized period code: {code}')
+ raise ValueError(f"Unrecognized period code: {code}")
sz = len(arr)
out = np.empty(sz, dtype=np.int64)
@@ -1578,8 +1577,8 @@ cdef class _Period:
freq = to_offset(freq)
if freq.n <= 0:
- raise ValueError(f'Frequency must be positive, because it '
- f'represents span: {freq.freqstr}')
+ raise ValueError("Frequency must be positive, because it "
+ f"represents span: {freq.freqstr}")
return freq
@@ -1613,8 +1612,8 @@ cdef class _Period:
return NotImplemented
elif op == Py_NE:
return NotImplemented
- raise TypeError(f'Cannot compare type {type(self).__name__} '
- f'with type {type(other).__name__}')
+ raise TypeError(f"Cannot compare type {type(self).__name__} "
+ f"with type {type(other).__name__}")
def __hash__(self):
return hash((self.ordinal, self.freqstr))
@@ -1632,8 +1631,8 @@ cdef class _Period:
if nanos % offset_nanos == 0:
ordinal = self.ordinal + (nanos // offset_nanos)
return Period(ordinal=ordinal, freq=self.freq)
- raise IncompatibleFrequency(f'Input cannot be converted to '
- f'Period(freq={self.freqstr})')
+ raise IncompatibleFrequency("Input cannot be converted to "
+ f"Period(freq={self.freqstr})")
elif util.is_offset_object(other):
freqstr = other.rule_code
base = get_base_alias(freqstr)
diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx
index fda508e51e48f..742403883f7dd 100644
--- a/pandas/_libs/tslibs/strptime.pyx
+++ b/pandas/_libs/tslibs/strptime.pyx
@@ -588,7 +588,7 @@ class TimeRE(dict):
else:
return ''
regex = '|'.join(re.escape(stuff) for stuff in to_convert)
- regex = f'(?P<{directive}>{regex})'
+ regex = f"(?P<{directive}>{regex})"
return regex
def pattern(self, format):
| ERROR: type should be string, got "https://github.com/pandas-dev/pandas/issues/29547#issuecomment-562164065\r\nhttps://github.com/pandas-dev/pandas/issues/29547\r\n\r\n- [x] pandas/_libs/tslibs/frequencies.pyx\r\n- [x] pandas/_libs/tslibs/period.pyx\r\n- [x] pandas/_libs/tslibs/strptime.pyx\r\n\r\nchanged %s to f strings and f ' ' to f \" \".\r\nstr.format() remained unchanged due to:\r\nhttps://github.com/pandas-dev/pandas/issues/29547#issuecomment-562227987 " | https://api.github.com/repos/pandas-dev/pandas/pulls/30108 | 2019-12-06T11:33:11Z | 2019-12-24T22:25:37Z | 2019-12-24T22:25:37Z | 2019-12-24T22:25:48Z |
DEPR: ufunc.outer for Series | diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index 5e2eaa6ca4a94..b93856db6ba8d 100644
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -604,6 +604,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more.
- Removed the previously deprecated :meth:`Series.to_dense`, :meth:`DataFrame.to_dense` (:issue:`26684`)
- Removed the previously deprecated :meth:`Index.dtype_str`, use ``str(index.dtype)`` instead (:issue:`27106`)
- :meth:`Categorical.ravel` returns a :class:`Categorical` instead of a ``ndarray`` (:issue:`27199`)
+- The 'outer' method on Numpy ufuncs, e.g. ``np.subtract.outer`` operating on :class:`Series` objects is no longer supported, and will raise ``NotImplementedError`` (:issue:`27198`)
- Removed previously deprecated :meth:`Series.get_dtype_counts` and :meth:`DataFrame.get_dtype_counts` (:issue:`27145`)
- Changed the default ``fill_value`` in :meth:`Categorical.take` from ``True`` to ``False`` (:issue:`20841`)
- Changed the default value for the `raw` argument in :func:`Series.rolling().apply() <pandas.core.window.Rolling.apply>`, :func:`DataFrame.rolling().apply() <pandas.core.window.Rolling.apply>`,
diff --git a/pandas/core/series.py b/pandas/core/series.py
index efa3d33a2a79a..9795412920efd 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -684,14 +684,8 @@ def construct_return(result):
elif result.ndim > 1:
# e.g. np.subtract.outer
if method == "outer":
- msg = (
- "outer method for ufunc {} is not implemented on "
- "pandas objects. Returning an ndarray, but in the "
- "future this will raise a 'NotImplementedError'. "
- "Consider explicitly converting the Series "
- "to an array with '.array' first."
- )
- warnings.warn(msg.format(ufunc), FutureWarning, stacklevel=3)
+ # GH#27198
+ raise NotImplementedError
return result
return self._constructor(result, index=index, name=name, copy=False)
diff --git a/pandas/tests/series/test_ufunc.py b/pandas/tests/series/test_ufunc.py
index 92d72706f3dec..120eaeaf785b0 100644
--- a/pandas/tests/series/test_ufunc.py
+++ b/pandas/tests/series/test_ufunc.py
@@ -299,7 +299,5 @@ def test_outer():
s = pd.Series([1, 2, 3])
o = np.array([1, 2, 3])
- with tm.assert_produces_warning(FutureWarning):
- result = np.subtract.outer(s, o)
- expected = np.array([[0, -1, -2], [1, 0, -1], [2, 1, 0]], dtype=np.dtype("int64"))
- tm.assert_numpy_array_equal(result, expected)
+ with pytest.raises(NotImplementedError):
+ np.subtract.outer(s, o)
| xref #27198 | https://api.github.com/repos/pandas-dev/pandas/pulls/30104 | 2019-12-06T05:25:45Z | 2019-12-06T13:03:31Z | 2019-12-06T13:03:31Z | 2019-12-06T15:26:50Z |
DEPR: Index.contains, DatetimeIndex.offset | diff --git a/doc/redirects.csv b/doc/redirects.csv
index 1471bfb82c07c..e0ec3bcaa340d 100644
--- a/doc/redirects.csv
+++ b/doc/redirects.csv
@@ -618,7 +618,6 @@ generated/pandas.Index.asi8,../reference/api/pandas.Index.asi8
generated/pandas.Index.asof,../reference/api/pandas.Index.asof
generated/pandas.Index.asof_locs,../reference/api/pandas.Index.asof_locs
generated/pandas.Index.astype,../reference/api/pandas.Index.astype
-generated/pandas.Index.contains,../reference/api/pandas.Index.contains
generated/pandas.Index.copy,../reference/api/pandas.Index.copy
generated/pandas.Index.data,../reference/api/pandas.Index.data
generated/pandas.Index.delete,../reference/api/pandas.Index.delete
diff --git a/doc/source/reference/indexing.rst b/doc/source/reference/indexing.rst
index a01f2bcd40612..ec485675771c4 100644
--- a/doc/source/reference/indexing.rst
+++ b/doc/source/reference/indexing.rst
@@ -151,7 +151,6 @@ Selecting
Index.asof
Index.asof_locs
- Index.contains
Index.get_indexer
Index.get_indexer_for
Index.get_indexer_non_unique
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index 120976d475ac5..1ea33d2279c4e 100644
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -548,6 +548,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more.
- Passing ``datetime64`` data to :class:`TimedeltaIndex` or ``timedelta64`` data to ``DatetimeIndex`` now raises ``TypeError`` (:issue:`23539`, :issue:`23937`)
- Passing ``int64`` values to :class:`DatetimeIndex` and a timezone now interprets the values as nanosecond timestamps in UTC, not wall times in the given timezone (:issue:`24559`)
- A tuple passed to :meth:`DataFrame.groupby` is now exclusively treated as a single key (:issue:`18314`)
+- Removed the previously deprecated :meth:`Index.contains`, use ``key in index`` instead (:issue:`30103`)
- Addition and subtraction of ``int`` or integer-arrays is no longer allowed in :class:`Timestamp`, :class:`DatetimeIndex`, :class:`TimedeltaIndex`, use ``obj + n * obj.freq`` instead of ``obj + n`` (:issue:`22535`)
- Removed :meth:`Series.from_array` (:issue:`18258`)
- Removed :meth:`DataFrame.from_items` (:issue:`18458`)
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index e57ec40bdf04d..1587d97ffb52c 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -3994,26 +3994,6 @@ def __contains__(self, key) -> bool:
except (OverflowError, TypeError, ValueError):
return False
- def contains(self, key) -> bool:
- """
- Return a boolean indicating whether the provided key is in the index.
-
- .. deprecated:: 0.25.0
- Use ``key in index`` instead of ``index.contains(key)``.
-
- Returns
- -------
- bool
- """
- warnings.warn(
- "The 'contains' method is deprecated and will be removed in a "
- "future version. Use 'key in index' instead of "
- "'index.contains(key)'",
- FutureWarning,
- stacklevel=2,
- )
- return key in self
-
def __hash__(self):
raise TypeError(f"unhashable type: {repr(type(self).__name__)}")
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index 142533584670d..b730fd0f876fa 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -1146,34 +1146,6 @@ def slice_indexer(self, start=None, end=None, step=None, kind=None):
_has_same_tz = ea_passthrough(DatetimeArray._has_same_tz)
- @property
- def offset(self):
- """
- get/set the frequency of the instance
- """
- msg = (
- "{cls}.offset has been deprecated and will be removed "
- "in a future version; use {cls}.freq instead.".format(
- cls=type(self).__name__
- )
- )
- warnings.warn(msg, FutureWarning, stacklevel=2)
- return self.freq
-
- @offset.setter
- def offset(self, value):
- """
- get/set the frequency of the instance
- """
- msg = (
- "{cls}.offset has been deprecated and will be removed "
- "in a future version; use {cls}.freq instead.".format(
- cls=type(self).__name__
- )
- )
- warnings.warn(msg, FutureWarning, stacklevel=2)
- self._data.freq = value
-
def __getitem__(self, key):
result = self._data.__getitem__(key)
if is_scalar(result):
diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py
index c9c5963e5590c..67dad61611b20 100644
--- a/pandas/tests/indexes/datetimes/test_ops.py
+++ b/pandas/tests/indexes/datetimes/test_ops.py
@@ -437,18 +437,6 @@ def test_freq_setter_errors(self):
with pytest.raises(ValueError, match="Invalid frequency"):
idx._data.freq = "foo"
- def test_offset_deprecated(self):
- # GH 20716
- idx = pd.DatetimeIndex(["20180101", "20180102"])
-
- # getter deprecated
- with tm.assert_produces_warning(FutureWarning):
- idx.offset
-
- # setter deprecated
- with tm.assert_produces_warning(FutureWarning):
- idx.offset = BDay()
-
class TestBusinessDatetimeIndex:
def setup_method(self, method):
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index 353210d7537c3..9cc1ab58c6de7 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -2402,11 +2402,13 @@ def test_tab_complete_warning(self, ip):
with provisionalcompleter("ignore"):
list(ip.Completer.completions("idx.", 4))
- def test_deprecated_contains(self, indices):
- # deprecated for all types except IntervalIndex
- warning = FutureWarning if not isinstance(indices, pd.IntervalIndex) else None
- with tm.assert_produces_warning(warning):
+ def test_contains_method_removed(self, indices):
+ # GH#30103 method removed for all types except IntervalIndex
+ if isinstance(indices, pd.IntervalIndex):
indices.contains(1)
+ else:
+ with pytest.raises(AttributeError):
+ indices.contains(1)
class TestMixedIntIndex(Base):
diff --git a/pandas/tests/indexes/test_range.py b/pandas/tests/indexes/test_range.py
index b60d3126da1d5..13b8ca2a8ea22 100644
--- a/pandas/tests/indexes/test_range.py
+++ b/pandas/tests/indexes/test_range.py
@@ -306,14 +306,6 @@ def test_cached_data(self):
91 in idx
assert idx._cached_data is None
- with tm.assert_produces_warning(FutureWarning):
- idx.contains(90)
- assert idx._cached_data is None
-
- with tm.assert_produces_warning(FutureWarning):
- idx.contains(91)
- assert idx._cached_data is None
-
idx.all()
assert idx._cached_data is None
| DatetimeIndex.offset I thought was removed in #29801, but apparently slipped through the cracks. | https://api.github.com/repos/pandas-dev/pandas/pulls/30103 | 2019-12-06T01:44:13Z | 2019-12-08T17:30:41Z | 2019-12-08T17:30:41Z | 2019-12-08T19:07:59Z |
REF: implement io.pytables.DataCol._get_atom | diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 66b8089537e8d..347d60f8a7354 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -34,10 +34,12 @@
from pandas.core.dtypes.common import (
ensure_object,
is_categorical_dtype,
+ is_complex_dtype,
is_datetime64_dtype,
is_datetime64tz_dtype,
is_extension_array_dtype,
is_list_like,
+ is_string_dtype,
is_timedelta64_dtype,
)
from pandas.core.dtypes.generic import ABCExtensionArray
@@ -2353,16 +2355,48 @@ def set_atom(self, block, data_converted, use_str: bool):
# set as a data block
self.set_atom_data(block)
- def get_atom_string(self, shape, itemsize):
+ @classmethod
+ def _get_atom(cls, values: Union[np.ndarray, ABCExtensionArray]) -> "Col":
+ """
+ Get an appropriately typed and shaped pytables.Col object for values.
+ """
+
+ dtype = values.dtype
+ itemsize = dtype.itemsize
+
+ shape = values.shape
+ if values.ndim == 1:
+ # EA, use block shape pretending it is 2D
+ shape = (1, values.size)
+
+ if is_categorical_dtype(dtype):
+ codes = values.codes
+ atom = cls.get_atom_data(shape, kind=codes.dtype.name)
+ elif is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype):
+ atom = cls.get_atom_datetime64(shape)
+ elif is_timedelta64_dtype(dtype):
+ atom = cls.get_atom_timedelta64(shape)
+ elif is_complex_dtype(dtype):
+ atom = _tables().ComplexCol(itemsize=itemsize, shape=shape[0])
+
+ elif is_string_dtype(dtype):
+ atom = cls.get_atom_string(shape, itemsize)
+
+ else:
+ atom = cls.get_atom_data(shape, kind=dtype.name)
+
+ return atom
+
+ @classmethod
+ def get_atom_string(cls, shape, itemsize):
return _tables().StringCol(itemsize=itemsize, shape=shape[0])
def set_atom_string(self, data_converted: np.ndarray):
- itemsize = data_converted.dtype.itemsize
self.kind = "string"
- self.typ = self.get_atom_string(data_converted.shape, itemsize)
self.set_data(data_converted)
- def get_atom_coltype(self, kind: str) -> Type["Col"]:
+ @classmethod
+ def get_atom_coltype(cls, kind: str) -> Type["Col"]:
""" return the PyTables column class for this column """
if kind.startswith("uint"):
k4 = kind[4:]
@@ -2373,18 +2407,16 @@ def get_atom_coltype(self, kind: str) -> Type["Col"]:
return getattr(_tables(), col_name)
- def get_atom_data(self, shape, kind: str) -> "Col":
- return self.get_atom_coltype(kind=kind)(shape=shape[0])
+ @classmethod
+ def get_atom_data(cls, shape, kind: str) -> "Col":
+ return cls.get_atom_coltype(kind=kind)(shape=shape[0])
def set_atom_complex(self, block):
self.kind = block.dtype.name
- itemsize = int(self.kind.split("complex")[-1]) // 8
- self.typ = _tables().ComplexCol(itemsize=itemsize, shape=block.shape[0])
self.set_data(block.values)
def set_atom_data(self, block):
self.kind = block.dtype.name
- self.typ = self.get_atom_data(block.shape, kind=block.dtype.name)
self.set_data(block.values)
def set_atom_categorical(self, block):
@@ -2401,7 +2433,6 @@ def set_atom_categorical(self, block):
# write the codes; must be in a block shape
self.ordered = values.ordered
- self.typ = self.get_atom_data(block.shape, kind=codes.dtype.name)
self.set_data(block.values)
# write the categories
@@ -2410,12 +2441,12 @@ def set_atom_categorical(self, block):
assert self.kind == "integer", self.kind
assert self.dtype == codes.dtype.name, codes.dtype.name
- def get_atom_datetime64(self, block):
- return _tables().Int64Col(shape=block.shape[0])
+ @classmethod
+ def get_atom_datetime64(cls, shape):
+ return _tables().Int64Col(shape=shape[0])
def set_atom_datetime64(self, block):
self.kind = "datetime64"
- self.typ = self.get_atom_datetime64(block)
self.set_data(block.values)
def set_atom_datetime64tz(self, block):
@@ -2424,15 +2455,14 @@ def set_atom_datetime64tz(self, block):
self.tz = _get_tz(block.values.tz)
self.kind = "datetime64"
- self.typ = self.get_atom_datetime64(block)
self.set_data(block.values)
- def get_atom_timedelta64(self, block):
- return _tables().Int64Col(shape=block.shape[0])
+ @classmethod
+ def get_atom_timedelta64(cls, shape):
+ return _tables().Int64Col(shape=shape[0])
def set_atom_timedelta64(self, block):
self.kind = "timedelta64"
- self.typ = self.get_atom_timedelta64(block)
self.set_data(block.values)
@property
@@ -2558,16 +2588,20 @@ def validate_names(self):
# TODO: should the message here be more specifically non-str?
raise ValueError("cannot have non-object label DataIndexableCol")
- def get_atom_string(self, shape, itemsize):
+ @classmethod
+ def get_atom_string(cls, shape, itemsize):
return _tables().StringCol(itemsize=itemsize)
- def get_atom_data(self, shape, kind: str) -> "Col":
- return self.get_atom_coltype(kind=kind)()
+ @classmethod
+ def get_atom_data(cls, shape, kind: str) -> "Col":
+ return cls.get_atom_coltype(kind=kind)()
- def get_atom_datetime64(self, block):
+ @classmethod
+ def get_atom_datetime64(cls, shape):
return _tables().Int64Col()
- def get_atom_timedelta64(self, block):
+ @classmethod
+ def get_atom_timedelta64(cls, shape):
return _tables().Int64Col()
@@ -3922,8 +3956,11 @@ def get_blk_items(mgr, blocks):
errors=self.errors,
)
+ typ = klass._get_atom(data_converted)
+
col = klass.create_for_block(i=i, name=new_name, version=self.version)
col.values = list(b_items)
+ col.typ = typ
col.set_atom(block=b, data_converted=data_converted, use_str=use_str)
col.update_info(self.info)
col.set_pos(j)
| companion to #30101 with promised payoff (logically orthgonal, but will have merge conflict when the time comes)
This implements _get_atom and makes only one call to it on 3949. By making all the relevant methods into classmethods, we can call it before we've instantiated an instance. Then following #30100, we'll be able to pass `typ` to the constructor instead of pinning it. This in turn will let us pass `pos` instead of calling `set_pos`.
Also after both this and #30101, we can get to rip out a bunch of no-longer-needed state-altering methods. | https://api.github.com/repos/pandas-dev/pandas/pulls/30102 | 2019-12-06T01:37:17Z | 2019-12-06T03:21:37Z | 2019-12-06T03:21:36Z | 2019-12-06T04:11:47Z |
REF: collect pytables DataCol.set_data calls in one place | diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 347d60f8a7354..04e0255bb6d42 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -2334,7 +2334,7 @@ def set_kind(self):
if self.typ is None:
self.typ = getattr(self.description, self.cname, None)
- def set_atom(self, block, data_converted, use_str: bool):
+ def set_atom(self, block):
""" create and setup my atom from the block b """
# short-cut certain block types
@@ -2342,18 +2342,6 @@ def set_atom(self, block, data_converted, use_str: bool):
self.set_atom_categorical(block)
elif block.is_datetimetz:
self.set_atom_datetime64tz(block)
- elif block.is_datetime:
- self.set_atom_datetime64(block)
- elif block.is_timedelta:
- self.set_atom_timedelta64(block)
- elif block.is_complex:
- self.set_atom_complex(block)
-
- elif use_str:
- self.set_atom_string(data_converted)
- else:
- # set as a data block
- self.set_atom_data(block)
@classmethod
def _get_atom(cls, values: Union[np.ndarray, ABCExtensionArray]) -> "Col":
@@ -2391,10 +2379,6 @@ def _get_atom(cls, values: Union[np.ndarray, ABCExtensionArray]) -> "Col":
def get_atom_string(cls, shape, itemsize):
return _tables().StringCol(itemsize=itemsize, shape=shape[0])
- def set_atom_string(self, data_converted: np.ndarray):
- self.kind = "string"
- self.set_data(data_converted)
-
@classmethod
def get_atom_coltype(cls, kind: str) -> Type["Col"]:
""" return the PyTables column class for this column """
@@ -2411,60 +2395,35 @@ def get_atom_coltype(cls, kind: str) -> Type["Col"]:
def get_atom_data(cls, shape, kind: str) -> "Col":
return cls.get_atom_coltype(kind=kind)(shape=shape[0])
- def set_atom_complex(self, block):
- self.kind = block.dtype.name
- self.set_data(block.values)
-
- def set_atom_data(self, block):
- self.kind = block.dtype.name
- self.set_data(block.values)
-
def set_atom_categorical(self, block):
# currently only supports a 1-D categorical
# in a 1-D block
values = block.values
- codes = values.codes
if values.ndim > 1:
raise NotImplementedError("only support 1-d categoricals")
- assert codes.dtype.name.startswith("int"), codes.dtype.name
-
# write the codes; must be in a block shape
self.ordered = values.ordered
- self.set_data(block.values)
# write the categories
self.meta = "category"
- self.metadata = np.array(block.values.categories, copy=False).ravel()
- assert self.kind == "integer", self.kind
- assert self.dtype == codes.dtype.name, codes.dtype.name
+ self.metadata = np.array(values.categories, copy=False).ravel()
@classmethod
def get_atom_datetime64(cls, shape):
return _tables().Int64Col(shape=shape[0])
- def set_atom_datetime64(self, block):
- self.kind = "datetime64"
- self.set_data(block.values)
-
def set_atom_datetime64tz(self, block):
# store a converted timezone
self.tz = _get_tz(block.values.tz)
- self.kind = "datetime64"
- self.set_data(block.values)
-
@classmethod
def get_atom_timedelta64(cls, shape):
return _tables().Int64Col(shape=shape[0])
- def set_atom_timedelta64(self, block):
- self.kind = "timedelta64"
- self.set_data(block.values)
-
@property
def shape(self):
return getattr(self.data, "shape", None)
@@ -3946,7 +3905,7 @@ def get_blk_items(mgr, blocks):
existing_col = None
new_name = name or f"values_block_{i}"
- data_converted, use_str = _maybe_convert_for_string_atom(
+ data_converted = _maybe_convert_for_string_atom(
new_name,
b,
existing_col=existing_col,
@@ -3961,7 +3920,8 @@ def get_blk_items(mgr, blocks):
col = klass.create_for_block(i=i, name=new_name, version=self.version)
col.values = list(b_items)
col.typ = typ
- col.set_atom(block=b, data_converted=data_converted, use_str=use_str)
+ col.set_atom(block=b)
+ col.set_data(data_converted)
col.update_info(self.info)
col.set_pos(j)
@@ -4830,10 +4790,9 @@ def _unconvert_index(data, kind: str, encoding=None, errors="strict"):
def _maybe_convert_for_string_atom(
name: str, block, existing_col, min_itemsize, nan_rep, encoding, errors
):
- use_str = False
if not block.is_object:
- return block.values, use_str
+ return block.values
dtype_name = block.dtype.name
inferred_type = lib.infer_dtype(block.values, skipna=False)
@@ -4848,9 +4807,7 @@ def _maybe_convert_for_string_atom(
)
elif not (inferred_type == "string" or dtype_name == "object"):
- return block.values, use_str
-
- use_str = True
+ return block.values
block = block.fillna(nan_rep, downcast=False)
if isinstance(block, list):
@@ -4893,7 +4850,7 @@ def _maybe_convert_for_string_atom(
itemsize = eci
data_converted = data_converted.astype(f"|S{itemsize}", copy=False)
- return data_converted, use_str
+ return data_converted
def _convert_string_array(data, encoding, errors, itemsize=None):
| This is part 1 of 2 of the payoff promised from #30074. | https://api.github.com/repos/pandas-dev/pandas/pulls/30101 | 2019-12-06T00:51:33Z | 2019-12-06T13:05:26Z | 2019-12-06T13:05:26Z | 2019-12-06T15:26:02Z |
REF: implement io.pytables._maybe_adjust_name | diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 04e0255bb6d42..a95d7f39ab82c 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -2222,26 +2222,12 @@ class DataCol(IndexCol):
_info_fields = ["tz", "ordered"]
@classmethod
- def create_for_block(
- cls, i: int, name=None, version=None, pos: Optional[int] = None
- ):
+ def create_for_block(cls, name: str, version, pos: int):
""" return a new datacol with the block i """
+ assert isinstance(name, str)
- cname = name or f"values_block_{i}"
- if name is None:
- name = cname
-
- # prior to 0.10.1, we named values blocks like: values_block_0 an the
- # name values_0
- try:
- if version[0] == 0 and version[1] <= 10 and version[2] == 0:
- m = re.search(r"values_block_(\d+)", name)
- if m:
- grp = m.groups()[0]
- name = f"values_{grp}"
- except IndexError:
- pass
-
+ cname = name
+ name = _maybe_adjust_name(name, version)
return cls(name=name, cname=cname, pos=pos)
def __init__(
@@ -3535,7 +3521,7 @@ def f(i, c):
if c in dc:
klass = DataIndexableCol
return klass.create_for_block(
- i=i, name=c, pos=base_pos + i, version=self.version
+ name=c, pos=base_pos + i, version=self.version
)
# Note: the definition of `values_cols` ensures that each
@@ -3914,16 +3900,16 @@ def get_blk_items(mgr, blocks):
encoding=self.encoding,
errors=self.errors,
)
+ adj_name = _maybe_adjust_name(new_name, self.version)
typ = klass._get_atom(data_converted)
- col = klass.create_for_block(i=i, name=new_name, version=self.version)
- col.values = list(b_items)
- col.typ = typ
+ col = klass(
+ name=adj_name, cname=new_name, values=list(b_items), typ=typ, pos=j
+ )
col.set_atom(block=b)
col.set_data(data_converted)
col.update_info(self.info)
- col.set_pos(j)
vaxes.append(col)
@@ -4948,6 +4934,31 @@ def _need_convert(kind) -> bool:
return False
+def _maybe_adjust_name(name: str, version) -> str:
+ """
+ Prior to 0.10.1, we named values blocks like: values_block_0 an the
+ name values_0, adjust the given name if necessary.
+
+ Parameters
+ ----------
+ name : str
+ version : Tuple[int, int, int]
+
+ Returns
+ -------
+ str
+ """
+ try:
+ if version[0] == 0 and version[1] <= 10 and version[2] == 0:
+ m = re.search(r"values_block_(\d+)", name)
+ if m:
+ grp = m.groups()[0]
+ name = f"values_{grp}"
+ except IndexError:
+ pass
+ return name
+
+
class Selection:
"""
Carries out a selection operation on a tables.Table object.
| Besides being a well-scoped utility function, this makes it easy to use the klass constructor directly instead of `klass.create_for_block` on L3905. Note that now we are passing `values` to the constructor instead of pinning them afterwards. Most of what we've been doing in this file has been building up towards being able to pass things into the constructor here and avoid pinning afterward. | https://api.github.com/repos/pandas-dev/pandas/pulls/30100 | 2019-12-06T00:00:10Z | 2019-12-06T23:24:40Z | 2019-12-06T23:24:40Z | 2019-12-06T23:39:08Z |
CI: Checking in f-strings we use {repr(...)} instead of {...!r} | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index 0ac15327494e6..46ace2dd9d70e 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -200,6 +200,10 @@ if [[ -z "$CHECK" || "$CHECK" == "patterns" ]]; then
invgrep -R --include="*.py" --include="*.pyx" -E 'class.*:\n\n( )+"""' .
RET=$(($RET + $?)) ; echo $MSG "DONE"
+ MSG='Check for use of {foo!r} instead of {repr(foo)}' ; echo $MSG
+ invgrep -R --include=*.{py,pyx} '!r}' pandas
+ RET=$(($RET + $?)) ; echo $MSG "DONE"
+
MSG='Check for use of comment-based annotation syntax' ; echo $MSG
invgrep -R --include="*.py" -P '# type: (?!ignore)' pandas
RET=$(($RET + $?)) ; echo $MSG "DONE"
| - [x] ref #29886
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
---
Can merge only after merging:
- [x] #29948
- [x] #29950
- [x] #29953
- [x] #29959
- [x] #29963
| https://api.github.com/repos/pandas-dev/pandas/pulls/30099 | 2019-12-05T23:21:51Z | 2019-12-25T22:10:45Z | 2019-12-25T22:10:44Z | 2019-12-25T22:33:01Z |
API: Handle pow & rpow special cases | diff --git a/doc/source/user_guide/missing_data.rst b/doc/source/user_guide/missing_data.rst
index 1cc485a229123..1bfe196cb2f89 100644
--- a/doc/source/user_guide/missing_data.rst
+++ b/doc/source/user_guide/missing_data.rst
@@ -822,6 +822,18 @@ For example, ``pd.NA`` propagates in arithmetic operations, similarly to
pd.NA + 1
"a" * pd.NA
+There are a few special cases when the result is known, even when one of the
+operands is ``NA``.
+
+
+================ ======
+Operation Result
+================ ======
+``pd.NA ** 0`` 0
+``1 ** pd.NA`` 1
+``-1 ** pd.NA`` -1
+================ ======
+
In equality and comparison operations, ``pd.NA`` also propagates. This deviates
from the behaviour of ``np.nan``, where comparisons with ``np.nan`` always
return ``False``.
diff --git a/pandas/_libs/missing.pyx b/pandas/_libs/missing.pyx
index 30832a8e4daab..63aa5501c5250 100644
--- a/pandas/_libs/missing.pyx
+++ b/pandas/_libs/missing.pyx
@@ -365,8 +365,6 @@ class NAType(C_NAType):
__rmod__ = _create_binary_propagating_op("__rmod__")
__divmod__ = _create_binary_propagating_op("__divmod__", divmod=True)
__rdivmod__ = _create_binary_propagating_op("__rdivmod__", divmod=True)
- __pow__ = _create_binary_propagating_op("__pow__")
- __rpow__ = _create_binary_propagating_op("__rpow__")
# __lshift__ and __rshift__ are not implemented
__eq__ = _create_binary_propagating_op("__eq__")
@@ -383,6 +381,30 @@ class NAType(C_NAType):
__abs__ = _create_unary_propagating_op("__abs__")
__invert__ = _create_unary_propagating_op("__invert__")
+ # pow has special
+ def __pow__(self, other):
+ if other is C_NA:
+ return NA
+ elif isinstance(other, (numbers.Number, np.bool_)):
+ if other == 0:
+ # returning positive is correct for +/- 0.
+ return type(other)(1)
+ else:
+ return NA
+
+ return NotImplemented
+
+ def __rpow__(self, other):
+ if other is C_NA:
+ return NA
+ elif isinstance(other, (numbers.Number, np.bool_)):
+ if other == 1 or other == -1:
+ return other
+ else:
+ return NA
+
+ return NotImplemented
+
# Logical ops using Kleene logic
def __and__(self, other):
diff --git a/pandas/tests/scalar/test_na_scalar.py b/pandas/tests/scalar/test_na_scalar.py
index 586433698a587..40db617c64717 100644
--- a/pandas/tests/scalar/test_na_scalar.py
+++ b/pandas/tests/scalar/test_na_scalar.py
@@ -38,11 +38,14 @@ def test_arithmetic_ops(all_arithmetic_functions):
op = all_arithmetic_functions
for other in [NA, 1, 1.0, "a", np.int64(1), np.nan]:
- if op.__name__ == "rmod" and isinstance(other, str):
+ if op.__name__ in ("pow", "rpow", "rmod") and isinstance(other, str):
continue
if op.__name__ in ("divmod", "rdivmod"):
assert op(NA, other) is (NA, NA)
else:
+ if op.__name__ == "rpow":
+ # avoid special case
+ other += 1
assert op(NA, other) is NA
@@ -69,6 +72,49 @@ def test_comparison_ops():
assert (other <= NA) is NA
+@pytest.mark.parametrize(
+ "value",
+ [
+ 0,
+ 0.0,
+ -0,
+ -0.0,
+ False,
+ np.bool_(False),
+ np.int_(0),
+ np.float_(0),
+ np.int_(-0),
+ np.float_(-0),
+ ],
+)
+def test_pow_special(value):
+ result = pd.NA ** value
+ assert isinstance(result, type(value))
+ assert result == 1
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ 1,
+ 1.0,
+ -1,
+ -1.0,
+ True,
+ np.bool_(True),
+ np.int_(1),
+ np.float_(1),
+ np.int_(-1),
+ np.float_(-1),
+ ],
+)
+def test_rpow_special(value):
+ result = value ** pd.NA
+ assert result == value
+ if not isinstance(value, (np.float_, np.bool_, np.int_)):
+ assert isinstance(result, type(value))
+
+
def test_unary_ops():
assert +NA is NA
assert -NA is NA
| Closes https://github.com/pandas-dev/pandas/issues/29997
@jorisvandenbossche do you have thoughts on where to document this behavior? I added a bit to `reference/arrays.rst` for now, but perhaps we'll eventually have a `user_guide/scalar_na.rst`?
| https://api.github.com/repos/pandas-dev/pandas/pulls/30097 | 2019-12-05T22:16:06Z | 2019-12-08T17:35:45Z | 2019-12-08T17:35:44Z | 2019-12-08T17:35:48Z |
BUG: file leak in read_excel | diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index 44254f54cbc7a..d4570498e3fc6 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -892,6 +892,12 @@ def sheet_names(self):
def close(self):
"""close io if necessary"""
+ if self.engine == "openpyxl":
+ # https://stackoverflow.com/questions/31416842/
+ # openpyxl-does-not-close-excel-workbook-in-read-only-mode
+ wb = self.book
+ wb._archive.close()
+
if hasattr(self.io, "close"):
self.io.close()
@@ -900,3 +906,7 @@ def __enter__(self):
def __exit__(self, exc_type, exc_value, traceback):
self.close()
+
+ def __del__(self):
+ # Ensure we don't leak file descriptors
+ self.close()
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
index e4b7d683b4c3b..480407664285f 100644
--- a/pandas/tests/io/excel/test_readers.py
+++ b/pandas/tests/io/excel/test_readers.py
@@ -543,6 +543,7 @@ def test_read_from_pathlib_path(self, read_ext):
tm.assert_frame_equal(expected, actual)
@td.skip_if_no("py.path")
+ @td.check_file_leaks
def test_read_from_py_localpath(self, read_ext):
# GH12655
@@ -881,6 +882,7 @@ def test_excel_passes_na_filter(self, read_ext, na_filter):
tm.assert_frame_equal(parsed, expected)
@pytest.mark.parametrize("arg", ["sheet", "sheetname", "parse_cols"])
+ @td.check_file_leaks
def test_unexpected_kwargs_raises(self, read_ext, arg):
# gh-17964
kwarg = {arg: "Sheet1"}
diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py
index b1be0a1a2fece..e0cb75b0a6c99 100644
--- a/pandas/tests/io/excel/test_writers.py
+++ b/pandas/tests/io/excel/test_writers.py
@@ -809,6 +809,7 @@ def test_to_excel_unicode_filename(self, ext, path):
)
tm.assert_frame_equal(result, expected)
+ # FIXME: dont leave commented-out
# def test_to_excel_header_styling_xls(self, engine, ext):
# import StringIO
diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py
index b9c165140aaad..7669e729995d0 100644
--- a/pandas/util/_test_decorators.py
+++ b/pandas/util/_test_decorators.py
@@ -24,6 +24,7 @@ def test_foo():
For more information, refer to the ``pytest`` documentation on ``skipif``.
"""
from distutils.version import LooseVersion
+from functools import wraps
import locale
from typing import Callable, Optional
@@ -230,3 +231,24 @@ def documented_fixture(fixture):
return fixture
return documented_fixture
+
+
+def check_file_leaks(func):
+ """
+ Decorate a test function tot check that we are not leaking file descriptors.
+ """
+ psutil = safe_import("psutil")
+ if not psutil:
+ return func
+
+ @wraps(func)
+ def new_func(*args, **kwargs):
+ proc = psutil.Process()
+ flist = proc.open_files()
+
+ func(*args, **kwargs)
+
+ flist2 = proc.open_files()
+ assert flist2 == flist
+
+ return new_func
| I _think_ this
closes #30031
closes #29514
we'll probably want to wait a few days to make it official.
To make the new test decorator useful in the CI we'll need to add psutil to the environment (unless someone knows of a stdlib way of doing the same check?)
One more note, the check in check_no_file_leaks depends on `__del__` having been called, which in turn depends on the gc. I'm not sure, but that might induce another layer of flakiness. If so, I think that can be fixed by calling `gc.collect()` before doing the `flist == flist2` check | https://api.github.com/repos/pandas-dev/pandas/pulls/30096 | 2019-12-05T22:08:50Z | 2019-12-06T03:11:12Z | 2019-12-06T03:11:12Z | 2022-08-22T16:09:00Z |
PERF: improve conversion to BooleanArray from int/float array | diff --git a/asv_bench/benchmarks/array.py b/asv_bench/benchmarks/array.py
new file mode 100644
index 0000000000000..8cbf8c8592661
--- /dev/null
+++ b/asv_bench/benchmarks/array.py
@@ -0,0 +1,23 @@
+import numpy as np
+
+import pandas as pd
+
+
+class BooleanArray:
+ def setup(self):
+ self.values_bool = np.array([True, False, True, False])
+ self.values_float = np.array([1.0, 0.0, 1.0, 0.0])
+ self.values_integer = np.array([1, 0, 1, 0])
+ self.values_integer_like = [1, 0, 1, 0]
+
+ def time_from_bool_array(self):
+ pd.array(self.values_bool, dtype="boolean")
+
+ def time_from_integer_array(self):
+ pd.array(self.values_integer, dtype="boolean")
+
+ def time_from_integer_like(self):
+ pd.array(self.values_integer_like, dtype="boolean")
+
+ def time_from_float_array(self):
+ pd.array(self.values_float, dtype="boolean")
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index 1a07b424fa884..5261b30ef9c1e 100644
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -156,7 +156,7 @@ type dedicated to boolean data that can hold missing values. With the default
``'bool`` data type based on a numpy bool array, the column can only hold
True or False values and not missing values. This new :class:`BooleanDtype`
can store missing values as well by keeping track of this in a separate mask.
-(:issue:`29555`)
+(:issue:`29555`, :issue:`30095`)
.. ipython:: python
diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py
index aec3397bddd16..349cbd1919e76 100644
--- a/pandas/core/arrays/boolean.py
+++ b/pandas/core/arrays/boolean.py
@@ -17,6 +17,7 @@
is_integer,
is_integer_dtype,
is_list_like,
+ is_numeric_dtype,
is_scalar,
pandas_dtype,
)
@@ -130,9 +131,19 @@ def coerce_to_array(values, mask=None, copy: bool = False):
if isinstance(values, np.ndarray) and values.dtype == np.bool_:
if copy:
values = values.copy()
+ elif isinstance(values, np.ndarray) and is_numeric_dtype(values.dtype):
+ mask_values = isna(values)
+
+ values_bool = np.zeros(len(values), dtype=bool)
+ values_bool[~mask_values] = values[~mask_values].astype(bool)
+
+ if not np.all(
+ values_bool[~mask_values].astype(values.dtype) == values[~mask_values]
+ ):
+ raise TypeError("Need to pass bool-like values")
+
+ values = values_bool
else:
- # TODO conversion from integer/float ndarray can be done more efficiently
- # (avoid roundtrip through object)
values_object = np.asarray(values, dtype=object)
inferred_dtype = lib.infer_dtype(values_object, skipna=True)
diff --git a/pandas/tests/arrays/test_boolean.py b/pandas/tests/arrays/test_boolean.py
index a13bb8edc8e48..2b946a2a925d5 100644
--- a/pandas/tests/arrays/test_boolean.py
+++ b/pandas/tests/arrays/test_boolean.py
@@ -124,6 +124,8 @@ def test_to_boolean_array_missing_indicators(a, b):
[1.0, 2.0],
pd.date_range("20130101", periods=2),
np.array(["foo"]),
+ np.array([1, 2]),
+ np.array([1.0, 2.0]),
[np.nan, {"a": 1}],
],
)
@@ -133,24 +135,37 @@ def test_to_boolean_array_error(values):
pd.array(values, dtype="boolean")
-def test_to_boolean_array_integer_like():
- # integers of 0's and 1's
- result = pd.array([1, 0, 1, 0], dtype="boolean")
+def test_to_boolean_array_from_integer_array():
+ result = pd.array(np.array([1, 0, 1, 0]), dtype="boolean")
expected = pd.array([True, False, True, False], dtype="boolean")
tm.assert_extension_array_equal(result, expected)
- result = pd.array(np.array([1, 0, 1, 0]), dtype="boolean")
+ # with missing values
+ result = pd.array(np.array([1, 0, 1, None]), dtype="boolean")
+ expected = pd.array([True, False, True, None], dtype="boolean")
tm.assert_extension_array_equal(result, expected)
+
+def test_to_boolean_array_from_float_array():
result = pd.array(np.array([1.0, 0.0, 1.0, 0.0]), dtype="boolean")
+ expected = pd.array([True, False, True, False], dtype="boolean")
tm.assert_extension_array_equal(result, expected)
# with missing values
- result = pd.array([1, 0, 1, None], dtype="boolean")
+ result = pd.array(np.array([1.0, 0.0, 1.0, np.nan]), dtype="boolean")
expected = pd.array([True, False, True, None], dtype="boolean")
tm.assert_extension_array_equal(result, expected)
- result = pd.array(np.array([1.0, 0.0, 1.0, np.nan]), dtype="boolean")
+
+def test_to_boolean_array_integer_like():
+ # integers of 0's and 1's
+ result = pd.array([1, 0, 1, 0], dtype="boolean")
+ expected = pd.array([True, False, True, False], dtype="boolean")
+ tm.assert_extension_array_equal(result, expected)
+
+ # with missing values
+ result = pd.array([1, 0, 1, None], dtype="boolean")
+ expected = pd.array([True, False, True, None], dtype="boolean")
tm.assert_extension_array_equal(result, expected)
| - [x] closes pandas-dev#29838
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/30095 | 2019-12-05T21:43:27Z | 2019-12-09T09:41:33Z | 2019-12-09T09:41:32Z | 2019-12-09T16:24:11Z |
STY: fstrings, repr pandas/io/html.py | diff --git a/pandas/io/html.py b/pandas/io/html.py
index 82c4e17a77535..cc93bba4603bf 100644
--- a/pandas/io/html.py
+++ b/pandas/io/html.py
@@ -103,7 +103,7 @@ def _get_skiprows(skiprows):
elif skiprows is None:
return 0
raise TypeError(
- "%r is not a valid type for skipping rows" % type(skiprows).__name__
+ f"'{type(skiprows).__name__}' is not a valid type for skipping rows"
)
@@ -133,7 +133,7 @@ def _read(obj):
except (TypeError, ValueError):
pass
else:
- raise TypeError("Cannot read object of type %r" % type(obj).__name__)
+ raise TypeError(f"Cannot read object of type '{type(obj).__name__}'")
return text
| - [x] ref #29547 #29886
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/30093 | 2019-12-05T20:58:57Z | 2019-12-08T17:37:06Z | 2019-12-08T17:37:06Z | 2019-12-08T21:09:27Z |
BUG: preserve EA dtype in transpose | diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index 4671170fa79ae..cc8e6f50cba2b 100644
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -863,6 +863,7 @@ Reshaping
- Bug where :meth:`DataFrame.equals` returned True incorrectly in some cases when two DataFrames had the same columns in different orders (:issue:`28839`)
- Bug in :meth:`DataFrame.replace` that caused non-numeric replacer's dtype not respected (:issue:`26632`)
- Bug in :func:`melt` where supplying mixed strings and numeric values for ``id_vars`` or ``value_vars`` would incorrectly raise a ``ValueError`` (:issue:`29718`)
+- Dtypes are now preserved when transposing a ``DataFrame`` where each column is the same extension dtype (:issue:`30091`)
- Bug in :func:`merge_asof` merging on a tz-aware ``left_index`` and ``right_on`` a tz-aware column (:issue:`29864`)
-
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index dfda1470413b7..45b89e8425b17 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2485,7 +2485,7 @@ def memory_usage(self, index=True, deep=False):
)
return result
- def transpose(self, *args, **kwargs):
+ def transpose(self, *args, copy: bool = False):
"""
Transpose index and columns.
@@ -2495,9 +2495,14 @@ def transpose(self, *args, **kwargs):
Parameters
----------
- *args, **kwargs
- Additional arguments and keywords have no effect but might be
- accepted for compatibility with numpy.
+ *args : tuple, optional
+ Accepted for compatibility with NumPy.
+ copy : bool, default False
+ Whether to copy the data after transposing, even for DataFrames
+ with a single dtype.
+
+ Note that a copy is always required for mixed dtype DataFrames,
+ or for DataFrames with any extension types.
Returns
-------
@@ -2578,7 +2583,29 @@ def transpose(self, *args, **kwargs):
dtype: object
"""
nv.validate_transpose(args, dict())
- return super().transpose(1, 0, **kwargs)
+ # construct the args
+
+ dtypes = list(self.dtypes)
+ if self._is_homogeneous_type and dtypes and is_extension_array_dtype(dtypes[0]):
+ # We have EAs with the same dtype. We can preserve that dtype in transpose.
+ dtype = dtypes[0]
+ arr_type = dtype.construct_array_type()
+ values = self.values
+
+ new_values = [arr_type._from_sequence(row, dtype=dtype) for row in values]
+ result = self._constructor(
+ dict(zip(self.index, new_values)), index=self.columns
+ )
+
+ else:
+ new_values = self.values.T
+ if copy:
+ new_values = new_values.copy()
+ result = self._constructor(
+ new_values, index=self.columns, columns=self.index
+ )
+
+ return result.__finalize__(self)
T = property(transpose)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index f846d5883a8b5..ab5ee8414d9c8 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -643,50 +643,6 @@ def _set_axis(self, axis, labels):
self._data.set_axis(axis, labels)
self._clear_item_cache()
- def transpose(self, *args, **kwargs):
- """
- Permute the dimensions of the %(klass)s
-
- Parameters
- ----------
- args : %(args_transpose)s
- copy : bool, default False
- Make a copy of the underlying data. Mixed-dtype data will
- always result in a copy
- **kwargs
- Additional keyword arguments will be passed to the function.
-
- Returns
- -------
- y : same as input
-
- Examples
- --------
- >>> p.transpose(2, 0, 1)
- >>> p.transpose(2, 0, 1, copy=True)
- """
-
- # construct the args
- axes, kwargs = self._construct_axes_from_arguments(
- args, kwargs, require_all=True
- )
- axes_names = tuple(self._get_axis_name(axes[a]) for a in self._AXIS_ORDERS)
- axes_numbers = tuple(self._get_axis_number(axes[a]) for a in self._AXIS_ORDERS)
-
- # we must have unique axes
- if len(axes) != len(set(axes)):
- raise ValueError(f"Must specify {self._AXIS_LEN} unique axes")
-
- new_axes = self._construct_axes_dict_from(
- self, [self._get_axis(x) for x in axes_names]
- )
- new_values = self.values.transpose(axes_numbers)
- if kwargs.pop("copy", None) or (len(args) and args[-1]):
- new_values = new_values.copy()
-
- nv.validate_transpose(tuple(), kwargs)
- return self._constructor(new_values, **new_axes).__finalize__(self)
-
def swapaxes(self, axis1, axis2, copy=True):
"""
Interchange axes and swap values axes appropriately.
diff --git a/pandas/tests/arithmetic/conftest.py b/pandas/tests/arithmetic/conftest.py
index 33dda75e2f110..64588af3e3053 100644
--- a/pandas/tests/arithmetic/conftest.py
+++ b/pandas/tests/arithmetic/conftest.py
@@ -235,25 +235,6 @@ def box_df_fail(request):
return request.param
-@pytest.fixture(
- params=[
- (pd.Index, False),
- (pd.Series, False),
- (pd.DataFrame, False),
- pytest.param((pd.DataFrame, True), marks=pytest.mark.xfail),
- (tm.to_array, False),
- ],
- ids=id_func,
-)
-def box_transpose_fail(request):
- """
- Fixture similar to `box` but testing both transpose cases for DataFrame,
- with the transpose=True case xfailed.
- """
- # GH#23620
- return request.param
-
-
@pytest.fixture(params=[pd.Index, pd.Series, pd.DataFrame, tm.to_array], ids=id_func)
def box_with_array(request):
"""
diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py
index 5917c8deee8a9..f0edcd11567d2 100644
--- a/pandas/tests/arithmetic/test_period.py
+++ b/pandas/tests/arithmetic/test_period.py
@@ -753,18 +753,18 @@ def test_pi_sub_isub_offset(self):
rng -= pd.offsets.MonthEnd(5)
tm.assert_index_equal(rng, expected)
- def test_pi_add_offset_n_gt1(self, box_transpose_fail):
+ @pytest.mark.parametrize("transpose", [True, False])
+ def test_pi_add_offset_n_gt1(self, box_with_array, transpose):
# GH#23215
# add offset to PeriodIndex with freq.n > 1
- box, transpose = box_transpose_fail
per = pd.Period("2016-01", freq="2M")
pi = pd.PeriodIndex([per])
expected = pd.PeriodIndex(["2016-03"], freq="2M")
- pi = tm.box_expected(pi, box, transpose=transpose)
- expected = tm.box_expected(expected, box, transpose=transpose)
+ pi = tm.box_expected(pi, box_with_array, transpose=transpose)
+ expected = tm.box_expected(expected, box_with_array, transpose=transpose)
result = pi + per.freq
tm.assert_equal(result, expected)
@@ -982,16 +982,15 @@ def test_pi_add_sub_timedeltalike_freq_mismatch_monthly(self, mismatched_freq):
with pytest.raises(IncompatibleFrequency, match=msg):
rng -= other
- def test_parr_add_sub_td64_nat(self, box_transpose_fail):
+ @pytest.mark.parametrize("transpose", [True, False])
+ def test_parr_add_sub_td64_nat(self, box_with_array, transpose):
# GH#23320 special handling for timedelta64("NaT")
- box, transpose = box_transpose_fail
-
pi = pd.period_range("1994-04-01", periods=9, freq="19D")
other = np.timedelta64("NaT")
expected = pd.PeriodIndex(["NaT"] * 9, freq="19D")
- obj = tm.box_expected(pi, box, transpose=transpose)
- expected = tm.box_expected(expected, box, transpose=transpose)
+ obj = tm.box_expected(pi, box_with_array, transpose=transpose)
+ expected = tm.box_expected(expected, box_with_array, transpose=transpose)
result = obj + other
tm.assert_equal(result, expected)
@@ -1009,16 +1008,12 @@ def test_parr_add_sub_td64_nat(self, box_transpose_fail):
TimedeltaArray._from_sequence(["NaT"] * 9),
],
)
- def test_parr_add_sub_tdt64_nat_array(self, box_df_fail, other):
- # FIXME: DataFrame fails because when when operating column-wise
- # timedelta64 entries become NaT and are treated like datetimes
- box = box_df_fail
-
+ def test_parr_add_sub_tdt64_nat_array(self, box_with_array, other):
pi = pd.period_range("1994-04-01", periods=9, freq="19D")
expected = pd.PeriodIndex(["NaT"] * 9, freq="19D")
- obj = tm.box_expected(pi, box)
- expected = tm.box_expected(expected, box)
+ obj = tm.box_expected(pi, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
result = obj + other
tm.assert_equal(result, expected)
diff --git a/pandas/tests/extension/base/reshaping.py b/pandas/tests/extension/base/reshaping.py
index 90e607343297d..89c9ed3674a66 100644
--- a/pandas/tests/extension/base/reshaping.py
+++ b/pandas/tests/extension/base/reshaping.py
@@ -295,3 +295,19 @@ def test_ravel(self, data):
# Check that we have a view, not a copy
result[0] = result[1]
assert data[0] == data[1]
+
+ def test_transpose(self, data):
+ df = pd.DataFrame({"A": data[:4], "B": data[:4]}, index=["a", "b", "c", "d"])
+ result = df.T
+ expected = pd.DataFrame(
+ {
+ "a": type(data)._from_sequence([data[0]] * 2, dtype=data.dtype),
+ "b": type(data)._from_sequence([data[1]] * 2, dtype=data.dtype),
+ "c": type(data)._from_sequence([data[2]] * 2, dtype=data.dtype),
+ "d": type(data)._from_sequence([data[3]] * 2, dtype=data.dtype),
+ },
+ index=["A", "B"],
+ )
+ self.assert_frame_equal(result, expected)
+ self.assert_frame_equal(np.transpose(np.transpose(df)), df)
+ self.assert_frame_equal(np.transpose(np.transpose(df[["A"]])), df[["A"]])
diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py
index 16a4caa7d7ebe..01f2565e2ee58 100644
--- a/pandas/tests/extension/json/test_json.py
+++ b/pandas/tests/extension/json/test_json.py
@@ -163,6 +163,10 @@ def test_unstack(self, data, index):
# this matches otherwise
return super().test_unstack(data, index)
+ @pytest.mark.xfail(reason="Inconsistent sizes.")
+ def test_transpose(self, data):
+ super().test_transpose(data)
+
class TestGetitem(BaseJSON, base.BaseGetitemTests):
pass
diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py
index beb3fc80eccd6..55a617caf28ce 100644
--- a/pandas/tests/extension/test_numpy.py
+++ b/pandas/tests/extension/test_numpy.py
@@ -332,6 +332,10 @@ def test_merge_on_extension_array_duplicates(self, data):
# Fails creating expected
super().test_merge_on_extension_array_duplicates(data)
+ @skip_nested
+ def test_transpose(self, data):
+ super().test_transpose(data)
+
class TestSetitem(BaseNumPyTests, base.BaseSetitemTests):
@skip_nested
| https://api.github.com/repos/pandas-dev/pandas/pulls/30091 | 2019-12-05T20:21:21Z | 2019-12-27T15:05:05Z | 2019-12-27T15:05:05Z | 2020-02-28T23:53:51Z | |
DEPR: join_axes kwarg to pd.concat | diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index 4ce4c12483b36..085f11f63aea2 100644
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -523,6 +523,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more.
- Removed the previously deprecated ``time_rule`` keyword from (non-public) :func:`offsets.generate_range`, which has been moved to :func:`core.arrays._ranges.generate_range` (:issue:`24157`)
- :meth:`DataFrame.loc` or :meth:`Series.loc` with listlike indexers and missing labels will no longer reindex (:issue:`17295`)
- :meth:`DataFrame.to_excel` and :meth:`Series.to_excel` with non-existent columns will no longer reindex (:issue:`17295`)
+- :func:`concat` parameter "join_axes" has been removed, use ``reindex_like`` on the result instead (:issue:`22318`)
- Removed the previously deprecated "by" keyword from :meth:`DataFrame.sort_index`, use :meth:`DataFrame.sort_values` instead (:issue:`10726`)
- Removed support for nested renaming in :meth:`DataFrame.aggregate`, :meth:`Series.aggregate`, :meth:`DataFrameGroupBy.aggregate`, :meth:`SeriesGroupBy.aggregate`, :meth:`Rolling.aggregate` (:issue:`18529`)
- Passing ``datetime64`` data to :class:`TimedeltaIndex` or ``timedelta64`` data to ``DatetimeIndex`` now raises ``TypeError`` (:issue:`23539`, :issue:`23937`)
diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py
index 853a638bdb277..8319db9f07ad8 100644
--- a/pandas/core/reshape/concat.py
+++ b/pandas/core/reshape/concat.py
@@ -3,7 +3,6 @@
"""
from typing import List
-import warnings
import numpy as np
@@ -31,7 +30,6 @@ def concat(
objs,
axis=0,
join: str = "outer",
- join_axes=None,
ignore_index: bool = False,
keys=None,
levels=None,
@@ -59,12 +57,6 @@ def concat(
The axis to concatenate along.
join : {'inner', 'outer'}, default 'outer'
How to handle indexes on other axis (or axes).
- join_axes : list of Index objects
- .. deprecated:: 0.25.0
-
- Specific indexes to use for the other n - 1 axes instead of performing
- inner/outer set logic. Use .reindex() before or after concatenation
- as a replacement.
ignore_index : bool, default False
If True, do not use the index values along the concatenation axis. The
resulting axis will be labeled 0, ..., n - 1. This is useful if you are
@@ -243,7 +235,6 @@ def concat(
axis=axis,
ignore_index=ignore_index,
join=join,
- join_axes=join_axes,
keys=keys,
levels=levels,
names=names,
@@ -265,7 +256,6 @@ def __init__(
objs,
axis=0,
join: str = "outer",
- join_axes=None,
keys=None,
levels=None,
names=None,
@@ -412,7 +402,6 @@ def __init__(
# note: this is the BlockManager axis (since DataFrame is transposed)
self.axis = axis
- self.join_axes = join_axes
self.keys = keys
self.names = names or getattr(keys, "names", None)
self.levels = levels
@@ -487,34 +476,10 @@ def _get_new_axes(self):
ndim = self._get_result_dim()
new_axes = [None] * ndim
- if self.join_axes is None:
- for i in range(ndim):
- if i == self.axis:
- continue
- new_axes[i] = self._get_comb_axis(i)
-
- else:
- # GH 21951
- warnings.warn(
- "The join_axes-keyword is deprecated. Use .reindex or "
- ".reindex_like on the result to achieve the same "
- "functionality.",
- FutureWarning,
- stacklevel=4,
- )
-
- if len(self.join_axes) != ndim - 1:
- raise AssertionError(
- "length of join_axes must be equal "
- "to {length}".format(length=ndim - 1)
- )
-
- # ufff...
- indices = list(range(ndim))
- indices.remove(self.axis)
-
- for i, ax in zip(indices, self.join_axes):
- new_axes[i] = ax
+ for i in range(ndim):
+ if i == self.axis:
+ continue
+ new_axes[i] = self._get_comb_axis(i)
new_axes[self.axis] = self._get_concat_axis()
return new_axes
diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py
index 63f1ef7595f31..ff52c4a5793bf 100644
--- a/pandas/tests/reshape/test_concat.py
+++ b/pandas/tests/reshape/test_concat.py
@@ -757,25 +757,6 @@ def test_concat_categorical_empty(self):
tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp)
tm.assert_series_equal(s2.append(s1, ignore_index=True), exp)
- def test_concat_join_axes_deprecated(self, axis):
- # GH21951
- one = pd.DataFrame([[0.0, 1.0], [2.0, 3.0]], columns=list("ab"))
- two = pd.DataFrame(
- [[10.0, 11.0], [12.0, 13.0]], index=[1, 2], columns=list("bc")
- )
-
- expected = pd.concat([one, two], axis=1, sort=False).reindex(index=two.index)
- with tm.assert_produces_warning(FutureWarning):
- result = pd.concat([one, two], axis=1, sort=False, join_axes=[two.index])
- tm.assert_frame_equal(result, expected)
-
- expected = pd.concat([one, two], axis=0, sort=False).reindex(
- columns=two.columns
- )
- with tm.assert_produces_warning(FutureWarning):
- result = pd.concat([one, two], axis=0, sort=False, join_axes=[two.columns])
- tm.assert_frame_equal(result, expected)
-
class TestAppend:
def test_append(self, sort, float_frame):
| https://api.github.com/repos/pandas-dev/pandas/pulls/30090 | 2019-12-05T20:05:28Z | 2019-12-05T23:11:57Z | 2019-12-05T23:11:57Z | 2019-12-05T23:48:32Z | |
DEPR: enforce deprecation of old set_axis signature | diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index 5e2eaa6ca4a94..75d28f7cca1c5 100644
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -613,6 +613,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more.
- Changed :meth:`Timedelta.resolution` to match the behavior of the standard library ``datetime.timedelta.resolution``, for the old behavior, use :meth:`Timedelta.resolution_string` (:issue:`26839`)
- Removed previously deprecated :attr:`Timestamp.weekday_name`, :attr:`DatetimeIndex.weekday_name`, and :attr:`Series.dt.weekday_name` (:issue:`18164`)
- Removed previously deprecated ``errors`` argument in :meth:`Timestamp.tz_localize`, :meth:`DatetimeIndex.tz_localize`, and :meth:`Series.tz_localize` (:issue:`22644`)
+- :meth:`Series.set_axis` and :meth:`DataFrame.set_axis` now require "labels" as the first argument and "axis" as an optional named parameter (:issue:`30089`)
-
.. _whatsnew_1000.performance:
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index bcc742e731110..3e41721b65f5d 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -633,17 +633,6 @@ def set_axis(self, labels, axis=0, inplace=False):
1 2 5
2 3 6
"""
- if is_scalar(labels):
- warnings.warn(
- 'set_axis now takes "labels" as first argument, and '
- '"axis" as named parameter. The old form, with "axis" as '
- 'first parameter and "labels" as second, is still supported '
- "but will be deprecated in a future version of pandas.",
- FutureWarning,
- stacklevel=2,
- )
- labels, axis = axis, labels
-
if inplace:
setattr(self, self._get_axis_name(axis), labels)
else:
diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py
index b52f24f9e06f1..48b373d9c7901 100644
--- a/pandas/tests/frame/test_alter_axes.py
+++ b/pandas/tests/frame/test_alter_axes.py
@@ -1548,21 +1548,3 @@ def test_set_axis_inplace(self):
for axis in 3, "foo":
with pytest.raises(ValueError, match="No axis named"):
df.set_axis(list("abc"), axis=axis)
-
- def test_set_axis_prior_to_deprecation_signature(self):
- df = DataFrame(
- {"A": [1.1, 2.2, 3.3], "B": [5.0, 6.1, 7.2], "C": [4.4, 5.5, 6.6]},
- index=[2010, 2011, 2012],
- )
-
- expected = {0: df.copy(), 1: df.copy()}
- expected[0].index = list("abc")
- expected[1].columns = list("abc")
- expected["index"] = expected[0]
- expected["columns"] = expected[1]
-
- # old signature
- for axis in expected:
- with tm.assert_produces_warning(FutureWarning):
- result = df.set_axis(axis, list("abc"), inplace=False)
- tm.assert_frame_equal(result, expected[axis])
diff --git a/pandas/tests/series/test_alter_axes.py b/pandas/tests/series/test_alter_axes.py
index 7a24a45b4b6c2..9e1bae8469138 100644
--- a/pandas/tests/series/test_alter_axes.py
+++ b/pandas/tests/series/test_alter_axes.py
@@ -322,17 +322,6 @@ def test_set_axis_inplace(self):
with pytest.raises(ValueError, match="No axis named"):
s.set_axis(list("abcd"), axis=axis, inplace=False)
- def test_set_axis_prior_to_deprecation_signature(self):
- s = Series(np.arange(4), index=[1, 3, 5, 7], dtype="int64")
-
- expected = s.copy()
- expected.index = list("abcd")
-
- for axis in [0, "index"]:
- with tm.assert_produces_warning(FutureWarning):
- result = s.set_axis(0, list("abcd"), inplace=False)
- tm.assert_series_equal(result, expected)
-
def test_reset_index_drop_errors(self):
# GH 20925
| https://api.github.com/repos/pandas-dev/pandas/pulls/30089 | 2019-12-05T19:48:25Z | 2019-12-06T14:40:36Z | 2019-12-06T14:40:35Z | 2019-12-06T15:24:28Z | |
DEPR: remove compound | diff --git a/doc/redirects.csv b/doc/redirects.csv
index 33ba94e2baa01..1471bfb82c07c 100644
--- a/doc/redirects.csv
+++ b/doc/redirects.csv
@@ -319,7 +319,6 @@ generated/pandas.DataFrame.clip_upper,../reference/api/pandas.DataFrame.clip_upp
generated/pandas.DataFrame.columns,../reference/api/pandas.DataFrame.columns
generated/pandas.DataFrame.combine_first,../reference/api/pandas.DataFrame.combine_first
generated/pandas.DataFrame.combine,../reference/api/pandas.DataFrame.combine
-generated/pandas.DataFrame.compound,../reference/api/pandas.DataFrame.compound
generated/pandas.DataFrame.convert_objects,../reference/api/pandas.DataFrame.convert_objects
generated/pandas.DataFrame.copy,../reference/api/pandas.DataFrame.copy
generated/pandas.DataFrame.corr,../reference/api/pandas.DataFrame.corr
@@ -950,7 +949,6 @@ generated/pandas.Series.clip_lower,../reference/api/pandas.Series.clip_lower
generated/pandas.Series.clip_upper,../reference/api/pandas.Series.clip_upper
generated/pandas.Series.combine_first,../reference/api/pandas.Series.combine_first
generated/pandas.Series.combine,../reference/api/pandas.Series.combine
-generated/pandas.Series.compound,../reference/api/pandas.Series.compound
generated/pandas.Series.compress,../reference/api/pandas.Series.compress
generated/pandas.Series.convert_objects,../reference/api/pandas.Series.convert_objects
generated/pandas.Series.copy,../reference/api/pandas.Series.copy
diff --git a/doc/source/getting_started/10min.rst b/doc/source/getting_started/10min.rst
index 41520795bde62..66e500131b316 100644
--- a/doc/source/getting_started/10min.rst
+++ b/doc/source/getting_started/10min.rst
@@ -75,8 +75,8 @@ will be completed:
df2.all df2.columns
df2.any df2.combine
df2.append df2.combine_first
- df2.apply df2.compound
- df2.applymap df2.consolidate
+ df2.apply df2.consolidate
+ df2.applymap
df2.D
As you can see, the columns ``A``, ``B``, ``C``, and ``D`` are automatically
diff --git a/doc/source/reference/frame.rst b/doc/source/reference/frame.rst
index 4c296d74b5ef9..8eeca1ec28054 100644
--- a/doc/source/reference/frame.rst
+++ b/doc/source/reference/frame.rst
@@ -137,7 +137,6 @@ Computations / descriptive stats
DataFrame.all
DataFrame.any
DataFrame.clip
- DataFrame.compound
DataFrame.corr
DataFrame.corrwith
DataFrame.count
diff --git a/doc/source/reference/series.rst b/doc/source/reference/series.rst
index 1e17b72db2aaf..807dc151dac4e 100644
--- a/doc/source/reference/series.rst
+++ b/doc/source/reference/series.rst
@@ -174,7 +174,6 @@ Computations / descriptive stats
Series.is_monotonic_increasing
Series.is_monotonic_decreasing
Series.value_counts
- Series.compound
Reindexing / selection / label manipulation
-------------------------------------------
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index 1a07b424fa884..4198ddf4b7a2a 100644
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -535,6 +535,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more.
- Removed the previously deprecated :meth:`Index.summary` (:issue:`18217`)
- Removed the previously deprecated "fastpath" keyword from the :class:`Index` constructor (:issue:`23110`)
- Removed the previously deprecated :meth:`Series.get_value`, :meth:`Series.set_value`, :meth:`DataFrame.get_value`, :meth:`DataFrame.set_value` (:issue:`17739`)
+- Removed the previously deprecated :meth:`Series.compound` and :meth:`DataFrame.compound` (:issue:`26405`)
- Changed the the default value of `inplace` in :meth:`DataFrame.set_index` and :meth:`Series.set_axis`. It now defaults to ``False`` (:issue:`27600`)
- Removed the previously deprecated :attr:`Series.cat.categorical`, :attr:`Series.cat.index`, :attr:`Series.cat.name` (:issue:`24751`)
- Removed the previously deprecated ``time_rule`` keyword from (non-public) :func:`offsets.generate_range`, which has been moved to :func:`core.arrays._ranges.generate_range` (:issue:`24157`)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index efdcfa7edbba3..bcc742e731110 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -10117,29 +10117,6 @@ def mad(self, axis=None, skipna=None, level=None):
nanops.nanstd,
)
- @Substitution(
- desc="Return the compound percentage of the values for "
- "the requested axis.\n\n.. deprecated:: 0.25.0",
- name1=name,
- name2=name2,
- axis_descr=axis_descr,
- min_count="",
- see_also="",
- examples="",
- )
- @Appender(_num_doc)
- def compound(self, axis=None, skipna=None, level=None):
- msg = (
- "The 'compound' method is deprecated and will be"
- "removed in a future version."
- )
- warnings.warn(msg, FutureWarning, stacklevel=2)
- if skipna is None:
- skipna = True
- return (1 + self).prod(axis=axis, skipna=skipna, level=level) - 1
-
- cls.compound = compound
-
cls.cummin = _make_cum_function(
cls,
"cummin",
diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py
index 71b4819bb4da8..c6c960910214a 100644
--- a/pandas/tests/series/test_analytics.py
+++ b/pandas/tests/series/test_analytics.py
@@ -1276,15 +1276,6 @@ def test_validate_stat_keepdims(self):
with pytest.raises(ValueError, match=msg):
np.sum(s, keepdims=True)
- def test_compound_deprecated(self):
- s = Series([0.1, 0.2, 0.3, 0.4])
- with tm.assert_produces_warning(FutureWarning):
- s.compound()
-
- df = pd.DataFrame({"s": s})
- with tm.assert_produces_warning(FutureWarning):
- df.compound()
-
main_dtypes = [
"datetime",
| https://api.github.com/repos/pandas-dev/pandas/pulls/30088 | 2019-12-05T19:42:49Z | 2019-12-05T23:02:59Z | 2019-12-05T23:02:58Z | 2019-12-05T23:47:22Z | |
REF: do string itemsize casting earlier | diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 8a75e0f56f8c9..878bd64fb5571 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -2326,7 +2326,7 @@ def set_kind(self):
if self.typ is None:
self.typ = getattr(self.description, self.cname, None)
- def set_atom(self, block, itemsize: int, data_converted, use_str: bool):
+ def set_atom(self, block, data_converted, use_str: bool):
""" create and setup my atom from the block b """
# short-cut certain block types
@@ -2342,7 +2342,7 @@ def set_atom(self, block, itemsize: int, data_converted, use_str: bool):
self.set_atom_complex(block)
elif use_str:
- self.set_atom_string(itemsize, data_converted)
+ self.set_atom_string(data_converted)
else:
# set as a data block
self.set_atom_data(block)
@@ -2350,10 +2350,11 @@ def set_atom(self, block, itemsize: int, data_converted, use_str: bool):
def get_atom_string(self, shape, itemsize):
return _tables().StringCol(itemsize=itemsize, shape=shape[0])
- def set_atom_string(self, itemsize: int, data_converted: np.ndarray):
+ def set_atom_string(self, data_converted: np.ndarray):
+ itemsize = data_converted.dtype.itemsize
self.kind = "string"
self.typ = self.get_atom_string(data_converted.shape, itemsize)
- self.set_data(data_converted.astype(f"|S{itemsize}", copy=False))
+ self.set_data(data_converted)
def get_atom_coltype(self, kind=None):
""" return the PyTables column class for this column """
@@ -3904,7 +3905,7 @@ def get_blk_items(mgr, blocks):
existing_col = None
new_name = name or f"values_block_{i}"
- itemsize, data_converted, use_str = _maybe_convert_for_string_atom(
+ data_converted, use_str = _maybe_convert_for_string_atom(
new_name,
b,
existing_col=existing_col,
@@ -3916,12 +3917,7 @@ def get_blk_items(mgr, blocks):
col = klass.create_for_block(i=i, name=new_name, version=self.version)
col.values = list(b_items)
- col.set_atom(
- block=b,
- itemsize=itemsize,
- data_converted=data_converted,
- use_str=use_str,
- )
+ col.set_atom(block=b, data_converted=data_converted, use_str=use_str)
col.update_info(self.info)
col.set_pos(j)
@@ -4793,7 +4789,7 @@ def _maybe_convert_for_string_atom(
use_str = False
if not block.is_object:
- return block.dtype.itemsize, block.values, use_str
+ return block.values, use_str
dtype_name = block.dtype.name
inferred_type = lib.infer_dtype(block.values, skipna=False)
@@ -4808,7 +4804,7 @@ def _maybe_convert_for_string_atom(
)
elif not (inferred_type == "string" or dtype_name == "object"):
- return block.dtype.itemsize, block.values, use_str
+ return block.values, use_str
use_str = True
@@ -4852,7 +4848,8 @@ def _maybe_convert_for_string_atom(
if eci > itemsize:
itemsize = eci
- return itemsize, data_converted, use_str
+ data_converted = data_converted.astype(f"|S{itemsize}", copy=False)
+ return data_converted, use_str
def _convert_string_array(data, encoding, errors, itemsize=None):
| This is the other PR mentioned in #30084. By doing this casting earlier, we'll be able to 7 calls to set_data into one place. | https://api.github.com/repos/pandas-dev/pandas/pulls/30085 | 2019-12-05T17:15:19Z | 2019-12-05T23:13:50Z | 2019-12-05T23:13:50Z | 2019-12-05T23:51:17Z |
REF: Standardize coercion in set_data | diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 1d24e15c504f2..d1d06d821e4f4 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -2270,15 +2270,25 @@ def __eq__(self, other: Any) -> bool:
for a in ["name", "cname", "dtype", "pos"]
)
- def set_data(self, data, dtype=None):
+ def set_data(self, data: Union[np.ndarray, ABCExtensionArray]):
+ assert data is not None
+
+ if is_categorical_dtype(data.dtype):
+ data = data.codes
+
+ # For datetime64tz we need to drop the TZ in tests TODO: why?
+ dtype_name = data.dtype.name.split("[")[0]
+
+ if data.dtype.kind in ["m", "M"]:
+ data = np.asarray(data.view("i8"))
+ # TODO: we used to reshape for the dt64tz case, but no longer
+ # doing that doesnt seem to break anything. why?
+
self.data = data
- if data is not None:
- if dtype is not None:
- self.dtype = dtype
- self.set_kind()
- elif self.dtype is None:
- self.dtype = data.dtype.name
- self.set_kind()
+
+ if self.dtype is None:
+ self.dtype = dtype_name
+ self.set_kind()
def take_data(self):
""" return the data & release the memory """
@@ -2363,12 +2373,12 @@ def set_atom_complex(self, block):
self.kind = block.dtype.name
itemsize = int(self.kind.split("complex")[-1]) // 8
self.typ = _tables().ComplexCol(itemsize=itemsize, shape=block.shape[0])
- self.set_data(block.values.astype(self.typ.type, copy=False))
+ self.set_data(block.values)
def set_atom_data(self, block):
self.kind = block.dtype.name
self.typ = self.get_atom_data(block)
- self.set_data(block.values.astype(self.typ.type, copy=False))
+ self.set_data(block.values)
def set_atom_categorical(self, block):
# currently only supports a 1-D categorical
@@ -2384,7 +2394,7 @@ def set_atom_categorical(self, block):
# write the codes; must be in a block shape
self.ordered = values.ordered
self.typ = self.get_atom_data(block, kind=codes.dtype.name)
- self.set_data(codes)
+ self.set_data(block.values)
# write the categories
self.meta = "category"
@@ -2396,22 +2406,16 @@ def get_atom_datetime64(self, block):
def set_atom_datetime64(self, block):
self.kind = "datetime64"
self.typ = self.get_atom_datetime64(block)
- values = block.values.view("i8")
- self.set_data(values, "datetime64")
+ self.set_data(block.values)
def set_atom_datetime64tz(self, block):
- values = block.values
-
- # convert this column to i8 in UTC, and save the tz
- values = values.asi8.reshape(block.shape)
-
# store a converted timezone
self.tz = _get_tz(block.values.tz)
self.kind = "datetime64"
self.typ = self.get_atom_datetime64(block)
- self.set_data(values, "datetime64")
+ self.set_data(block.values)
def get_atom_timedelta64(self, block):
return _tables().Int64Col(shape=block.shape[0])
@@ -2419,8 +2423,7 @@ def get_atom_timedelta64(self, block):
def set_atom_timedelta64(self, block):
self.kind = "timedelta64"
self.typ = self.get_atom_timedelta64(block)
- values = block.values.view("i8")
- self.set_data(values, "timedelta64")
+ self.set_data(block.values)
@property
def shape(self):
@@ -2454,6 +2457,7 @@ def convert(self, values, nan_rep, encoding, errors, start=None, stop=None):
if values.dtype.fields is not None:
values = values[self.cname]
+ # NB: unlike in the other calls to set_data, self.dtype may not be None here
self.set_data(values)
# use the meta if needed
| See that after this, the way we are calling `self.set_data` is always with just `block.values` within the `set_atom_foo` methods (except for `set_atom_string`, which needs a small edit coming up in another PR). Once set_atom_string joins the others, we can move these 7 calls to set_data up to just one place. | https://api.github.com/repos/pandas-dev/pandas/pulls/30084 | 2019-12-05T17:12:24Z | 2019-12-05T19:26:42Z | 2019-12-05T19:26:42Z | 2019-12-05T20:10:26Z |
Fixes Error thrown when None is passed to pd.to_datetime() with format as %Y%m%d | diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index 4ce4c12483b36..8caba5cf9d53f 100644
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -652,6 +652,7 @@ Datetimelike
- Bug in :meth:`Series.var` failing to raise ``TypeError`` when called with ``timedelta64[ns]`` dtype (:issue:`28289`)
- Bug in :meth:`DatetimeIndex.strftime` and :meth:`Series.dt.strftime` where ``NaT`` was converted to the string ``'NaT'`` instead of ``np.nan`` (:issue:`29578`)
- Bug in :attr:`Timestamp.resolution` being a property instead of a class attribute (:issue:`29910`)
+- Bug in :func:`pandas.to_datetime` when called with ``None`` raising ``TypeError`` instead of returning ``NaT`` (:issue:`30011`)
Timedelta
^^^^^^^^^
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py
index 453d1cca2e085..f5695343282a6 100644
--- a/pandas/core/tools/datetimes.py
+++ b/pandas/core/tools/datetimes.py
@@ -940,21 +940,21 @@ def calc_with_mask(carg, mask):
# try intlike / strings that are ints
try:
return calc(arg.astype(np.int64))
- except (ValueError, OverflowError):
+ except (ValueError, OverflowError, TypeError):
pass
# a float with actual np.nan
try:
carg = arg.astype(np.float64)
return calc_with_mask(carg, notna(carg))
- except (ValueError, OverflowError):
+ except (ValueError, OverflowError, TypeError):
pass
# string with NaN-like
try:
mask = ~algorithms.isin(arg, list(tslib.nat_strings))
return calc_with_mask(arg, mask)
- except (ValueError, OverflowError):
+ except (ValueError, OverflowError, TypeError):
pass
return None
diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py
index 4e5d624eba844..ee4611d0f56df 100644
--- a/pandas/tests/indexes/datetimes/test_tools.py
+++ b/pandas/tests/indexes/datetimes/test_tools.py
@@ -101,6 +101,29 @@ def test_to_datetime_format_YYYYMMDD(self, cache):
expected = Series(["20121231", "20141231", "NaT"], dtype="M8[ns]")
tm.assert_series_equal(result, expected)
+ @pytest.mark.parametrize(
+ "input_s",
+ [
+ # Null values with Strings
+ ["19801222", "20010112", None],
+ ["19801222", "20010112", np.nan],
+ ["19801222", "20010112", pd.NaT],
+ ["19801222", "20010112", "NaT"],
+ # Null values with Integers
+ [19801222, 20010112, None],
+ [19801222, 20010112, np.nan],
+ [19801222, 20010112, pd.NaT],
+ [19801222, 20010112, "NaT"],
+ ],
+ )
+ def test_to_datetime_format_YYYYMMDD_with_none(self, input_s):
+ # GH 30011
+ # format='%Y%m%d'
+ # with None
+ expected = Series([Timestamp("19801222"), Timestamp("20010112"), pd.NaT])
+ result = Series(pd.to_datetime(input_s, format="%Y%m%d"))
+ tm.assert_series_equal(result, expected)
+
@pytest.mark.parametrize(
"input_s, expected",
[
| - [ ] closes #30011
- [x] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry `bug fix of to_datetime for pandas versions >0.24. Now the change will avoid error even when value passed None to to_datetime`
| https://api.github.com/repos/pandas-dev/pandas/pulls/30083 | 2019-12-05T16:42:54Z | 2019-12-12T14:53:49Z | 2019-12-12T14:53:49Z | 2019-12-12T15:08:53Z |
REF: make pytables.IndexCol.itemsize a property | diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 1d24e15c504f2..8b04fab6587da 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -1882,7 +1882,6 @@ def __init__(
kind=None,
typ=None,
cname: Optional[str] = None,
- itemsize=None,
axis=None,
pos=None,
freq=None,
@@ -1896,7 +1895,6 @@ def __init__(
self.values = values
self.kind = kind
self.typ = typ
- self.itemsize = itemsize
self.name = name
self.cname = cname or name
self.axis = axis
@@ -1916,6 +1914,11 @@ def __init__(
assert isinstance(self.name, str)
assert isinstance(self.cname, str)
+ @property
+ def itemsize(self) -> int:
+ # Assumes self.typ has already been initialized
+ return self.typ.itemsize
+
@property
def kind_attr(self) -> str:
return f"{self.name}_kind"
@@ -2338,7 +2341,6 @@ def get_atom_string(self, shape, itemsize):
return _tables().StringCol(itemsize=itemsize, shape=shape[0])
def set_atom_string(self, itemsize: int, data_converted: np.ndarray):
- self.itemsize = itemsize
self.kind = "string"
self.typ = self.get_atom_string(data_converted.shape, itemsize)
self.set_data(data_converted.astype(f"|S{itemsize}", copy=False))
@@ -4724,7 +4726,6 @@ def _convert_index(name: str, index: Index, encoding=None, errors="strict"):
converted,
"string",
_tables().StringCol(itemsize),
- itemsize=itemsize,
index_name=index_name,
)
| Along with #30074 this is a bite-sized-pieces part of a series of PRs that ends with IndexCol attributes being set in the constructor and not mutated elsewhere | https://api.github.com/repos/pandas-dev/pandas/pulls/30082 | 2019-12-05T16:42:14Z | 2019-12-05T19:22:33Z | 2019-12-05T19:22:33Z | 2019-12-05T20:10:46Z |
STY: fstrings doc/source/conf.py #2 | diff --git a/doc/source/conf.py b/doc/source/conf.py
index 5f6a6af60e9bf..096f1a63eddf8 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -568,7 +568,7 @@ def _add_deprecation_prefixes(self, items):
for item in items:
display_name, sig, summary, real_name = item
if self._is_deprecated(real_name):
- summary = "(DEPRECATED) %s" % summary
+ summary = f"(DEPRECATED) {summary}"
yield display_name, sig, summary, real_name
def get_items(self, names):
| - [x] ref #29547
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Somehow missed it on #30071 | https://api.github.com/repos/pandas-dev/pandas/pulls/30080 | 2019-12-05T13:50:51Z | 2019-12-05T14:45:10Z | 2019-12-05T14:45:10Z | 2019-12-05T14:56:13Z |
TYP: Annotations in pandas/core/{accessor, sorting}.py | diff --git a/pandas/core/accessor.py b/pandas/core/accessor.py
index 96b7cf8f97c3f..963c9c65cb30c 100644
--- a/pandas/core/accessor.py
+++ b/pandas/core/accessor.py
@@ -58,7 +58,9 @@ def _delegate_method(self, name, *args, **kwargs):
raise TypeError("You cannot call method {name}".format(name=name))
@classmethod
- def _add_delegate_accessors(cls, delegate, accessors, typ, overwrite=False):
+ def _add_delegate_accessors(
+ cls, delegate, accessors, typ: str, overwrite: bool = False
+ ):
"""
Add accessors to cls from the delegate class.
@@ -107,7 +109,7 @@ def f(self, *args, **kwargs):
setattr(cls, name, f)
-def delegate_names(delegate, accessors, typ, overwrite=False):
+def delegate_names(delegate, accessors, typ: str, overwrite: bool = False):
"""
Add delegated names to a class using a class decorator. This provides
an alternative usage to directly calling `_add_delegate_accessors`
@@ -162,7 +164,7 @@ class CachedAccessor:
the single argument ``data``.
"""
- def __init__(self, name, accessor):
+ def __init__(self, name: str, accessor) -> None:
self._name = name
self._accessor = accessor
diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py
index b99ac9cc333c6..3005bdcbe78a4 100644
--- a/pandas/core/sorting.py
+++ b/pandas/core/sorting.py
@@ -187,7 +187,7 @@ def indexer_from_factorized(labels, shape, compress: bool = True):
return get_group_index_sorter(ids, ngroups)
-def lexsort_indexer(keys, orders=None, na_position="last"):
+def lexsort_indexer(keys, orders=None, na_position: str = "last"):
from pandas.core.arrays import Categorical
labels = []
@@ -233,7 +233,9 @@ def lexsort_indexer(keys, orders=None, na_position="last"):
return indexer_from_factorized(labels, shape)
-def nargsort(items, kind="quicksort", ascending: bool = True, na_position="last"):
+def nargsort(
+ items, kind: str = "quicksort", ascending: bool = True, na_position: str = "last"
+):
"""
This is intended to be a drop-in replacement for np.argsort which
handles NaNs. It adds ascending and na_position parameters.
@@ -273,7 +275,7 @@ class _KeyMapper:
Ease my suffering. Map compressed group id -> key tuple
"""
- def __init__(self, comp_ids, ngroups, levels, labels):
+ def __init__(self, comp_ids, ngroups: int, levels, labels):
self.levels = levels
self.labels = labels
self.comp_ids = comp_ids.astype(np.int64)
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/30079 | 2019-12-05T10:49:19Z | 2019-12-06T20:47:38Z | 2019-12-06T20:47:38Z | 2019-12-07T09:08:42Z |
BUG/TST: fix arrow roundtrip / parquet tests for recent pyarrow | diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py
index 743d45e1fa400..a8fcd6d03847c 100644
--- a/pandas/core/arrays/boolean.py
+++ b/pandas/core/arrays/boolean.py
@@ -103,6 +103,24 @@ def __repr__(self) -> str:
def _is_boolean(self) -> bool:
return True
+ def __from_arrow__(self, array):
+ """Construct BooleanArray from passed pyarrow Array/ChunkedArray"""
+ import pyarrow
+
+ if isinstance(array, pyarrow.Array):
+ chunks = [array]
+ else:
+ # pyarrow.ChunkedArray
+ chunks = array.chunks
+
+ results = []
+ for arr in chunks:
+ # TODO should optimize this without going through object array
+ bool_arr = BooleanArray._from_sequence(np.array(arr))
+ results.append(bool_arr)
+
+ return BooleanArray._concat_same_type(results)
+
def coerce_to_array(values, mask=None, copy: bool = False):
"""
diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py
index 3bad7f0162f44..0d30aa06cd466 100644
--- a/pandas/core/arrays/string_.py
+++ b/pandas/core/arrays/string_.py
@@ -86,7 +86,7 @@ def __from_arrow__(self, array):
results = []
for arr in chunks:
- # using _from_sequence to ensure None is convered to np.nan
+ # using _from_sequence to ensure None is convered to NA
str_arr = StringArray._from_sequence(np.array(arr))
results.append(str_arr)
@@ -208,7 +208,10 @@ def __arrow_array__(self, type=None):
if type is None:
type = pa.string()
- return pa.array(self._ndarray, type=type, from_pandas=True)
+
+ values = self._ndarray.copy()
+ values[self.isna()] = None
+ return pa.array(values, type=type, from_pandas=True)
def _values_for_factorize(self):
arr = self._ndarray.copy()
diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py
index 0544ee4002890..c3f342f16a0bf 100644
--- a/pandas/tests/arrays/string_/test_string.py
+++ b/pandas/tests/arrays/string_/test_string.py
@@ -235,5 +235,5 @@ def test_arrow_roundtrip():
result = table.to_pandas()
assert isinstance(result["a"].dtype, pd.StringDtype)
tm.assert_frame_equal(result, df)
- # ensure the missing value is represented by NaN and not None
- assert np.isnan(result.loc[2, "a"])
+ # ensure the missing value is represented by NA and not np.nan or None
+ assert result.loc[2, "a"] is pd.NA
diff --git a/pandas/tests/arrays/test_boolean.py b/pandas/tests/arrays/test_boolean.py
index 90bcd66987e0d..abec4b42c0ffb 100644
--- a/pandas/tests/arrays/test_boolean.py
+++ b/pandas/tests/arrays/test_boolean.py
@@ -757,12 +757,29 @@ def test_any_all(values, exp_any, exp_all, exp_any_noskip, exp_all_noskip):
# result = arr[mask]
-@pytest.mark.skip(reason="broken test")
@td.skip_if_no("pyarrow", min_version="0.15.0")
def test_arrow_array(data):
# protocol added in 0.15.0
import pyarrow as pa
arr = pa.array(data)
- expected = pa.array(np.array(data, dtype=object), type=pa.bool_(), from_pandas=True)
+
+ # TODO use to_numpy(na_value=None) here
+ data_object = np.array(data, dtype=object)
+ data_object[data.isna()] = None
+ expected = pa.array(data_object, type=pa.bool_(), from_pandas=True)
assert arr.equals(expected)
+
+
+@td.skip_if_no("pyarrow", min_version="0.15.1.dev")
+def test_arrow_roundtrip():
+ # roundtrip possible from arrow 1.0.0
+ import pyarrow as pa
+
+ data = pd.array([True, False, None], dtype="boolean")
+ df = pd.DataFrame({"a": data})
+ table = pa.table(df)
+ assert table.field("a").type == "bool"
+ result = table.to_pandas()
+ assert isinstance(result["a"].dtype, pd.BooleanDtype)
+ tm.assert_frame_equal(result, df)
diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index 0b8677d6b1415..fc3d55e110d69 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -525,7 +525,6 @@ def test_write_with_schema(self, pa):
out_df = df.astype(bool)
check_round_trip(df, pa, write_kwargs={"schema": schema}, expected=out_df)
- @pytest.mark.skip(reason="broken test")
@td.skip_if_no("pyarrow", min_version="0.15.0")
def test_additional_extension_arrays(self, pa):
# test additional ExtensionArrays that are supported through the
| Closes https://github.com/pandas-dev/pandas/issues/29976 | https://api.github.com/repos/pandas-dev/pandas/pulls/30077 | 2019-12-05T08:07:23Z | 2019-12-18T16:56:42Z | 2019-12-18T16:56:42Z | 2019-12-18T16:56:43Z |
Fix PR06 docstring errors in sql.py and gbq.py | diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py
index b120de1b3011a..19aed15f46491 100644
--- a/pandas/io/gbq.py
+++ b/pandas/io/gbq.py
@@ -50,10 +50,10 @@ def read_gbq(
col_order : list(str), optional
List of BigQuery column names in the desired order for results
DataFrame.
- reauth : boolean, default False
+ reauth : bool, default False
Force Google BigQuery to re-authenticate the user. This is useful
if multiple accounts are used.
- auth_local_webserver : boolean, default False
+ auth_local_webserver : bool, default False
Use the `local webserver flow`_ instead of the `console flow`_
when getting user credentials.
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index 684e602f06d12..b619ea93b981d 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -277,14 +277,14 @@ def read_sql_query(
Parameters
----------
- sql : string SQL query or SQLAlchemy Selectable (select or text object)
+ sql : str SQL query or SQLAlchemy Selectable (select or text object)
SQL query to be executed.
- con : SQLAlchemy connectable(engine/connection), database string URI,
+ con : SQLAlchemy connectable(engine/connection), database str URI,
or sqlite3 DBAPI2 connection
Using SQLAlchemy makes it possible to use any DB supported by that
library.
If a DBAPI2 object, only sqlite3 is supported.
- index_col : string or list of strings, optional, default: None
+ index_col : str or list of strings, optional, default: None
Column(s) to set as index(MultiIndex).
coerce_float : bool, default True
Attempts to convert values of non-string, non-numeric objects (like
@@ -355,18 +355,18 @@ def read_sql(
Parameters
----------
- sql : string or SQLAlchemy Selectable (select or text object)
+ sql : str or SQLAlchemy Selectable (select or text object)
SQL query to be executed or a table name.
- con : SQLAlchemy connectable (engine/connection) or database string URI
- or DBAPI2 connection (fallback mode)
+ con : SQLAlchemy connectable (engine/connection) or database str URI
+ or DBAPI2 connection (fallback mode)'
Using SQLAlchemy makes it possible to use any DB supported by that
library. If a DBAPI2 object, only sqlite3 is supported. The user is responsible
for engine disposal and connection closure for the SQLAlchemy connectable. See
`here <https://docs.sqlalchemy.org/en/13/core/connections.html>`_
- index_col : string or list of strings, optional, default: None
+ index_col : str or list of strings, optional, default: None
Column(s) to set as index(MultiIndex).
- coerce_float : boolean, default True
+ coerce_float : bool, default True
Attempts to convert values of non-string, non-numeric objects (like
decimal.Decimal) to floating point, useful for SQL result sets.
params : list, tuple or dict, optional, default: None
| - [x] xref #28724
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/30075 | 2019-12-05T04:37:42Z | 2019-12-05T06:35:59Z | 2019-12-05T06:35:59Z | 2019-12-05T06:36:06Z |
REF: make pytables get_atom_data non-stateful | diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 8a75e0f56f8c9..7581bec68d44b 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -65,7 +65,7 @@
from pandas.io.formats.printing import adjoin, pprint_thing
if TYPE_CHECKING:
- from tables import File, Node # noqa:F401
+ from tables import File, Node, Col # noqa:F401
# versioning attribute
@@ -1092,6 +1092,9 @@ def remove(self, key: str, where=None, start=None, stop=None):
except KeyError:
# the key is not a valid store, re-raising KeyError
raise
+ except AssertionError:
+ # surface any assertion errors for e.g. debugging
+ raise
except Exception:
# In tests we get here with ClosedFileError, TypeError, and
# _table_mod.NoSuchNodeError. TODO: Catch only these?
@@ -1519,6 +1522,9 @@ def info(self) -> str:
if s is not None:
keys.append(pprint_thing(s.pathname or k))
values.append(pprint_thing(s or "invalid_HDFStore node"))
+ except AssertionError:
+ # surface any assertion errors for e.g. debugging
+ raise
except Exception as detail:
keys.append(k)
dstr = pprint_thing(detail)
@@ -1680,7 +1686,7 @@ def _write_to_group(
self._handle.remove_node(group, recursive=True)
group = None
- # we don't want to store a table node at all if are object is 0-len
+ # we don't want to store a table node at all if our object is 0-len
# as there are not dtypes
if getattr(value, "empty", None) and (format == "table" or append):
return
@@ -2355,11 +2361,9 @@ def set_atom_string(self, itemsize: int, data_converted: np.ndarray):
self.typ = self.get_atom_string(data_converted.shape, itemsize)
self.set_data(data_converted.astype(f"|S{itemsize}", copy=False))
- def get_atom_coltype(self, kind=None):
+ def get_atom_coltype(self, kind: str) -> Type["Col"]:
""" return the PyTables column class for this column """
- if kind is None:
- kind = self.kind
- if self.kind.startswith("uint"):
+ if kind.startswith("uint"):
k4 = kind[4:]
col_name = f"UInt{k4}Col"
else:
@@ -2368,8 +2372,8 @@ def get_atom_coltype(self, kind=None):
return getattr(_tables(), col_name)
- def get_atom_data(self, block, kind=None):
- return self.get_atom_coltype(kind=kind)(shape=block.shape[0])
+ def get_atom_data(self, shape, kind: str) -> "Col":
+ return self.get_atom_coltype(kind=kind)(shape=shape[0])
def set_atom_complex(self, block):
self.kind = block.dtype.name
@@ -2379,7 +2383,7 @@ def set_atom_complex(self, block):
def set_atom_data(self, block):
self.kind = block.dtype.name
- self.typ = self.get_atom_data(block)
+ self.typ = self.get_atom_data(block.shape, kind=block.dtype.name)
self.set_data(block.values)
def set_atom_categorical(self, block):
@@ -2388,19 +2392,22 @@ def set_atom_categorical(self, block):
values = block.values
codes = values.codes
- self.kind = "integer"
- self.dtype = codes.dtype.name
+
if values.ndim > 1:
raise NotImplementedError("only support 1-d categoricals")
+ assert codes.dtype.name.startswith("int"), codes.dtype.name
+
# write the codes; must be in a block shape
self.ordered = values.ordered
- self.typ = self.get_atom_data(block, kind=codes.dtype.name)
+ self.typ = self.get_atom_data(block.shape, kind=codes.dtype.name)
self.set_data(block.values)
# write the categories
self.meta = "category"
self.metadata = np.array(block.values.categories, copy=False).ravel()
+ assert self.kind == "integer", self.kind
+ assert self.dtype == codes.dtype.name, codes.dtype.name
def get_atom_datetime64(self, block):
return _tables().Int64Col(shape=block.shape[0])
@@ -2553,7 +2560,7 @@ def validate_names(self):
def get_atom_string(self, shape, itemsize):
return _tables().StringCol(itemsize=itemsize)
- def get_atom_data(self, block, kind=None):
+ def get_atom_data(self, shape, kind: str) -> "Col":
return self.get_atom_coltype(kind=kind)()
def get_atom_datetime64(self, block):
| cc @WillAyd how do we annotate "this returns a subclass of Col"? Here i've used `Type["Col"]` but afaik that doesnt include subclasses | https://api.github.com/repos/pandas-dev/pandas/pulls/30074 | 2019-12-05T01:27:17Z | 2019-12-06T00:46:06Z | 2019-12-06T00:46:06Z | 2019-12-06T00:47:28Z |
#29886 - Replace !r for repr() on pandas/io/parses.py | diff --git a/pandas/io/html.py b/pandas/io/html.py
index cc93bba4603bf..3521bad375aa6 100644
--- a/pandas/io/html.py
+++ b/pandas/io/html.py
@@ -102,9 +102,7 @@ def _get_skiprows(skiprows):
return skiprows
elif skiprows is None:
return 0
- raise TypeError(
- f"'{type(skiprows).__name__}' is not a valid type for skipping rows"
- )
+ raise TypeError(f"{type(skiprows).__name__} is not a valid type for skipping rows")
def _read(obj):
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index aeade1d5ed2c2..2d8787d1c4874 100755
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -913,8 +913,8 @@ def _get_options_with_defaults(self, engine):
pass
else:
raise ValueError(
- "The %r option is not supported with the"
- " %r engine" % (argname, engine)
+ f"The {repr(argname)} option is not supported with the"
+ f" {repr(engine)} engine"
)
else:
value = _deprecated_defaults.get(argname, default)
@@ -1079,8 +1079,8 @@ def _clean_options(self, options, engine):
if converters is not None:
if not isinstance(converters, dict):
raise TypeError(
- f"Type converters must be a dict or subclass, "
- f"input was a {repr(type(converters).__name__)}"
+ "Type converters must be a dict or subclass, "
+ f"input was a {type(converters).__name__}"
)
else:
converters = {}
@@ -3608,7 +3608,7 @@ def __init__(self, f, colspecs, delimiter, comment, skiprows=None, infer_nrows=1
if not isinstance(self.colspecs, (tuple, list)):
raise TypeError(
"column specifications must be a list or tuple, "
- "input was a %r" % type(colspecs).__name__
+ f"input was a {type(colspecs).__name__}"
)
for colspec in self.colspecs:
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/30073 | 2019-12-05T01:03:37Z | 2019-12-10T13:06:20Z | 2019-12-10T13:06:20Z | 2019-12-10T13:06:22Z |
Remove legacy scipy compat | diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index a2a40bbf93604..9e436ec4c6c13 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -1248,10 +1248,9 @@ def _pearson(a, b):
return np.corrcoef(a, b)[0, 1]
def _kendall(a, b):
+ # kendallttau returns a tuple of the tau statistic and pvalue
rs = kendalltau(a, b)
- if isinstance(rs, tuple):
- return rs[0]
- return rs
+ return rs[0]
def _spearman(a, b):
return spearmanr(a, b)[0]
| AFAICT from the scipy blame, it has been at least 16 years since scipy.stats.kendalltau returned anything but a tuple | https://api.github.com/repos/pandas-dev/pandas/pulls/30072 | 2019-12-05T00:29:46Z | 2019-12-05T05:55:35Z | 2019-12-05T05:55:35Z | 2019-12-05T16:15:06Z |
STY: fstrings doc/source/conf.py | diff --git a/doc/source/conf.py b/doc/source/conf.py
index b4f719b6e64b2..5f6a6af60e9bf 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -296,12 +296,7 @@
for method in methods:
# ... and each of its public methods
- moved_api_pages.append(
- (
- "{old}.{method}".format(old=old, method=method),
- "{new}.{method}".format(new=new, method=method),
- )
- )
+ moved_api_pages.append((f"{old}.{method}", f"{new}.{method}",))
if pattern is None:
html_additional_pages = {
@@ -309,7 +304,7 @@
}
-header = """\
+header = f"""\
.. currentmodule:: pandas
.. ipython:: python
@@ -323,10 +318,8 @@
pd.options.display.max_rows = 15
import os
- os.chdir(r'{}')
-""".format(
- os.path.dirname(os.path.dirname(__file__))
-)
+ os.chdir(r'{os.path.dirname(os.path.dirname(__file__))}')
+"""
html_context = {
@@ -620,19 +613,18 @@ def linkcode_resolve(domain, info):
lineno = None
if lineno:
- linespec = "#L{:d}-L{:d}".format(lineno, lineno + len(source) - 1)
+ linespec = f"#L{lineno}-L{lineno + len(source) - 1}"
else:
linespec = ""
fn = os.path.relpath(fn, start=os.path.dirname(pandas.__file__))
if "+" in pandas.__version__:
- return "http://github.com/pandas-dev/pandas/blob/master/pandas/{}{}".format(
- fn, linespec
- )
+ return f"http://github.com/pandas-dev/pandas/blob/master/pandas/{fn}{linespec}"
else:
- return "http://github.com/pandas-dev/pandas/blob/v{}/pandas/{}{}".format(
- pandas.__version__, fn, linespec
+ return (
+ f"http://github.com/pandas-dev/pandas/blob/"
+ f"v{pandas.__version__}/pandas/{fn}{linespec}"
)
| - [x] ref #29547
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/30071 | 2019-12-04T22:57:45Z | 2019-12-05T12:57:46Z | 2019-12-05T12:57:46Z | 2019-12-05T13:30:46Z |
CI: troubleshoot codecov | diff --git a/ci/run_tests.sh b/ci/run_tests.sh
index b91cfb3bed8cc..4c5dbabc81950 100755
--- a/ci/run_tests.sh
+++ b/ci/run_tests.sh
@@ -37,7 +37,8 @@ echo $PYTEST_CMD
sh -c "$PYTEST_CMD"
if [[ "$COVERAGE" && $? == 0 && "$TRAVIS_BRANCH" == "master" ]]; then
+ SHA=`git rev-parse HEAD`
echo "uploading coverage"
- echo "bash <(curl -s https://codecov.io/bash) -Z -c -F $TYPE -f $COVERAGE_FNAME"
- bash <(curl -s https://codecov.io/bash) -Z -c -F $TYPE -f $COVERAGE_FNAME
+ echo "bash <(curl -s https://codecov.io/bash) -Z -c -F $TYPE -f $COVERAGE_FNAME -C $SHA"
+ bash <(curl -s https://codecov.io/bash) -Z -c -F $TYPE -f $COVERAGE_FNAME -C `git rev-parse HEAD`
fi
| The results here https://codecov.io/gh/pandas-dev/pandas/tree/master/pandas are 17 days old, the last attempt to re-enable codecov apparently didn't take. Trying again. | https://api.github.com/repos/pandas-dev/pandas/pulls/30070 | 2019-12-04T22:57:36Z | 2019-12-20T05:39:05Z | 2019-12-20T05:39:05Z | 2019-12-20T17:34:43Z |
CI: temp skip BooleanArray pyarrow test | diff --git a/pandas/tests/arrays/test_boolean.py b/pandas/tests/arrays/test_boolean.py
index d9cbf3f5b4172..a13bb8edc8e48 100644
--- a/pandas/tests/arrays/test_boolean.py
+++ b/pandas/tests/arrays/test_boolean.py
@@ -546,6 +546,7 @@ def test_reductions_return_types(dropna, data, all_numeric_reductions):
# result = arr[mask]
+@pytest.mark.skip(reason="broken test")
@td.skip_if_no("pyarrow", min_version="0.15.0")
def test_arrow_array(data):
# protocol added in 0.15.0
| This is a failure from https://github.com/pandas-dev/pandas/pull/29961, sorry. In hindsight I should have updated that PR with master after the CI changes were merged, since I added pyarrow 0.15 to one of the CI builds earlier today exactly to catch those errors .. Sorry about that.
Will merge this quickly to not have CI fail annoyingly, but will do a proper fix (for this and https://github.com/pandas-dev/pandas/issues/29976) tomorrow | https://api.github.com/repos/pandas-dev/pandas/pulls/30069 | 2019-12-04T22:03:30Z | 2019-12-04T22:04:02Z | 2019-12-04T22:04:02Z | 2019-12-04T22:04:27Z |
CLN: simplify pytables create_axes | diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index c56445d6c2b6e..5a3f488ddb544 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -3832,6 +3832,7 @@ def create_axes(
else:
existing_table = None
+ assert self.ndim == 2 # with next check, we must have len(axes) == 1
# currently support on ndim-1 axes
if len(axes) != self.ndim - 1:
raise ValueError(
@@ -3846,63 +3847,58 @@ def create_axes(
if nan_rep is None:
nan_rep = "nan"
- # create axes to index and non_index
- index_axes_map = dict()
- for i, a in enumerate(obj.axes):
+ # We construct the non-index-axis first, since that alters self.info
+ idx = [x for x in [0, 1] if x not in axes][0]
- if i in axes:
- name = obj._AXIS_NAMES[i]
- new_index = _convert_index(name, a, self.encoding, self.errors)
- new_index.axis = i
- index_axes_map[i] = new_index
-
- else:
+ a = obj.axes[idx]
+ # we might be able to change the axes on the appending data if necessary
+ append_axis = list(a)
+ if existing_table is not None:
+ indexer = len(new_non_index_axes) # i.e. 0
+ exist_axis = existing_table.non_index_axes[indexer][1]
+ if not array_equivalent(np.array(append_axis), np.array(exist_axis)):
- # we might be able to change the axes on the appending data if
- # necessary
- append_axis = list(a)
- if existing_table is not None:
- indexer = len(new_non_index_axes)
- exist_axis = existing_table.non_index_axes[indexer][1]
- if not array_equivalent(
- np.array(append_axis), np.array(exist_axis)
- ):
-
- # ahah! -> reindex
- if array_equivalent(
- np.array(sorted(append_axis)), np.array(sorted(exist_axis))
- ):
- append_axis = exist_axis
+ # ahah! -> reindex
+ if array_equivalent(
+ np.array(sorted(append_axis)), np.array(sorted(exist_axis))
+ ):
+ append_axis = exist_axis
- # the non_index_axes info
- info = _get_info(self.info, i)
- info["names"] = list(a.names)
- info["type"] = type(a).__name__
+ # the non_index_axes info
+ info = self.info.setdefault(idx, {})
+ info["names"] = list(a.names)
+ info["type"] = type(a).__name__
- new_non_index_axes.append((i, append_axis))
+ new_non_index_axes.append((idx, append_axis))
- self.non_index_axes = new_non_index_axes
+ # Now we can construct our new index axis
+ idx = axes[0]
+ a = obj.axes[idx]
+ name = obj._AXIS_NAMES[idx]
+ new_index = _convert_index(name, a, self.encoding, self.errors)
+ new_index.axis = idx
- # set axis positions (based on the axes)
- new_index_axes = [index_axes_map[a] for a in axes]
- for j, iax in enumerate(new_index_axes):
- iax.set_pos(j)
- iax.update_info(self.info)
+ # Because we are always 2D, there is only one new_index, so
+ # we know it will have pos=0
+ new_index.set_pos(0)
+ new_index.update_info(self.info)
+ new_index.maybe_set_size(min_itemsize) # check for column conflicts
- j = len(new_index_axes)
+ self.non_index_axes = new_non_index_axes
- # check for column conflicts
- for a in new_index_axes:
- a.maybe_set_size(min_itemsize=min_itemsize)
+ new_index_axes = [new_index]
+ j = len(new_index_axes) # i.e. 1
+ assert j == 1
# reindex by our non_index_axes & compute data_columns
+ assert len(new_non_index_axes) == 1
for a in new_non_index_axes:
obj = _reindex_axis(obj, a[0], a[1])
def get_blk_items(mgr, blocks):
return [mgr.items.take(blk.mgr_locs) for blk in blocks]
- transposed = new_index_axes[0].axis == 1
+ transposed = new_index.axis == 1
# figure out data_columns and get out blocks
block_obj = self.get_object(obj, transposed)._consolidate()
| As mentioned in #30019, with Panel cases gone we can now deduce that `len(axes) == 1` in all cases in `create_axes`. From there we can simplify this method a lot. This PR does most of that; some of it is held back to avoid creating merge conflicts with #30067 (orthogonal) | https://api.github.com/repos/pandas-dev/pandas/pulls/30068 | 2019-12-04T21:43:21Z | 2019-12-05T15:36:05Z | 2019-12-05T15:36:05Z | 2019-12-05T16:04:08Z |
REF: set non_index_axes at the end of create_axes | diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 1d24e15c504f2..36cf5592546b8 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -3662,15 +3662,15 @@ def get_object(self, obj, transposed: bool):
""" return the data for this obj """
return obj
- def validate_data_columns(self, data_columns, min_itemsize):
+ def validate_data_columns(self, data_columns, min_itemsize, non_index_axes):
"""take the input data_columns and min_itemize and create a data
columns spec
"""
- if not len(self.non_index_axes):
+ if not len(non_index_axes):
return []
- axis, axis_labels = self.non_index_axes[0]
+ axis, axis_labels = non_index_axes[0]
info = self.info.get(axis, dict())
if info.get("type") == "MultiIndex" and data_columns:
raise ValueError(
@@ -3829,7 +3829,9 @@ def get_blk_items(mgr, blocks):
blk_items = get_blk_items(block_obj._data, blocks)
if len(new_non_index_axes):
axis, axis_labels = new_non_index_axes[0]
- data_columns = self.validate_data_columns(data_columns, min_itemsize)
+ data_columns = self.validate_data_columns(
+ data_columns, min_itemsize, new_non_index_axes
+ )
if len(data_columns):
mgr = block_obj.reindex(
Index(axis_labels).difference(Index(data_columns)), axis=axis
@@ -3925,6 +3927,7 @@ def get_blk_items(mgr, blocks):
self.data_columns = new_data_columns
self.values_axes = vaxes
self.index_axes = new_index_axes
+ self.non_index_axes = new_non_index_axes
# validate our min_itemsize
self.validate_min_itemsize(min_itemsize)
| Follow-up to #30029 that handles the remaining attribute self.non_index_axes.
cc @WillAyd | https://api.github.com/repos/pandas-dev/pandas/pulls/30067 | 2019-12-04T21:37:23Z | 2019-12-05T19:45:28Z | 2019-12-05T19:45:28Z | 2019-12-05T19:51:57Z |
CI: upload coverage report to Codecov | diff --git a/.github/workflows/database.yml b/.github/workflows/database.yml
index f3ccd78266ba6..b34373b82af1a 100644
--- a/.github/workflows/database.yml
+++ b/.github/workflows/database.yml
@@ -170,3 +170,11 @@ jobs:
- name: Print skipped tests
run: python ci/print_skipped.py
+
+ - name: Upload coverage to Codecov
+ uses: codecov/codecov-action@v1
+ with:
+ files: /tmp/test_coverage.xml
+ flags: unittests
+ name: codecov-pandas
+ fail_ci_if_error: true
| After moving the coverage build from Travis to GitHub Actions #38344, coverage upload was stopped.
Trying to add it back using action provided by codecov. https://github.com/codecov/codecov-action
| https://api.github.com/repos/pandas-dev/pandas/pulls/39822 | 2021-02-15T17:38:42Z | 2021-02-15T23:02:44Z | 2021-02-15T23:02:44Z | 2021-03-18T16:40:49Z |
ENH: Styler builtins: `highlight_between` | diff --git a/doc/source/_static/style/hbetw_axNone.png b/doc/source/_static/style/hbetw_axNone.png
new file mode 100644
index 0000000000000..2918131b40bde
Binary files /dev/null and b/doc/source/_static/style/hbetw_axNone.png differ
diff --git a/doc/source/_static/style/hbetw_basic.png b/doc/source/_static/style/hbetw_basic.png
new file mode 100644
index 0000000000000..1d8e015aec37f
Binary files /dev/null and b/doc/source/_static/style/hbetw_basic.png differ
diff --git a/doc/source/_static/style/hbetw_props.png b/doc/source/_static/style/hbetw_props.png
new file mode 100644
index 0000000000000..56bbe8479d564
Binary files /dev/null and b/doc/source/_static/style/hbetw_props.png differ
diff --git a/doc/source/_static/style/hbetw_seq.png b/doc/source/_static/style/hbetw_seq.png
new file mode 100644
index 0000000000000..0fc3108a7968c
Binary files /dev/null and b/doc/source/_static/style/hbetw_seq.png differ
diff --git a/doc/source/reference/style.rst b/doc/source/reference/style.rst
index 90ec5a2283f1e..3c06bc30c5db9 100644
--- a/doc/source/reference/style.rst
+++ b/doc/source/reference/style.rst
@@ -53,6 +53,7 @@ Builtin styles
Styler.highlight_null
Styler.highlight_max
Styler.highlight_min
+ Styler.highlight_between
Styler.background_gradient
Styler.bar
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 0ec9758477eba..be6c1205810f5 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -206,6 +206,7 @@ Other enhancements
- :meth:`.Styler.background_gradient` now allows the ability to supply a specific gradient map (:issue:`22727`)
- :meth:`.Styler.clear` now clears :attr:`Styler.hidden_index` and :attr:`Styler.hidden_columns` as well (:issue:`40484`)
- Builtin highlighting methods in :class:`Styler` have a more consistent signature and css customisability (:issue:`40242`)
+- :meth:`.Styler.highlight_between` added to list of builtin styling methods (:issue:`39821`)
- :meth:`Series.loc.__getitem__` and :meth:`Series.loc.__setitem__` with :class:`MultiIndex` now raising helpful error message when indexer has too many dimensions (:issue:`35349`)
- :meth:`pandas.read_stata` and :class:`StataReader` support reading data from compressed files.
- Add support for parsing ``ISO 8601``-like timestamps with negative signs to :meth:`pandas.Timedelta` (:issue:`37172`)
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index 7b5347ba2d9a9..271dc766bf441 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -6,6 +6,7 @@
from contextlib import contextmanager
import copy
from functools import partial
+import operator
from typing import (
Any,
Callable,
@@ -21,6 +22,7 @@
FrameOrSeries,
FrameOrSeriesUnion,
IndexLabel,
+ Scalar,
)
from pandas.compat._optional import import_optional_dependency
from pandas.util._decorators import doc
@@ -1352,6 +1354,7 @@ def highlight_null(
--------
Styler.highlight_max: Highlight the maximum with a style.
Styler.highlight_min: Highlight the minimum with a style.
+ Styler.highlight_between: Highlight a defined range with a style.
"""
def f(data: DataFrame, props: str) -> np.ndarray:
@@ -1399,6 +1402,7 @@ def highlight_max(
--------
Styler.highlight_null: Highlight missing values with a style.
Styler.highlight_min: Highlight the minimum with a style.
+ Styler.highlight_between: Highlight a defined range with a style.
"""
def f(data: FrameOrSeries, props: str) -> np.ndarray:
@@ -1446,6 +1450,7 @@ def highlight_min(
--------
Styler.highlight_null: Highlight missing values with a style.
Styler.highlight_max: Highlight the maximum with a style.
+ Styler.highlight_between: Highlight a defined range with a style.
"""
def f(data: FrameOrSeries, props: str) -> np.ndarray:
@@ -1459,6 +1464,157 @@ def f(data: FrameOrSeries, props: str) -> np.ndarray:
f, axis=axis, subset=subset, props=props # type: ignore[arg-type]
)
+ def highlight_between(
+ self,
+ subset: IndexLabel | None = None,
+ color: str = "yellow",
+ axis: Axis | None = 0,
+ left: Scalar | Sequence | None = None,
+ right: Scalar | Sequence | None = None,
+ inclusive: str = "both",
+ props: str | None = None,
+ ) -> Styler:
+ """
+ Highlight a defined range with a style.
+
+ .. versionadded:: 1.3.0
+
+ Parameters
+ ----------
+ subset : IndexSlice, default None
+ A valid slice for ``data`` to limit the style application to.
+ color : str, default 'yellow'
+ Background color to use for highlighting.
+ axis : {0 or 'index', 1 or 'columns', None}, default 0
+ If ``left`` or ``right`` given as sequence, axis along which to apply those
+ boundaries. See examples.
+ left : scalar or datetime-like, or sequence or array-like, default None
+ Left bound for defining the range.
+ right : scalar or datetime-like, or sequence or array-like, default None
+ Right bound for defining the range.
+ inclusive : {'both', 'neither', 'left', 'right'}
+ Identify whether bounds are closed or open.
+ props : str, default None
+ CSS properties to use for highlighting. If ``props`` is given, ``color``
+ is not used.
+
+ Returns
+ -------
+ self : Styler
+
+ See Also
+ --------
+ Styler.highlight_null: Highlight missing values with a style.
+ Styler.highlight_max: Highlight the maximum with a style.
+ Styler.highlight_min: Highlight the minimum with a style.
+
+ Notes
+ -----
+ If ``left`` is ``None`` only the right bound is applied.
+ If ``right`` is ``None`` only the left bound is applied. If both are ``None``
+ all values are highlighted.
+
+ ``axis`` is only needed if ``left`` or ``right`` are provided as a sequence or
+ an array-like object for aligning the shapes. If ``left`` and ``right`` are
+ both scalars then all ``axis`` inputs will give the same result.
+
+ This function only works with compatible ``dtypes``. For example a datetime-like
+ region can only use equivalent datetime-like ``left`` and ``right`` arguments.
+ Use ``subset`` to control regions which have multiple ``dtypes``.
+
+ Examples
+ --------
+ Basic usage
+
+ >>> df = pd.DataFrame({
+ ... 'One': [1.2, 1.6, 1.5],
+ ... 'Two': [2.9, 2.1, 2.5],
+ ... 'Three': [3.1, 3.2, 3.8],
+ ... })
+ >>> df.style.highlight_between(left=2.1, right=2.9)
+
+ .. figure:: ../../_static/style/hbetw_basic.png
+
+ Using a range input sequnce along an ``axis``, in this case setting a ``left``
+ and ``right`` for each column individually
+
+ >>> df.style.highlight_between(left=[1.4, 2.4, 3.4], right=[1.6, 2.6, 3.6],
+ ... axis=1, color="#fffd75")
+
+ .. figure:: ../../_static/style/hbetw_seq.png
+
+ Using ``axis=None`` and providing the ``left`` argument as an array that
+ matches the input DataFrame, with a constant ``right``
+
+ >>> df.style.highlight_between(left=[[2,2,3],[2,2,3],[3,3,3]], right=3.5,
+ ... axis=None, color="#fffd75")
+
+ .. figure:: ../../_static/style/hbetw_axNone.png
+
+ Using ``props`` instead of default background coloring
+
+ >>> df.style.highlight_between(left=1.5, right=3.5,
+ ... props='font-weight:bold;color:#e83e8c')
+
+ .. figure:: ../../_static/style/hbetw_props.png
+ """
+
+ def f(
+ data: FrameOrSeries,
+ props: str,
+ left: Scalar | Sequence | np.ndarray | FrameOrSeries | None = None,
+ right: Scalar | Sequence | np.ndarray | FrameOrSeries | None = None,
+ inclusive: bool | str = True,
+ ) -> np.ndarray:
+ if np.iterable(left) and not isinstance(left, str):
+ left = _validate_apply_axis_arg(
+ left, "left", None, data # type: ignore[arg-type]
+ )
+
+ if np.iterable(right) and not isinstance(right, str):
+ right = _validate_apply_axis_arg(
+ right, "right", None, data # type: ignore[arg-type]
+ )
+
+ # get ops with correct boundary attribution
+ if inclusive == "both":
+ ops = (operator.ge, operator.le)
+ elif inclusive == "neither":
+ ops = (operator.gt, operator.lt)
+ elif inclusive == "left":
+ ops = (operator.ge, operator.lt)
+ elif inclusive == "right":
+ ops = (operator.gt, operator.le)
+ else:
+ raise ValueError(
+ f"'inclusive' values can be 'both', 'left', 'right', or 'neither' "
+ f"got {inclusive}"
+ )
+
+ g_left = (
+ ops[0](data, left)
+ if left is not None
+ else np.full(data.shape, True, dtype=bool)
+ )
+ l_right = (
+ ops[1](data, right)
+ if right is not None
+ else np.full(data.shape, True, dtype=bool)
+ )
+ return np.where(g_left & l_right, props, "")
+
+ if props is None:
+ props = f"background-color: {color};"
+ return self.apply(
+ f, # type: ignore[arg-type]
+ axis=axis,
+ subset=subset,
+ props=props,
+ left=left,
+ right=right,
+ inclusive=inclusive,
+ )
+
@classmethod
def from_custom_template(cls, searchpath, name):
"""
diff --git a/pandas/tests/io/formats/style/test_highlight.py b/pandas/tests/io/formats/style/test_highlight.py
index 8aca3cadff0b4..b8c194f8955ab 100644
--- a/pandas/tests/io/formats/style/test_highlight.py
+++ b/pandas/tests/io/formats/style/test_highlight.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import DataFrame
+from pandas import (
+ DataFrame,
+ IndexSlice,
+)
pytest.importorskip("jinja2")
@@ -70,3 +73,72 @@ def test_highlight_minmax_ext(df, f, kwargs):
df = -df
result = getattr(df.style, f)(**kwargs)._compute().ctx
assert result == expected
+
+
+@pytest.mark.parametrize(
+ "kwargs",
+ [
+ {"left": 0, "right": 1}, # test basic range
+ {"left": 0, "right": 1, "props": "background-color: yellow"}, # test props
+ {"left": -100, "right": 100, "subset": IndexSlice[[0, 1], :]}, # test subset
+ {"left": 0, "subset": IndexSlice[[0, 1], :]}, # test no right
+ {"right": 1}, # test no left
+ {"left": [0, 0, 11], "axis": 0}, # test left as sequence
+ {"left": DataFrame({"A": [0, 0, 11], "B": [1, 1, 11]}), "axis": None}, # axis
+ {"left": 0, "right": [0, 1], "axis": 1}, # test sequence right
+ ],
+)
+def test_highlight_between(styler, kwargs):
+ expected = {
+ (0, 0): [("background-color", "yellow")],
+ (0, 1): [("background-color", "yellow")],
+ }
+ result = styler.highlight_between(**kwargs)._compute().ctx
+ assert result == expected
+
+
+@pytest.mark.parametrize(
+ "arg, map, axis",
+ [
+ ("left", [1, 2], 0), # 0 axis has 3 elements not 2
+ ("left", [1, 2, 3], 1), # 1 axis has 2 elements not 3
+ ("left", np.array([[1, 2], [1, 2]]), None), # df is (2,3) not (2,2)
+ ("right", [1, 2], 0), # same tests as above for 'right' not 'left'
+ ("right", [1, 2, 3], 1), # ..
+ ("right", np.array([[1, 2], [1, 2]]), None), # ..
+ ],
+)
+def test_highlight_between_raises(arg, styler, map, axis):
+ msg = f"supplied '{arg}' is not correct shape"
+ with pytest.raises(ValueError, match=msg):
+ styler.highlight_between(**{arg: map, "axis": axis})._compute()
+
+
+def test_highlight_between_raises2(styler):
+ msg = "values can be 'both', 'left', 'right', or 'neither'"
+ with pytest.raises(ValueError, match=msg):
+ styler.highlight_between(inclusive="badstring")._compute()
+
+ with pytest.raises(ValueError, match=msg):
+ styler.highlight_between(inclusive=1)._compute()
+
+
+@pytest.mark.parametrize(
+ "inclusive, expected",
+ [
+ (
+ "both",
+ {
+ (0, 0): [("background-color", "yellow")],
+ (0, 1): [("background-color", "yellow")],
+ },
+ ),
+ ("neither", {}),
+ ("left", {(0, 0): [("background-color", "yellow")]}),
+ ("right", {(0, 1): [("background-color", "yellow")]}),
+ ],
+)
+def test_highlight_between_inclusive(styler, inclusive, expected):
+ kwargs = {"left": 0, "right": 1, "subset": IndexSlice[[0, 1], :]}
+ result = styler.highlight_between(**kwargs, inclusive=inclusive)._compute()
+ assert result.ctx == expected
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
- [x] update docs for existing highlight functions for consistency
- [x] add a new `props` argument to existing highlight functions.
Will add tests if approved:
Could wrap both methods into one as well, but probably easier api if two?


| https://api.github.com/repos/pandas-dev/pandas/pulls/39821 | 2021-02-15T16:56:49Z | 2021-04-13T14:16:42Z | 2021-04-13T14:16:42Z | 2021-04-13T14:32:38Z |
REF: call ensure_wrapped_if_datetimelike before the array arithmetic_op | diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py
index c9db995319cdf..6e4aa1a5efacf 100644
--- a/pandas/core/arrays/numpy_.py
+++ b/pandas/core/arrays/numpy_.py
@@ -23,6 +23,7 @@
)
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays._mixins import NDArrayBackedExtensionArray
+from pandas.core.construction import ensure_wrapped_if_datetimelike
from pandas.core.strings.object_array import ObjectStringArrayMixin
@@ -395,6 +396,7 @@ def _cmp_method(self, other, op):
other = other._ndarray
pd_op = ops.get_array_op(op)
+ other = ensure_wrapped_if_datetimelike(other)
with np.errstate(all="ignore"):
result = pd_op(self._ndarray, other)
diff --git a/pandas/core/ops/array_ops.py b/pandas/core/ops/array_ops.py
index ba9da8d648597..387d8b463b8b4 100644
--- a/pandas/core/ops/array_ops.py
+++ b/pandas/core/ops/array_ops.py
@@ -195,20 +195,17 @@ def arithmetic_op(left: ArrayLike, right: Any, op):
Or a 2-tuple of these in the case of divmod or rdivmod.
"""
- # NB: We assume that extract_array has already been called
- # on `left` and `right`.
+ # NB: We assume that extract_array and ensure_wrapped_if_datetimelike
+ # has already been called on `left` and `right`.
# We need to special-case datetime64/timedelta64 dtypes (e.g. because numpy
# casts integer dtypes to timedelta64 when operating with timedelta64 - GH#22390)
- lvalues = ensure_wrapped_if_datetimelike(left)
- rvalues = ensure_wrapped_if_datetimelike(right)
- rvalues = _maybe_upcast_for_op(rvalues, lvalues.shape)
+ right = _maybe_upcast_for_op(right, left.shape)
- if should_extension_dispatch(lvalues, rvalues) or isinstance(rvalues, Timedelta):
+ if should_extension_dispatch(left, right) or isinstance(right, Timedelta):
# Timedelta is included because numexpr will fail on it, see GH#31457
- res_values = op(lvalues, rvalues)
-
+ res_values = op(left, right)
else:
- res_values = _na_arithmetic_op(lvalues, rvalues, op)
+ res_values = _na_arithmetic_op(left, right, op)
return res_values
diff --git a/pandas/core/series.py b/pandas/core/series.py
index e19d521bda3df..85c30096b1001 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -100,6 +100,7 @@
import pandas.core.common as com
from pandas.core.construction import (
create_series_with_explicit_dtype,
+ ensure_wrapped_if_datetimelike,
extract_array,
is_empty_data,
sanitize_array,
@@ -2872,7 +2873,7 @@ def _binop(self, other: Series, func, level=None, fill_value=None):
if not self.index.equals(other.index):
this, other = self.align(other, level=level, join="outer", copy=False)
- this_vals, other_vals = ops.fill_binop(this.values, other.values, fill_value)
+ this_vals, other_vals = ops.fill_binop(this._values, other._values, fill_value)
with np.errstate(all="ignore"):
result = func(this_vals, other_vals)
@@ -5313,6 +5314,7 @@ def _arith_method(self, other, op):
lvalues = self._values
rvalues = extract_array(other, extract_numpy=True, extract_range=True)
+ rvalues = ensure_wrapped_if_datetimelike(rvalues)
with np.errstate(all="ignore"):
result = ops.arithmetic_op(lvalues, rvalues, op)
| ~This is on top of https://github.com/pandas-dev/pandas/pull/39772, so only the last commit needs to be looked at for now: https://github.com/pandas-dev/pandas/pull/39820/commits/bd50388e019c61559c310638186aeea57d2d2d3e~
The actual goal here is to have a version of [`array_ops.py::arithmetic_op`](https://github.com/pandas-dev/pandas/blob/9f792cd90373177bffa0e9f85a14d5d5b30fb289/pandas/core/ops/array_ops.py#L159-L191) that does *not* call `ensure_wrapped_if_datetimelike` on its arrays. Reason: when performing ops column-wise, this becomes unnecessary overhead, and so the goal is to ensure this on a higher level, before calling the `array_op`.
So the experiment in this PR is to actually remove `ensure_wrapped_if_datetimelike` from `arithmetic_op`, and then add it in the places that will call `arithmetic_op`, to see how much changes this needs. This would ensure that we can keep a single shared `arithmetic_op` for use by both ArrayManager and BlockManager. The alternative would be to make a variant of `arithmetic_op` without the `ensure_wrapped_if_datetimelike`. That would require fewer code changes, but would give some duplication around `arithmetic_op` content (but it's not that it is a long function). Thoughts on which approach to prefer?
cc @jbrockmendel | https://api.github.com/repos/pandas-dev/pandas/pulls/39820 | 2021-02-15T15:21:36Z | 2021-04-22T22:16:51Z | 2021-04-22T22:16:51Z | 2021-04-22T22:34:09Z |
REF: share DTBlock/TDBlock _maybe_coerce_values | diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 8ba6018e743bb..4ecd47496f109 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -32,8 +32,6 @@
soft_convert_objects,
)
from pandas.core.dtypes.common import (
- DT64NS_DTYPE,
- TD64NS_DTYPE,
is_categorical_dtype,
is_datetime64_dtype,
is_datetime64tz_dtype,
@@ -144,7 +142,8 @@ def __init__(self, values, placement, ndim: int):
f"placement implies {len(self.mgr_locs)}"
)
- def _maybe_coerce_values(self, values):
+ @classmethod
+ def _maybe_coerce_values(cls, values):
"""
Ensure we have correctly-typed values.
@@ -1543,7 +1542,8 @@ def putmask(self, mask, new) -> List[Block]:
new_values[mask] = new
return [self.make_block(values=new_values)]
- def _maybe_coerce_values(self, values):
+ @classmethod
+ def _maybe_coerce_values(cls, values):
"""
Unbox to an extension array.
@@ -1934,13 +1934,39 @@ def to_native_types(
class DatetimeLikeBlockMixin(HybridMixin, Block):
"""Mixin class for DatetimeBlock, DatetimeTZBlock, and TimedeltaBlock."""
- @property
- def _holder(self):
- return DatetimeArray
+ _dtype: np.dtype
+ _holder: Type[Union[DatetimeArray, TimedeltaArray]]
- @property
- def fill_value(self):
- return np.datetime64("NaT", "ns")
+ @classmethod
+ def _maybe_coerce_values(cls, values):
+ """
+ Input validation for values passed to __init__. Ensure that
+ we have nanosecond datetime64/timedelta64, coercing if necessary.
+
+ Parameters
+ ----------
+ values : array-like
+ Must be convertible to datetime64/timedelta64
+
+ Returns
+ -------
+ values : ndarray[datetime64ns/timedelta64ns]
+
+ Overridden by DatetimeTZBlock.
+ """
+ if values.dtype != cls._dtype:
+ # non-nano we will convert to nano
+ if values.dtype.kind != cls._dtype.kind:
+ # caller is responsible for ensuring td64/dt64 dtype
+ raise TypeError(values.dtype) # pragma: no cover
+
+ values = cls._holder._from_sequence(values)._data
+
+ if isinstance(values, cls._holder):
+ values = values._data
+
+ assert isinstance(values, np.ndarray), type(values)
+ return values
def get_values(self, dtype: Optional[DtypeObj] = None) -> np.ndarray:
"""
@@ -2036,36 +2062,14 @@ def where(self, other, cond, errors="raise", axis: int = 0) -> List[Block]:
class DatetimeBlock(DatetimeLikeBlockMixin):
__slots__ = ()
is_datetime = True
+ fill_value = np.datetime64("NaT", "ns")
+ _dtype = fill_value.dtype
+ _holder = DatetimeArray
@property
def _can_hold_na(self):
return True
- def _maybe_coerce_values(self, values):
- """
- Input validation for values passed to __init__. Ensure that
- we have datetime64ns, coercing if necessary.
-
- Parameters
- ----------
- values : array-like
- Must be convertible to datetime64
-
- Returns
- -------
- values : ndarray[datetime64ns]
-
- Overridden by DatetimeTZBlock.
- """
- if values.dtype != DT64NS_DTYPE:
- values = conversion.ensure_datetime64ns(values)
-
- if isinstance(values, DatetimeArray):
- values = values._data
-
- assert isinstance(values, np.ndarray), type(values)
- return values
-
def set_inplace(self, locs, values):
"""
See Block.set.__doc__
@@ -2084,6 +2088,8 @@ class DatetimeTZBlock(ExtensionBlock, DatetimeBlock):
is_datetimetz = True
is_extension = True
+ _holder = DatetimeArray
+
internal_values = Block.internal_values
_can_hold_element = DatetimeBlock._can_hold_element
to_native_types = DatetimeBlock.to_native_types
@@ -2094,11 +2100,8 @@ class DatetimeTZBlock(ExtensionBlock, DatetimeBlock):
array_values = ExtensionBlock.array_values
- @property
- def _holder(self):
- return DatetimeArray
-
- def _maybe_coerce_values(self, values):
+ @classmethod
+ def _maybe_coerce_values(cls, values):
"""
Input validation for values passed to __init__. Ensure that
we have datetime64TZ, coercing if necessary.
@@ -2112,8 +2115,8 @@ def _maybe_coerce_values(self, values):
-------
values : DatetimeArray
"""
- if not isinstance(values, self._holder):
- values = self._holder(values)
+ if not isinstance(values, cls._holder):
+ values = cls._holder(values)
if values.tz is None:
raise ValueError("cannot create a DatetimeTZBlock without a tz")
@@ -2206,24 +2209,9 @@ class TimeDeltaBlock(DatetimeLikeBlockMixin):
is_timedelta = True
_can_hold_na = True
is_numeric = False
+ _holder = TimedeltaArray
fill_value = np.timedelta64("NaT", "ns")
-
- def _maybe_coerce_values(self, values):
- if values.dtype != TD64NS_DTYPE:
- # non-nano we will convert to nano
- if values.dtype.kind != "m":
- # caller is responsible for ensuring timedelta64 dtype
- raise TypeError(values.dtype) # pragma: no cover
-
- values = TimedeltaArray._from_sequence(values)._data
- if isinstance(values, TimedeltaArray):
- values = values._data
- assert isinstance(values, np.ndarray), type(values)
- return values
-
- @property
- def _holder(self):
- return TimedeltaArray
+ _dtype = fill_value.dtype
def fillna(
self, value, limit=None, inplace: bool = False, downcast=None
@@ -2245,7 +2233,8 @@ class ObjectBlock(Block):
is_object = True
_can_hold_na = True
- def _maybe_coerce_values(self, values):
+ @classmethod
+ def _maybe_coerce_values(cls, values):
if issubclass(values.dtype.type, str):
values = np.array(values, dtype=object)
return values
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39815 | 2021-02-15T02:48:00Z | 2021-02-15T22:46:23Z | 2021-02-15T22:46:23Z | 2021-02-15T22:50:11Z |
REF: implement HybridBlock | diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 06bf2e5d7b18e..b3dce41514ed9 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -1935,64 +1935,59 @@ def to_native_types(
return self.make_block(res)
-class DatetimeLikeBlockMixin(HybridMixin, Block):
- """Mixin class for DatetimeBlock, DatetimeTZBlock, and TimedeltaBlock."""
-
- _dtype: np.dtype
- _holder: Type[Union[DatetimeArray, TimedeltaArray]]
-
- @classmethod
- def _maybe_coerce_values(cls, values):
- """
- Input validation for values passed to __init__. Ensure that
- we have nanosecond datetime64/timedelta64, coercing if necessary.
-
- Parameters
- ----------
- values : array-like
- Must be convertible to datetime64/timedelta64
-
- Returns
- -------
- values : ndarray[datetime64ns/timedelta64ns]
-
- Overridden by DatetimeTZBlock.
- """
- if values.dtype != cls._dtype:
- # non-nano we will convert to nano
- if values.dtype.kind != cls._dtype.kind:
- # caller is responsible for ensuring td64/dt64 dtype
- raise TypeError(values.dtype) # pragma: no cover
-
- values = cls._holder._from_sequence(values)._data
-
- if isinstance(values, cls._holder):
- values = values._data
+class NDArrayBackedExtensionBlock(HybridMixin, Block):
+ """
+ Block backed by an NDArrayBackedExtensionArray
+ """
- assert isinstance(values, np.ndarray), type(values)
- return values
+ def internal_values(self):
+ # Override to return DatetimeArray and TimedeltaArray
+ return self.array_values()
def get_values(self, dtype: Optional[DtypeObj] = None) -> np.ndarray:
"""
return object dtype as boxed values, such as Timestamps/Timedelta
"""
+ values = self.array_values()
if is_object_dtype(dtype):
# DTA/TDA constructor and astype can handle 2D
- return self._holder(self.values).astype(object)
- return self.values
-
- def internal_values(self):
- # Override to return DatetimeArray and TimedeltaArray
- return self.array_values()
-
- def array_values(self):
- return self._holder._simple_new(self.values)
+ values = values.astype(object)
+ # TODO(EA2D): reshape not needed with 2D EAs
+ return np.asarray(values).reshape(self.shape)
def iget(self, key):
# GH#31649 we need to wrap scalars in Timestamp/Timedelta
# TODO(EA2D): this can be removed if we ever have 2D EA
return self.array_values().reshape(self.shape)[key]
+ def putmask(self, mask, new) -> List[Block]:
+ mask = extract_bool_array(mask)
+
+ if not self._can_hold_element(new):
+ return self.astype(object).putmask(mask, new)
+
+ # TODO(EA2D): reshape unnecessary with 2D EAs
+ arr = self.array_values().reshape(self.shape)
+ arr = cast("NDArrayBackedExtensionArray", arr)
+ arr.T.putmask(mask, new)
+ return [self]
+
+ def where(self, other, cond, errors="raise", axis: int = 0) -> List[Block]:
+ # TODO(EA2D): reshape unnecessary with 2D EAs
+ arr = self.array_values().reshape(self.shape)
+
+ cond = extract_bool_array(cond)
+
+ try:
+ res_values = arr.T.where(cond, other).T
+ except (ValueError, TypeError):
+ return super().where(other, cond, errors=errors, axis=axis)
+
+ # TODO(EA2D): reshape not needed with 2D EAs
+ res_values = res_values.reshape(self.values.shape)
+ nb = self.make_block_same_class(res_values)
+ return [nb]
+
def diff(self, n: int, axis: int = 0) -> List[Block]:
"""
1st discrete difference.
@@ -2017,50 +2012,61 @@ def diff(self, n: int, axis: int = 0) -> List[Block]:
values = self.array_values().reshape(self.shape)
new_values = values - values.shift(n, axis=axis)
- return [
- TimeDeltaBlock(new_values, placement=self.mgr_locs.indexer, ndim=self.ndim)
- ]
+ return [self.make_block(new_values)]
def shift(self, periods: int, axis: int = 0, fill_value: Any = None) -> List[Block]:
# TODO(EA2D) this is unnecessary if these blocks are backed by 2D EAs
- values = self.array_values()
+ values = self.array_values().reshape(self.shape)
new_values = values.shift(periods, fill_value=fill_value, axis=axis)
return [self.make_block_same_class(new_values)]
- def to_native_types(self, na_rep="NaT", **kwargs):
- """ convert to our native types format """
- arr = self.array_values()
- result = arr._format_native_types(na_rep=na_rep, **kwargs)
- return self.make_block(result)
+class DatetimeLikeBlockMixin(NDArrayBackedExtensionBlock):
+ """Mixin class for DatetimeBlock, DatetimeTZBlock, and TimedeltaBlock."""
- def putmask(self, mask, new) -> List[Block]:
- mask = extract_bool_array(mask)
+ _dtype: np.dtype
+ _holder: Type[Union[DatetimeArray, TimedeltaArray]]
- if not self._can_hold_element(new):
- return self.astype(object).putmask(mask, new)
+ @classmethod
+ def _maybe_coerce_values(cls, values):
+ """
+ Input validation for values passed to __init__. Ensure that
+ we have nanosecond datetime64/timedelta64, coercing if necessary.
- # TODO(EA2D): reshape unnecessary with 2D EAs
- arr = self.array_values().reshape(self.shape)
- arr = cast("NDArrayBackedExtensionArray", arr)
- arr.T.putmask(mask, new)
- return [self]
+ Parameters
+ ----------
+ values : array-like
+ Must be convertible to datetime64/timedelta64
- def where(self, other, cond, errors="raise", axis: int = 0) -> List[Block]:
- # TODO(EA2D): reshape unnecessary with 2D EAs
- arr = self.array_values().reshape(self.shape)
+ Returns
+ -------
+ values : ndarray[datetime64ns/timedelta64ns]
- cond = extract_bool_array(cond)
+ Overridden by DatetimeTZBlock.
+ """
+ if values.dtype != cls._dtype:
+ # non-nano we will convert to nano
+ if values.dtype.kind != cls._dtype.kind:
+ # caller is responsible for ensuring td64/dt64 dtype
+ raise TypeError(values.dtype) # pragma: no cover
- try:
- res_values = arr.T.where(cond, other).T
- except (ValueError, TypeError):
- return super().where(other, cond, errors=errors, axis=axis)
+ values = cls._holder._from_sequence(values)._data
- # TODO(EA2D): reshape not needed with 2D EAs
- res_values = res_values.reshape(self.values.shape)
- nb = self.make_block_same_class(res_values)
- return [nb]
+ if isinstance(values, cls._holder):
+ values = values._data
+
+ assert isinstance(values, np.ndarray), type(values)
+ return values
+
+ def array_values(self):
+ return self._holder._simple_new(self.values)
+
+ def to_native_types(self, na_rep="NaT", **kwargs):
+ """ convert to our native types format """
+ arr = self.array_values()
+
+ result = arr._format_native_types(na_rep=na_rep, **kwargs)
+ return self.make_block(result)
class DatetimeBlock(DatetimeLikeBlockMixin):
@@ -2133,37 +2139,6 @@ def is_view(self) -> bool:
# check the ndarray values of the DatetimeIndex values
return self.values._data.base is not None
- def get_values(self, dtype: Optional[DtypeObj] = None) -> np.ndarray:
- """
- Returns an ndarray of values.
-
- Parameters
- ----------
- dtype : np.dtype
- Only `object`-like dtypes are respected here (not sure
- why).
-
- Returns
- -------
- values : ndarray
- When ``dtype=object``, then and object-dtype ndarray of
- boxed values is returned. Otherwise, an M8[ns] ndarray
- is returned.
-
- DatetimeArray is always 1-d. ``get_values`` will reshape
- the return value to be the same dimensionality as the
- block.
- """
- values = self.values
- if is_object_dtype(dtype):
- values = values.astype(object)
-
- # TODO(EA2D): reshape unnecessary with 2D EAs
- # Ensure that our shape is correct for DataFrame.
- # ExtensionArrays are always 1-D, even in a DataFrame when
- # the analogous NumPy-backed column would be a 2-D ndarray.
- return np.asarray(values).reshape(self.shape)
-
def external_values(self):
# NB: this is different from np.asarray(self.values), since that
# return an object-dtype ndarray of Timestamps.
| Methods that would work with any NDArrayBackedExtensionArray, not just DTA/TDA. Written to facilitate experimenting with Blocks backed by 2D EAs. | https://api.github.com/repos/pandas-dev/pandas/pulls/39814 | 2021-02-14T23:39:53Z | 2021-02-16T16:59:12Z | 2021-02-16T16:59:12Z | 2021-02-16T17:45:41Z |
TYP: typing refactor mypy fix | diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index 735fb345363c7..54dacd2d639a6 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -158,13 +158,12 @@ def __init__(
uuid_len: int = 5,
):
# validate ordered args
- if not isinstance(data, (pd.Series, pd.DataFrame)):
- raise TypeError("``data`` must be a Series or DataFrame")
- if data.ndim == 1:
+ if isinstance(data, pd.Series):
data = data.to_frame()
+ if not isinstance(data, DataFrame):
+ raise TypeError("``data`` must be a Series or DataFrame")
if not data.index.is_unique or not data.columns.is_unique:
raise ValueError("style is not supported for non-unique indices.")
- assert isinstance(data, DataFrame)
self.data: DataFrame = data
self.index: pd.Index = data.index
self.columns: pd.Index = data.columns
| `pandas/io/formats/style.py:168: error: Incompatible types in assignment (expression has type "Union[DataFrame, Series]", variable has type "DataFrame") [assignment]`
refactor to remove the `assert` statement otherwise needed to solve the above `mypy` error. | https://api.github.com/repos/pandas-dev/pandas/pulls/39812 | 2021-02-14T21:57:39Z | 2021-02-15T17:17:44Z | 2021-02-15T17:17:44Z | 2021-02-16T18:24:35Z |
REF: Dispatch TimedeltaBlock.fillna to TimedeltaArray | diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 8ba6018e743bb..ff0c5380468f5 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -39,7 +39,6 @@
is_datetime64tz_dtype,
is_dtype_equal,
is_extension_array_dtype,
- is_integer,
is_list_like,
is_object_dtype,
is_sparse,
@@ -442,8 +441,7 @@ def fillna(
if self._can_hold_element(value):
nb = self if inplace else self.copy()
putmask_inplace(nb.values, mask, value)
- # TODO: should be nb._maybe_downcast?
- return self._maybe_downcast([nb], downcast)
+ return nb._maybe_downcast([nb], downcast)
if noop:
# we can't process the value, but nothing to do
@@ -2160,10 +2158,8 @@ def get_values(self, dtype: Optional[DtypeObj] = None) -> np.ndarray:
def external_values(self):
# NB: this is different from np.asarray(self.values), since that
# return an object-dtype ndarray of Timestamps.
- if self.is_datetimetz:
- # avoid FutureWarning in .astype in casting from dt64t to dt64
- return self.values._data
- return np.asarray(self.values.astype("datetime64[ns]", copy=False))
+ # avoid FutureWarning in .astype in casting from dt64t to dt64
+ return self.values._data
def fillna(
self, value, limit=None, inplace: bool = False, downcast=None
@@ -2228,16 +2224,10 @@ def _holder(self):
def fillna(
self, value, limit=None, inplace: bool = False, downcast=None
) -> List[Block]:
- # TODO(EA2D): if we operated on array_values, TDA.fillna would handle
- # raising here.
- if is_integer(value):
- # Deprecation GH#24694, GH#19233
- raise TypeError(
- "Passing integers to fillna for timedelta64[ns] dtype is no "
- "longer supported. To obtain the old behavior, pass "
- "`pd.Timedelta(seconds=n)` instead."
- )
- return super().fillna(value, limit=limit, inplace=inplace, downcast=downcast)
+ values = self.array_values()
+ values = values if inplace else values.copy()
+ new_values = values.fillna(value=value, limit=limit)
+ return [self.make_block_same_class(values=new_values)]
class ObjectBlock(Block):
diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py
index 0bcb37d4880a6..7e33b766a1413 100644
--- a/pandas/tests/series/methods/test_fillna.py
+++ b/pandas/tests/series/methods/test_fillna.py
@@ -204,8 +204,9 @@ def test_timedelta_fillna(self, frame_or_series):
expected = frame_or_series(expected)
tm.assert_equal(result, expected)
- # interpreted as seconds, deprecated
- with pytest.raises(TypeError, match="Passing integers to fillna"):
+ # interpreted as seconds, no longer supported
+ msg = "value should be a 'Timedelta', 'NaT', or array of those. Got 'int'"
+ with pytest.raises(TypeError, match=msg):
obj.fillna(1)
result = obj.fillna(Timedelta(seconds=1))
| https://api.github.com/repos/pandas-dev/pandas/pulls/39811 | 2021-02-14T19:39:04Z | 2021-02-15T22:15:23Z | 2021-02-15T22:15:23Z | 2021-02-15T22:38:42Z | |
REF: put Block replace methods together | diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 8ba6018e743bb..66d7fcb13e234 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -722,6 +722,9 @@ def copy(self, deep: bool = True):
values = values.copy()
return self.make_block_same_class(values, ndim=self.ndim)
+ # ---------------------------------------------------------------------
+ # Replace
+
def replace(
self,
to_replace,
@@ -872,6 +875,57 @@ def _replace_list(
rb = new_rb
return rb
+ def _replace_coerce(
+ self,
+ to_replace,
+ value,
+ mask: np.ndarray,
+ inplace: bool = True,
+ regex: bool = False,
+ ) -> List[Block]:
+ """
+ Replace value corresponding to the given boolean array with another
+ value.
+
+ Parameters
+ ----------
+ to_replace : object or pattern
+ Scalar to replace or regular expression to match.
+ value : object
+ Replacement object.
+ mask : np.ndarray[bool]
+ True indicate corresponding element is ignored.
+ inplace : bool, default True
+ Perform inplace modification.
+ regex : bool, default False
+ If true, perform regular expression substitution.
+
+ Returns
+ -------
+ List[Block]
+ """
+ if mask.any():
+ if not regex:
+ nb = self.coerce_to_target_dtype(value)
+ if nb is self and not inplace:
+ nb = nb.copy()
+ putmask_inplace(nb.values, mask, value)
+ return [nb]
+ else:
+ regex = should_use_regex(regex, to_replace)
+ if regex:
+ return self._replace_regex(
+ to_replace,
+ value,
+ inplace=inplace,
+ convert=False,
+ mask=mask,
+ )
+ return self.replace(to_replace, value, inplace=inplace, regex=False)
+ return [self]
+
+ # ---------------------------------------------------------------------
+
def setitem(self, indexer, value):
"""
Attempt self.values[indexer] = value, possibly creating a new array.
@@ -1402,55 +1456,6 @@ def quantile(
return make_block(result, placement=self.mgr_locs, ndim=2)
- def _replace_coerce(
- self,
- to_replace,
- value,
- mask: np.ndarray,
- inplace: bool = True,
- regex: bool = False,
- ) -> List[Block]:
- """
- Replace value corresponding to the given boolean array with another
- value.
-
- Parameters
- ----------
- to_replace : object or pattern
- Scalar to replace or regular expression to match.
- value : object
- Replacement object.
- mask : np.ndarray[bool]
- True indicate corresponding element is ignored.
- inplace : bool, default True
- Perform inplace modification.
- regex : bool, default False
- If true, perform regular expression substitution.
-
- Returns
- -------
- List[Block]
- """
- if mask.any():
- if not regex:
- nb = self.coerce_to_target_dtype(value)
- if nb is self and not inplace:
- nb = nb.copy()
- putmask_inplace(nb.values, mask, value)
- return [nb]
- else:
- regex = should_use_regex(regex, to_replace)
- if regex:
- return self._replace_regex(
- to_replace,
- value,
- inplace=inplace,
- convert=False,
- mask=mask,
- )
- return self.replace(to_replace, value, inplace=inplace, regex=False)
- return [self]
-
class ExtensionBlock(Block):
"""
| pure cut/paste | https://api.github.com/repos/pandas-dev/pandas/pulls/39810 | 2021-02-14T16:42:28Z | 2021-02-15T22:17:55Z | 2021-02-15T22:17:55Z | 2021-02-15T22:37:47Z |
BUG: add `col<k>` class identifier to blank index name row cells | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 799bc88ffff4e..bbc36ad58773c 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -460,6 +460,7 @@ Other
- Bug in :func:`pandas.testing.assert_series_equal`, :func:`pandas.testing.assert_frame_equal`, :func:`pandas.testing.assert_index_equal` and :func:`pandas.testing.assert_extension_array_equal` incorrectly raising when an attribute has an unrecognized NA type (:issue:`39461`)
- Bug in :class:`Styler` where ``subset`` arg in methods raised an error for some valid multiindex slices (:issue:`33562`)
- :class:`Styler` rendered HTML output minor alterations to support w3 good code standard (:issue:`39626`)
+- Bug in :class:`Styler` where rendered HTML was missing a column class identifier for certain header cells (:issue:`39716`)
- Bug in :meth:`DataFrame.equals`, :meth:`Series.equals`, :meth:`Index.equals` with object-dtype containing ``np.datetime64("NaT")`` or ``np.timedelta64("NaT")`` (:issue:`39650`)
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index 735fb345363c7..d84d1481227c3 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -474,8 +474,15 @@ def _translate(self):
)
index_header_row.extend(
- [{"type": "th", "value": BLANK_VALUE, "class": " ".join([BLANK_CLASS])}]
- * (len(clabels[0]) - len(hidden_columns))
+ [
+ {
+ "type": "th",
+ "value": BLANK_VALUE,
+ "class": " ".join([BLANK_CLASS, f"col{c}"]),
+ }
+ for c in range(len(clabels[0]))
+ if c not in hidden_columns
+ ]
)
head.append(index_header_row)
diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py
index a154e51f68dba..b8df18d593667 100644
--- a/pandas/tests/io/formats/test_style.py
+++ b/pandas/tests/io/formats/test_style.py
@@ -254,8 +254,8 @@ def test_index_name(self):
],
[
{"class": "index_name level0", "type": "th", "value": "A"},
- {"class": "blank", "type": "th", "value": ""},
- {"class": "blank", "type": "th", "value": ""},
+ {"class": "blank col0", "type": "th", "value": ""},
+ {"class": "blank col1", "type": "th", "value": ""},
],
]
@@ -293,7 +293,7 @@ def test_multiindex_name(self):
[
{"class": "index_name level0", "type": "th", "value": "A"},
{"class": "index_name level1", "type": "th", "value": "B"},
- {"class": "blank", "type": "th", "value": ""},
+ {"class": "blank col0", "type": "th", "value": ""},
],
]
@@ -1537,7 +1537,7 @@ def test_mi_sparse_index_names(self):
expected = [
{"class": "index_name level0", "value": "idx_level_0", "type": "th"},
{"class": "index_name level1", "value": "idx_level_1", "type": "th"},
- {"class": "blank", "value": "", "type": "th"},
+ {"class": "blank col0", "value": "", "type": "th"},
]
assert head == expected
| - [x] closes #39716
- [x] tests passed
- [x] linting and typing checks | https://api.github.com/repos/pandas-dev/pandas/pulls/39807 | 2021-02-14T13:09:25Z | 2021-02-17T00:16:18Z | 2021-02-17T00:16:18Z | 2021-02-17T07:04:44Z |
DOC: update cheatsheet | diff --git a/doc/cheatsheet/Pandas_Cheat_Sheet.pdf b/doc/cheatsheet/Pandas_Cheat_Sheet.pdf
index fb71f869ba22f..3582e0c0dabf9 100644
Binary files a/doc/cheatsheet/Pandas_Cheat_Sheet.pdf and b/doc/cheatsheet/Pandas_Cheat_Sheet.pdf differ
diff --git a/doc/cheatsheet/Pandas_Cheat_Sheet.pptx b/doc/cheatsheet/Pandas_Cheat_Sheet.pptx
index fd3d699d09f7b..746f508516964 100644
Binary files a/doc/cheatsheet/Pandas_Cheat_Sheet.pptx and b/doc/cheatsheet/Pandas_Cheat_Sheet.pptx differ
| - [x] closes #39724
- [x] tests added / passed (not required)
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them (not required)
- [x] whatsnew entry (not required)
#### Major changes
1) **Replaced Heading "Data Wrangling ..." with section "General"**
- I found it useful to have the hyperlinks to pandas api reference and user guide included
- Also, all the time time when you work with pandas you need other packages (matplotlib etc.). That's why added hyperlinks for them as well
- There is some place left for other useful links!
2) **Replaces explanatory section "Tidy data" with section "Display & Visualize data"**
- Cheat sheets are for users who already have basic knowledge. So this explanation of Tidy Data is of no use here
- Displaying and visualizing data is one of the main tasks. So this section should be included in the cheat sheet
- On the previous cheat sheet there also was a section "Plotting". But it was very small at the end of the second page.
3) **Added section "Apply Funtions"** (bottom of second page)
- There are many ways to apply functions and I always find it confusing to remember them. So I added them here with a short description
- However, if you have a better suggestion for this section, it can be interchanged
4) **Refractor section "Subset Observation"**
- This section was pretty confusing in styling and layout before. E.g. there where multiple places where you can find the df.loc[] and df.iloc [] functions.
- I reordered this section
- I added df.iloc[row_ind, column_ind] and df.loc[row_ind, column_ind]
Let me know what you think about it and make suggestions.
Oli | https://api.github.com/repos/pandas-dev/pandas/pulls/39806 | 2021-02-14T11:56:43Z | 2021-03-29T15:24:01Z | 2021-03-29T15:24:00Z | 2021-08-31T21:46:02Z |
TST: fixturize indexing intervalindex tests | diff --git a/pandas/conftest.py b/pandas/conftest.py
index bc455092ebe86..79204c8896854 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -1565,6 +1565,14 @@ def indexer_si(request):
return request.param
+@pytest.fixture(params=[tm.setitem, tm.loc])
+def indexer_sl(request):
+ """
+ Parametrize over __setitem__, loc.__setitem__
+ """
+ return request.param
+
+
@pytest.fixture
def using_array_manager(request):
"""
diff --git a/pandas/tests/indexing/interval/test_interval.py b/pandas/tests/indexing/interval/test_interval.py
index f4e7296598d54..95f5115a8c28b 100644
--- a/pandas/tests/indexing/interval/test_interval.py
+++ b/pandas/tests/indexing/interval/test_interval.py
@@ -7,87 +7,83 @@
class TestIntervalIndex:
- def setup_method(self, method):
- self.s = Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6)))
+ @pytest.fixture
+ def series_with_interval_index(self):
+ return Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6)))
- def test_getitem_with_scalar(self):
+ def test_getitem_with_scalar(self, series_with_interval_index, indexer_sl):
- s = self.s
+ ser = series_with_interval_index.copy()
- expected = s.iloc[:3]
- tm.assert_series_equal(expected, s[:3])
- tm.assert_series_equal(expected, s[:2.5])
- tm.assert_series_equal(expected, s[0.1:2.5])
+ expected = ser.iloc[:3]
+ tm.assert_series_equal(expected, indexer_sl(ser)[:3])
+ tm.assert_series_equal(expected, indexer_sl(ser)[:2.5])
+ tm.assert_series_equal(expected, indexer_sl(ser)[0.1:2.5])
+ if indexer_sl is tm.loc:
+ tm.assert_series_equal(expected, ser.loc[-1:3])
- expected = s.iloc[1:4]
- tm.assert_series_equal(expected, s[[1.5, 2.5, 3.5]])
- tm.assert_series_equal(expected, s[[2, 3, 4]])
- tm.assert_series_equal(expected, s[[1.5, 3, 4]])
+ expected = ser.iloc[1:4]
+ tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 2.5, 3.5]])
+ tm.assert_series_equal(expected, indexer_sl(ser)[[2, 3, 4]])
+ tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 3, 4]])
- expected = s.iloc[2:5]
- tm.assert_series_equal(expected, s[s >= 2])
+ expected = ser.iloc[2:5]
+ tm.assert_series_equal(expected, indexer_sl(ser)[ser >= 2])
@pytest.mark.parametrize("direction", ["increasing", "decreasing"])
- def test_nonoverlapping_monotonic(self, direction, closed):
+ def test_nonoverlapping_monotonic(self, direction, closed, indexer_sl):
tpls = [(0, 1), (2, 3), (4, 5)]
if direction == "decreasing":
tpls = tpls[::-1]
idx = IntervalIndex.from_tuples(tpls, closed=closed)
- s = Series(list("abc"), idx)
+ ser = Series(list("abc"), idx)
- for key, expected in zip(idx.left, s):
+ for key, expected in zip(idx.left, ser):
if idx.closed_left:
- assert s[key] == expected
- assert s.loc[key] == expected
+ assert indexer_sl(ser)[key] == expected
else:
with pytest.raises(KeyError, match=str(key)):
- s[key]
- with pytest.raises(KeyError, match=str(key)):
- s.loc[key]
+ indexer_sl(ser)[key]
- for key, expected in zip(idx.right, s):
+ for key, expected in zip(idx.right, ser):
if idx.closed_right:
- assert s[key] == expected
- assert s.loc[key] == expected
+ assert indexer_sl(ser)[key] == expected
else:
with pytest.raises(KeyError, match=str(key)):
- s[key]
- with pytest.raises(KeyError, match=str(key)):
- s.loc[key]
+ indexer_sl(ser)[key]
- for key, expected in zip(idx.mid, s):
- assert s[key] == expected
- assert s.loc[key] == expected
+ for key, expected in zip(idx.mid, ser):
+ assert indexer_sl(ser)[key] == expected
- def test_non_matching(self):
- s = self.s
+ def test_non_matching(self, series_with_interval_index, indexer_sl):
+ ser = series_with_interval_index.copy()
# this is a departure from our current
# indexing scheme, but simpler
with pytest.raises(KeyError, match=r"^\[-1\]$"):
- s.loc[[-1, 3, 4, 5]]
+ indexer_sl(ser)[[-1, 3, 4, 5]]
with pytest.raises(KeyError, match=r"^\[-1\]$"):
- s.loc[[-1, 3]]
+ indexer_sl(ser)[[-1, 3]]
@pytest.mark.arm_slow
def test_large_series(self):
- s = Series(
+ ser = Series(
np.arange(1000000), index=IntervalIndex.from_breaks(np.arange(1000001))
)
- result1 = s.loc[:80000]
- result2 = s.loc[0:80000]
- result3 = s.loc[0:80000:1]
+ result1 = ser.loc[:80000]
+ result2 = ser.loc[0:80000]
+ result3 = ser.loc[0:80000:1]
tm.assert_series_equal(result1, result2)
tm.assert_series_equal(result1, result3)
def test_loc_getitem_frame(self):
# CategoricalIndex with IntervalIndex categories
df = DataFrame({"A": range(10)})
- s = pd.cut(df.A, 5)
- df["B"] = s
+ ser = pd.cut(df.A, 5)
+ df["B"] = ser
df = df.set_index("B")
result = df.loc[4]
diff --git a/pandas/tests/indexing/interval/test_interval_new.py b/pandas/tests/indexing/interval/test_interval_new.py
index a9512bc97d9de..8935eb94c1c49 100644
--- a/pandas/tests/indexing/interval/test_interval_new.py
+++ b/pandas/tests/indexing/interval/test_interval_new.py
@@ -8,89 +8,65 @@
class TestIntervalIndex:
- def setup_method(self, method):
- self.s = Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6)))
+ @pytest.fixture
+ def series_with_interval_index(self):
+ return Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6)))
- def test_loc_with_interval(self):
+ def test_loc_with_interval(self, series_with_interval_index, indexer_sl):
# loc with single label / list of labels:
# - Intervals: only exact matches
# - scalars: those that contain it
- s = self.s
+ ser = series_with_interval_index.copy()
expected = 0
- result = s.loc[Interval(0, 1)]
- assert result == expected
- result = s[Interval(0, 1)]
+ result = indexer_sl(ser)[Interval(0, 1)]
assert result == expected
- expected = s.iloc[3:5]
- result = s.loc[[Interval(3, 4), Interval(4, 5)]]
- tm.assert_series_equal(expected, result)
- result = s[[Interval(3, 4), Interval(4, 5)]]
+ expected = ser.iloc[3:5]
+ result = indexer_sl(ser)[[Interval(3, 4), Interval(4, 5)]]
tm.assert_series_equal(expected, result)
# missing or not exact
with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='left')")):
- s.loc[Interval(3, 5, closed="left")]
-
- with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='left')")):
- s[Interval(3, 5, closed="left")]
-
- with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='right')")):
- s[Interval(3, 5)]
+ indexer_sl(ser)[Interval(3, 5, closed="left")]
with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='right')")):
- s.loc[Interval(3, 5)]
-
- with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='right')")):
- s[Interval(3, 5)]
-
- with pytest.raises(
- KeyError, match=re.escape("Interval(-2, 0, closed='right')")
- ):
- s.loc[Interval(-2, 0)]
+ indexer_sl(ser)[Interval(3, 5)]
with pytest.raises(
KeyError, match=re.escape("Interval(-2, 0, closed='right')")
):
- s[Interval(-2, 0)]
-
- with pytest.raises(KeyError, match=re.escape("Interval(5, 6, closed='right')")):
- s.loc[Interval(5, 6)]
+ indexer_sl(ser)[Interval(-2, 0)]
with pytest.raises(KeyError, match=re.escape("Interval(5, 6, closed='right')")):
- s[Interval(5, 6)]
+ indexer_sl(ser)[Interval(5, 6)]
- def test_loc_with_scalar(self):
+ def test_loc_with_scalar(self, series_with_interval_index, indexer_sl):
# loc with single label / list of labels:
# - Intervals: only exact matches
# - scalars: those that contain it
- s = self.s
+ ser = series_with_interval_index.copy()
- assert s.loc[1] == 0
- assert s.loc[1.5] == 1
- assert s.loc[2] == 1
+ assert indexer_sl(ser)[1] == 0
+ assert indexer_sl(ser)[1.5] == 1
+ assert indexer_sl(ser)[2] == 1
- assert s[1] == 0
- assert s[1.5] == 1
- assert s[2] == 1
+ expected = ser.iloc[1:4]
+ tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 2.5, 3.5]])
+ tm.assert_series_equal(expected, indexer_sl(ser)[[2, 3, 4]])
+ tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 3, 4]])
- expected = s.iloc[1:4]
- tm.assert_series_equal(expected, s.loc[[1.5, 2.5, 3.5]])
- tm.assert_series_equal(expected, s.loc[[2, 3, 4]])
- tm.assert_series_equal(expected, s.loc[[1.5, 3, 4]])
+ expected = ser.iloc[[1, 1, 2, 1]]
+ tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 2, 2.5, 1.5]])
- expected = s.iloc[[1, 1, 2, 1]]
- tm.assert_series_equal(expected, s.loc[[1.5, 2, 2.5, 1.5]])
+ expected = ser.iloc[2:5]
+ tm.assert_series_equal(expected, indexer_sl(ser)[ser >= 2])
- expected = s.iloc[2:5]
- tm.assert_series_equal(expected, s.loc[s >= 2])
-
- def test_loc_with_slices(self):
+ def test_loc_with_slices(self, series_with_interval_index, indexer_sl):
# loc with slices:
# - Interval objects: only works with exact matches
@@ -99,178 +75,130 @@ def test_loc_with_slices(self):
# contains them:
# (slice_loc(start, stop) == (idx.get_loc(start), idx.get_loc(stop))
- s = self.s
+ ser = series_with_interval_index.copy()
# slice of interval
- expected = s.iloc[:3]
- result = s.loc[Interval(0, 1) : Interval(2, 3)]
- tm.assert_series_equal(expected, result)
- result = s[Interval(0, 1) : Interval(2, 3)]
+ expected = ser.iloc[:3]
+ result = indexer_sl(ser)[Interval(0, 1) : Interval(2, 3)]
tm.assert_series_equal(expected, result)
- expected = s.iloc[3:]
- result = s.loc[Interval(3, 4) :]
- tm.assert_series_equal(expected, result)
- result = s[Interval(3, 4) :]
+ expected = ser.iloc[3:]
+ result = indexer_sl(ser)[Interval(3, 4) :]
tm.assert_series_equal(expected, result)
msg = "Interval objects are not currently supported"
with pytest.raises(NotImplementedError, match=msg):
- s.loc[Interval(3, 6) :]
+ indexer_sl(ser)[Interval(3, 6) :]
with pytest.raises(NotImplementedError, match=msg):
- s[Interval(3, 6) :]
-
- with pytest.raises(NotImplementedError, match=msg):
- s.loc[Interval(3, 4, closed="left") :]
-
- with pytest.raises(NotImplementedError, match=msg):
- s[Interval(3, 4, closed="left") :]
-
- # slice of scalar
+ indexer_sl(ser)[Interval(3, 4, closed="left") :]
- expected = s.iloc[:3]
- tm.assert_series_equal(expected, s.loc[:3])
- tm.assert_series_equal(expected, s.loc[:2.5])
- tm.assert_series_equal(expected, s.loc[0.1:2.5])
- tm.assert_series_equal(expected, s.loc[-1:3])
-
- tm.assert_series_equal(expected, s[:3])
- tm.assert_series_equal(expected, s[:2.5])
- tm.assert_series_equal(expected, s[0.1:2.5])
-
- def test_slice_step_ne1(self):
+ def test_slice_step_ne1(self, series_with_interval_index):
# GH#31658 slice of scalar with step != 1
- s = self.s
- expected = s.iloc[0:4:2]
+ ser = series_with_interval_index.copy()
+ expected = ser.iloc[0:4:2]
- result = s[0:4:2]
+ result = ser[0:4:2]
tm.assert_series_equal(result, expected)
- result2 = s[0:4][::2]
+ result2 = ser[0:4][::2]
tm.assert_series_equal(result2, expected)
- def test_slice_float_start_stop(self):
+ def test_slice_float_start_stop(self, series_with_interval_index):
# GH#31658 slicing with integers is positional, with floats is not
# supported
- ser = Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6)))
+ ser = series_with_interval_index.copy()
msg = "label-based slicing with step!=1 is not supported for IntervalIndex"
with pytest.raises(ValueError, match=msg):
ser[1.5:9.5:2]
- def test_slice_interval_step(self):
+ def test_slice_interval_step(self, series_with_interval_index):
# GH#31658 allows for integer step!=1, not Interval step
- s = self.s
+ ser = series_with_interval_index.copy()
msg = "label-based slicing with step!=1 is not supported for IntervalIndex"
with pytest.raises(ValueError, match=msg):
- s[0 : 4 : Interval(0, 1)]
+ ser[0 : 4 : Interval(0, 1)]
- def test_loc_with_overlap(self):
+ def test_loc_with_overlap(self, indexer_sl):
idx = IntervalIndex.from_tuples([(1, 5), (3, 7)])
- s = Series(range(len(idx)), index=idx)
+ ser = Series(range(len(idx)), index=idx)
# scalar
- expected = s
- result = s.loc[4]
- tm.assert_series_equal(expected, result)
-
- result = s[4]
- tm.assert_series_equal(expected, result)
-
- result = s.loc[[4]]
+ expected = ser
+ result = indexer_sl(ser)[4]
tm.assert_series_equal(expected, result)
- result = s[[4]]
+ result = indexer_sl(ser)[[4]]
tm.assert_series_equal(expected, result)
# interval
expected = 0
- result = s.loc[Interval(1, 5)]
+ result = indexer_sl(ser)[Interval(1, 5)]
result == expected
- result = s[Interval(1, 5)]
- result == expected
-
- expected = s
- result = s.loc[[Interval(1, 5), Interval(3, 7)]]
- tm.assert_series_equal(expected, result)
-
- result = s[[Interval(1, 5), Interval(3, 7)]]
+ expected = ser
+ result = indexer_sl(ser)[[Interval(1, 5), Interval(3, 7)]]
tm.assert_series_equal(expected, result)
with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='right')")):
- s.loc[Interval(3, 5)]
+ indexer_sl(ser)[Interval(3, 5)]
with pytest.raises(KeyError, match=r"^\[Interval\(3, 5, closed='right'\)\]$"):
- s.loc[[Interval(3, 5)]]
-
- with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='right')")):
- s[Interval(3, 5)]
-
- with pytest.raises(KeyError, match=r"^\[Interval\(3, 5, closed='right'\)\]$"):
- s[[Interval(3, 5)]]
+ indexer_sl(ser)[[Interval(3, 5)]]
# slices with interval (only exact matches)
- expected = s
- result = s.loc[Interval(1, 5) : Interval(3, 7)]
- tm.assert_series_equal(expected, result)
-
- result = s[Interval(1, 5) : Interval(3, 7)]
+ expected = ser
+ result = indexer_sl(ser)[Interval(1, 5) : Interval(3, 7)]
tm.assert_series_equal(expected, result)
msg = "'can only get slices from an IntervalIndex if bounds are"
" non-overlapping and all monotonic increasing or decreasing'"
with pytest.raises(KeyError, match=msg):
- s.loc[Interval(1, 6) : Interval(3, 8)]
+ indexer_sl(ser)[Interval(1, 6) : Interval(3, 8)]
- with pytest.raises(KeyError, match=msg):
- s[Interval(1, 6) : Interval(3, 8)]
-
- # slices with scalar raise for overlapping intervals
- # TODO KeyError is the appropriate error?
- with pytest.raises(KeyError, match=msg):
- s.loc[1:4]
+ if indexer_sl is tm.loc:
+ # slices with scalar raise for overlapping intervals
+ # TODO KeyError is the appropriate error?
+ with pytest.raises(KeyError, match=msg):
+ ser.loc[1:4]
- def test_non_unique(self):
+ def test_non_unique(self, indexer_sl):
idx = IntervalIndex.from_tuples([(1, 3), (3, 7)])
- s = Series(range(len(idx)), index=idx)
+ ser = Series(range(len(idx)), index=idx)
- result = s.loc[Interval(1, 3)]
+ result = indexer_sl(ser)[Interval(1, 3)]
assert result == 0
- result = s.loc[[Interval(1, 3)]]
- expected = s.iloc[0:1]
+ result = indexer_sl(ser)[[Interval(1, 3)]]
+ expected = ser.iloc[0:1]
tm.assert_series_equal(expected, result)
- def test_non_unique_moar(self):
+ def test_non_unique_moar(self, indexer_sl):
idx = IntervalIndex.from_tuples([(1, 3), (1, 3), (3, 7)])
- s = Series(range(len(idx)), index=idx)
-
- expected = s.iloc[[0, 1]]
- result = s.loc[Interval(1, 3)]
- tm.assert_series_equal(expected, result)
+ ser = Series(range(len(idx)), index=idx)
- expected = s
- result = s.loc[Interval(1, 3) :]
+ expected = ser.iloc[[0, 1]]
+ result = indexer_sl(ser)[Interval(1, 3)]
tm.assert_series_equal(expected, result)
- expected = s
- result = s[Interval(1, 3) :]
+ expected = ser
+ result = indexer_sl(ser)[Interval(1, 3) :]
tm.assert_series_equal(expected, result)
- expected = s.iloc[[0, 1]]
- result = s[[Interval(1, 3)]]
+ expected = ser.iloc[[0, 1]]
+ result = indexer_sl(ser)[[Interval(1, 3)]]
tm.assert_series_equal(expected, result)
- def test_missing_key_error_message(self, frame_or_series):
+ def test_missing_key_error_message(
+ self, frame_or_series, series_with_interval_index
+ ):
# GH#27365
- obj = frame_or_series(
- np.arange(5), index=IntervalIndex.from_breaks(np.arange(6))
- )
+ ser = series_with_interval_index.copy()
+ obj = frame_or_series(ser)
with pytest.raises(KeyError, match=r"\[6\]"):
obj.loc[[4, 5, 6]]
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39803 | 2021-02-14T02:43:01Z | 2021-02-15T22:37:28Z | 2021-02-15T22:37:28Z | 2021-02-15T22:38:21Z |
DOC: skip evaluation of code in v0.8.0 release notes | diff --git a/doc/source/whatsnew/v0.8.0.rst b/doc/source/whatsnew/v0.8.0.rst
index 781054fc4de7c..490175914cef1 100644
--- a/doc/source/whatsnew/v0.8.0.rst
+++ b/doc/source/whatsnew/v0.8.0.rst
@@ -176,7 +176,7 @@ New plotting methods
Vytautas Jancauskas, the 2012 GSOC participant, has added many new plot
types. For example, ``'kde'`` is a new option:
-.. ipython:: python
+.. code-block:: python
s = pd.Series(
np.concatenate((np.random.randn(1000), np.random.randn(1000) * 0.5 + 3))
| As noted in https://github.com/pandas-dev/pandas/pull/39364#issuecomment-778678278. A little unclear to me why it's not failing in other pull requests, as I can reproduce the issue locally.
- [ ] ~~closes #xxxx~~
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] ~~whatsnew entry~~
| https://api.github.com/repos/pandas-dev/pandas/pulls/39801 | 2021-02-13T21:24:56Z | 2021-02-15T22:37:46Z | 2021-02-15T22:37:46Z | 2021-02-15T22:37:49Z |
Regression in to_excel when setting duplicate column names | diff --git a/doc/source/whatsnew/v1.2.3.rst b/doc/source/whatsnew/v1.2.3.rst
index e675b3ea921d1..4231b6d94b1b9 100644
--- a/doc/source/whatsnew/v1.2.3.rst
+++ b/doc/source/whatsnew/v1.2.3.rst
@@ -15,7 +15,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
--
+- Fixed regression in :func:`pandas.to_excel` raising ``KeyError`` when giving duplicate columns with ``columns`` attribute (:issue:`39695`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py
index b027d8139f24b..684ea9f01ff35 100644
--- a/pandas/io/formats/excel.py
+++ b/pandas/io/formats/excel.py
@@ -475,7 +475,7 @@ def __init__(
if not len(Index(cols).intersection(df.columns)):
raise KeyError("passes columns are not ALL present dataframe")
- if len(Index(cols).intersection(df.columns)) != len(cols):
+ if len(Index(cols).intersection(df.columns)) != len(set(cols)):
# Deprecated in GH#17295, enforced in 1.0.0
raise KeyError("Not all names specified in 'columns' are found")
diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py
index 0c61a8a18e153..0aebcda83993d 100644
--- a/pandas/tests/io/excel/test_writers.py
+++ b/pandas/tests/io/excel/test_writers.py
@@ -1305,6 +1305,15 @@ def test_raise_when_saving_timezones(self, dtype, tz_aware_fixture, path):
with pytest.raises(ValueError, match="Excel does not support"):
df.to_excel(path)
+ def test_excel_duplicate_columns_with_names(self, path):
+ # GH#39695
+ df = DataFrame({"A": [0, 1], "B": [10, 11]})
+ df.to_excel(path, columns=["A", "B", "A"], index=False)
+
+ result = pd.read_excel(path)
+ expected = DataFrame([[0, 10, 0], [1, 11, 1]], columns=["A", "B", "A.1"])
+ tm.assert_frame_equal(result, expected)
+
class TestExcelWriterEngineTests:
@pytest.mark.parametrize(
| - [x] closes #39695
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39800 | 2021-02-13T21:07:24Z | 2021-02-15T22:42:17Z | 2021-02-15T22:42:17Z | 2021-02-18T19:46:12Z |
TYP: assorted annotations | diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx
index 61568717ace68..4d0bd4744be5d 100644
--- a/pandas/_libs/reduction.pyx
+++ b/pandas/_libs/reduction.pyx
@@ -109,9 +109,8 @@ cdef class SeriesBinGrouper(_BaseGrouper):
ndarray arr, index, dummy_arr, dummy_index
object values, f, bins, typ, ityp, name
- def __init__(self, object series, object f, object bins, object dummy):
+ def __init__(self, object series, object f, object bins):
- assert dummy is not None # always obj[:0]
assert len(bins) > 0 # otherwise we get IndexError in get_result
self.bins = bins
@@ -127,6 +126,7 @@ cdef class SeriesBinGrouper(_BaseGrouper):
self.index = series.index.values
self.name = series.name
+ dummy = series.iloc[:0]
self.dummy_arr, self.dummy_index = self._check_dummy(dummy)
# kludge for #1688
@@ -203,10 +203,7 @@ cdef class SeriesGrouper(_BaseGrouper):
object f, labels, values, typ, ityp, name
def __init__(self, object series, object f, object labels,
- Py_ssize_t ngroups, object dummy):
-
- # in practice we always pass obj.iloc[:0] or equivalent
- assert dummy is not None
+ Py_ssize_t ngroups):
if len(series) == 0:
# get_result would never assign `result`
@@ -225,6 +222,7 @@ cdef class SeriesGrouper(_BaseGrouper):
self.index = series.index.values
self.name = series.name
+ dummy = series.iloc[:0]
self.dummy_arr, self.dummy_index = self._check_dummy(dummy)
self.ngroups = ngroups
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 40533cdd554b3..4dac4dd557af2 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -263,7 +263,7 @@ def _reconstruct_data(
return values
-def _ensure_arraylike(values):
+def _ensure_arraylike(values) -> ArrayLike:
"""
ensure that we are arraylike if not already
"""
@@ -323,7 +323,7 @@ def get_data_algo(values: ArrayLike):
return htable, values
-def _check_object_for_strings(values) -> str:
+def _check_object_for_strings(values: np.ndarray) -> str:
"""
Check if we can use string hashtable instead of object hashtable.
@@ -527,7 +527,11 @@ def f(c, v):
def factorize_array(
- values: np.ndarray, na_sentinel: int = -1, size_hint=None, na_value=None, mask=None
+ values: np.ndarray,
+ na_sentinel: int = -1,
+ size_hint: Optional[int] = None,
+ na_value=None,
+ mask: Optional[np.ndarray] = None,
) -> Tuple[np.ndarray, np.ndarray]:
"""
Factorize an array-like to codes and uniques.
@@ -982,13 +986,13 @@ def mode(values, dropna: bool = True) -> Series:
def rank(
- values,
+ values: ArrayLike,
axis: int = 0,
method: str = "average",
na_option: str = "keep",
ascending: bool = True,
pct: bool = False,
-):
+) -> np.ndarray:
"""
Rank the values along a given axis.
@@ -1038,7 +1042,12 @@ def rank(
return ranks
-def checked_add_with_arr(arr, b, arr_mask=None, b_mask=None):
+def checked_add_with_arr(
+ arr: np.ndarray,
+ b,
+ arr_mask: Optional[np.ndarray] = None,
+ b_mask: Optional[np.ndarray] = None,
+) -> np.ndarray:
"""
Perform array addition that checks for underflow and overflow.
@@ -1051,9 +1060,9 @@ def checked_add_with_arr(arr, b, arr_mask=None, b_mask=None):
----------
arr : array addend.
b : array or scalar addend.
- arr_mask : boolean array or None
+ arr_mask : np.ndarray[bool] or None, default None
array indicating which elements to exclude from checking
- b_mask : boolean array or boolean or None
+ b_mask : np.ndarray[bool] or None, default None
array or scalar indicating which element(s) to exclude from checking
Returns
@@ -1406,7 +1415,9 @@ def get_indexer(current_indexer, other_indexer):
def _view_wrapper(f, arr_dtype=None, out_dtype=None, fill_wrap=None):
- def wrapper(arr, indexer, out, fill_value=np.nan):
+ def wrapper(
+ arr: np.ndarray, indexer: np.ndarray, out: np.ndarray, fill_value=np.nan
+ ):
if arr_dtype is not None:
arr = arr.view(arr_dtype)
if out_dtype is not None:
@@ -1419,7 +1430,9 @@ def wrapper(arr, indexer, out, fill_value=np.nan):
def _convert_wrapper(f, conv_dtype):
- def wrapper(arr, indexer, out, fill_value=np.nan):
+ def wrapper(
+ arr: np.ndarray, indexer: np.ndarray, out: np.ndarray, fill_value=np.nan
+ ):
if conv_dtype == object:
# GH#39755 avoid casting dt64/td64 to integers
arr = ensure_wrapped_if_datetimelike(arr)
@@ -1429,7 +1442,9 @@ def wrapper(arr, indexer, out, fill_value=np.nan):
return wrapper
-def _take_2d_multi_object(arr, indexer, out, fill_value, mask_info):
+def _take_2d_multi_object(
+ arr: np.ndarray, indexer: np.ndarray, out: np.ndarray, fill_value, mask_info
+) -> None:
# this is not ideal, performance-wise, but it's better than raising
# an exception (best to optimize in Cython to avoid getting here)
row_idx, col_idx = indexer
@@ -1452,7 +1467,14 @@ def _take_2d_multi_object(arr, indexer, out, fill_value, mask_info):
out[i, j] = arr[u_, v]
-def _take_nd_object(arr, indexer, out, axis: int, fill_value, mask_info):
+def _take_nd_object(
+ arr: np.ndarray,
+ indexer: np.ndarray,
+ out: np.ndarray,
+ axis: int,
+ fill_value,
+ mask_info,
+):
if mask_info is not None:
mask, needs_masking = mask_info
else:
@@ -1570,7 +1592,7 @@ def _take_nd_object(arr, indexer, out, axis: int, fill_value, mask_info):
def _get_take_nd_function(
- ndim: int, arr_dtype, out_dtype, axis: int = 0, mask_info=None
+ ndim: int, arr_dtype: np.dtype, out_dtype: np.dtype, axis: int = 0, mask_info=None
):
if ndim <= 2:
tup = (arr_dtype.name, out_dtype.name)
@@ -1605,7 +1627,9 @@ def func2(arr, indexer, out, fill_value=np.nan):
return func2
-def take(arr, indices, axis: int = 0, allow_fill: bool = False, fill_value=None):
+def take(
+ arr, indices: np.ndarray, axis: int = 0, allow_fill: bool = False, fill_value=None
+):
"""
Take elements from an array.
@@ -1739,7 +1763,7 @@ def take_nd(
arr,
indexer,
axis: int = 0,
- out=None,
+ out: Optional[np.ndarray] = None,
fill_value=lib.no_default,
allow_fill: bool = True,
):
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 6cfc0e1853b74..4d165dac40397 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -198,7 +198,7 @@ class IntervalArray(IntervalMixin, ExtensionArray):
# Constructors
def __new__(
- cls,
+ cls: Type[IntervalArrayT],
data,
closed=None,
dtype: Optional[Dtype] = None,
@@ -226,7 +226,7 @@ def __new__(
raise TypeError(msg)
# might need to convert empty or purely na data
- data = maybe_convert_platform_interval(data)
+ data = _maybe_convert_platform_interval(data)
left, right, infer_closed = intervals_to_interval_bounds(
data, validate_closed=closed is None
)
@@ -243,14 +243,14 @@ def __new__(
@classmethod
def _simple_new(
- cls,
+ cls: Type[IntervalArrayT],
left,
right,
closed=None,
- copy=False,
+ copy: bool = False,
dtype: Optional[Dtype] = None,
- verify_integrity=True,
- ):
+ verify_integrity: bool = True,
+ ) -> IntervalArrayT:
result = IntervalMixin.__new__(cls)
if closed is None and isinstance(dtype, IntervalDtype):
@@ -330,12 +330,18 @@ def _simple_new(
@classmethod
def _from_sequence(
- cls, scalars, *, dtype: Optional[Dtype] = None, copy: bool = False
- ):
+ cls: Type[IntervalArrayT],
+ scalars,
+ *,
+ dtype: Optional[Dtype] = None,
+ copy: bool = False,
+ ) -> IntervalArrayT:
return cls(scalars, dtype=dtype, copy=copy)
@classmethod
- def _from_factorized(cls, values, original):
+ def _from_factorized(
+ cls: Type[IntervalArrayT], values: np.ndarray, original: IntervalArrayT
+ ) -> IntervalArrayT:
if len(values) == 0:
# An empty array returns object-dtype here. We can't create
# a new IA from an (empty) object-dtype array, so turn it into the
@@ -391,9 +397,13 @@ def _from_factorized(cls, values, original):
}
)
def from_breaks(
- cls, breaks, closed="right", copy: bool = False, dtype: Optional[Dtype] = None
- ):
- breaks = maybe_convert_platform_interval(breaks)
+ cls: Type[IntervalArrayT],
+ breaks,
+ closed="right",
+ copy: bool = False,
+ dtype: Optional[Dtype] = None,
+ ) -> IntervalArrayT:
+ breaks = _maybe_convert_platform_interval(breaks)
return cls.from_arrays(breaks[:-1], breaks[1:], closed, copy=copy, dtype=dtype)
@@ -462,10 +472,15 @@ def from_breaks(
}
)
def from_arrays(
- cls, left, right, closed="right", copy=False, dtype: Optional[Dtype] = None
- ):
- left = maybe_convert_platform_interval(left)
- right = maybe_convert_platform_interval(right)
+ cls: Type[IntervalArrayT],
+ left,
+ right,
+ closed="right",
+ copy: bool = False,
+ dtype: Optional[Dtype] = None,
+ ) -> IntervalArrayT:
+ left = _maybe_convert_platform_interval(left)
+ right = _maybe_convert_platform_interval(right)
return cls._simple_new(
left, right, closed, copy=copy, dtype=dtype, verify_integrity=True
@@ -521,8 +536,12 @@ def from_arrays(
}
)
def from_tuples(
- cls, data, closed="right", copy=False, dtype: Optional[Dtype] = None
- ):
+ cls: Type[IntervalArrayT],
+ data,
+ closed="right",
+ copy: bool = False,
+ dtype: Optional[Dtype] = None,
+ ) -> IntervalArrayT:
if len(data):
left, right = [], []
else:
@@ -577,7 +596,7 @@ def _validate(self):
msg = "left side of interval must be <= right side"
raise ValueError(msg)
- def _shallow_copy(self, left, right):
+ def _shallow_copy(self: IntervalArrayT, left, right) -> IntervalArrayT:
"""
Return a new IntervalArray with the replacement attributes
@@ -594,7 +613,7 @@ def _shallow_copy(self, left, right):
# Descriptive
@property
- def dtype(self):
+ def dtype(self) -> IntervalDtype:
return self._dtype
@property
@@ -750,7 +769,9 @@ def argsort(
ascending=ascending, kind=kind, na_position=na_position, **kwargs
)
- def fillna(self, value=None, method=None, limit=None):
+ def fillna(
+ self: IntervalArrayT, value=None, method=None, limit=None
+ ) -> IntervalArrayT:
"""
Fill NA/NaN values using the specified method.
@@ -788,7 +809,7 @@ def fillna(self, value=None, method=None, limit=None):
right = self.right.fillna(value=value_right)
return self._shallow_copy(left, right)
- def astype(self, dtype, copy=True):
+ def astype(self, dtype, copy: bool = True):
"""
Cast to an ExtensionArray or NumPy array with dtype 'dtype'.
@@ -892,7 +913,9 @@ def copy(self: IntervalArrayT) -> IntervalArrayT:
def isna(self) -> np.ndarray:
return isna(self._left)
- def shift(self, periods: int = 1, fill_value: object = None) -> IntervalArray:
+ def shift(
+ self: IntervalArrayT, periods: int = 1, fill_value: object = None
+ ) -> IntervalArray:
if not len(self) or periods == 0:
return self.copy()
@@ -921,7 +944,15 @@ def shift(self, periods: int = 1, fill_value: object = None) -> IntervalArray:
b = empty
return self._concat_same_type([a, b])
- def take(self, indices, *, allow_fill=False, fill_value=None, axis=None, **kwargs):
+ def take(
+ self: IntervalArrayT,
+ indices,
+ *,
+ allow_fill: bool = False,
+ fill_value=None,
+ axis=None,
+ **kwargs,
+ ) -> IntervalArrayT:
"""
Take elements from the IntervalArray.
@@ -1076,7 +1107,7 @@ def value_counts(self, dropna: bool = True):
# ---------------------------------------------------------------------
# Rendering Methods
- def _format_data(self):
+ def _format_data(self) -> str:
# TODO: integrate with categorical and make generic
# name argument is unused here; just for compat with base / categorical
@@ -1120,7 +1151,7 @@ def __repr__(self) -> str:
template = f"{class_name}{data}\nLength: {len(self)}, dtype: {self.dtype}"
return template
- def _format_space(self):
+ def _format_space(self) -> str:
space = " " * (len(type(self).__name__) + 1)
return f"\n{space}"
@@ -1300,7 +1331,7 @@ def closed(self):
),
}
)
- def set_closed(self, closed):
+ def set_closed(self: IntervalArrayT, closed) -> IntervalArrayT:
if closed not in VALID_CLOSED:
msg = f"invalid option for 'closed': {closed}"
raise ValueError(msg)
@@ -1323,7 +1354,7 @@ def set_closed(self, closed):
@Appender(
_interval_shared_docs["is_non_overlapping_monotonic"] % _shared_docs_kwargs
)
- def is_non_overlapping_monotonic(self):
+ def is_non_overlapping_monotonic(self) -> bool:
# must be increasing (e.g., [0, 1), [1, 2), [2, 3), ... )
# or decreasing (e.g., [-1, 0), [-2, -1), [-3, -2), ...)
# we already require left <= right
@@ -1436,7 +1467,7 @@ def __arrow_array__(self, type=None):
@Appender(
_interval_shared_docs["to_tuples"] % {"return_type": "ndarray", "examples": ""}
)
- def to_tuples(self, na_tuple=True):
+ def to_tuples(self, na_tuple=True) -> np.ndarray:
tuples = com.asarray_tuplesafe(zip(self._left, self._right))
if not na_tuple:
# GH 18756
@@ -1465,7 +1496,7 @@ def delete(self: IntervalArrayT, loc) -> IntervalArrayT:
return self._shallow_copy(left=new_left, right=new_right)
@Appender(_extension_array_shared_docs["repeat"] % _shared_docs_kwargs)
- def repeat(self, repeats, axis=None):
+ def repeat(self: IntervalArrayT, repeats: int, axis=None) -> IntervalArrayT:
nv.validate_repeat((), {"axis": axis})
left_repeat = self.left.repeat(repeats)
right_repeat = self.right.repeat(repeats)
@@ -1564,7 +1595,7 @@ def _combined(self) -> ArrayLike:
return comb
-def maybe_convert_platform_interval(values):
+def _maybe_convert_platform_interval(values) -> ArrayLike:
"""
Try to do platform conversion, with special casing for IntervalArray.
Wrapper around maybe_convert_platform that alters the default return
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 50aed70bf275d..8625c5063382f 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -49,11 +49,7 @@
ABCSeries,
)
from pandas.core.dtypes.inference import iterable_not_string
-from pandas.core.dtypes.missing import ( # noqa
- isna,
- isnull,
- notnull,
-)
+from pandas.core.dtypes.missing import isna
class SettingWithCopyError(ValueError):
@@ -153,7 +149,7 @@ def is_bool_indexer(key: Any) -> bool:
return False
-def cast_scalar_indexer(val, warn_float=False):
+def cast_scalar_indexer(val, warn_float: bool = False):
"""
To avoid numpy DeprecationWarnings, cast float to integer where valid.
@@ -300,7 +296,7 @@ def is_null_slice(obj) -> bool:
)
-def is_true_slices(line):
+def is_true_slices(line) -> List[bool]:
"""
Find non-trivial slices in "line": return a list of booleans with same length.
"""
@@ -308,7 +304,7 @@ def is_true_slices(line):
# TODO: used only once in indexing; belongs elsewhere?
-def is_full_slice(obj, line) -> bool:
+def is_full_slice(obj, line: int) -> bool:
"""
We have a full length slice.
"""
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 00cb65fff3803..5004d1fe08a5b 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -742,11 +742,10 @@ def _aggregate_series_fast(self, obj: Series, func: F):
group_index, _, ngroups = self.group_info
# avoids object / Series creation overhead
- dummy = obj.iloc[:0]
indexer = get_group_index_sorter(group_index, ngroups)
obj = obj.take(indexer)
group_index = algorithms.take_nd(group_index, indexer, allow_fill=False)
- grouper = libreduction.SeriesGrouper(obj, func, group_index, ngroups, dummy)
+ grouper = libreduction.SeriesGrouper(obj, func, group_index, ngroups)
result, counts = grouper.get_result()
return result, counts
@@ -945,8 +944,7 @@ def agg_series(self, obj: Series, func: F):
# preempt SeriesBinGrouper from raising TypeError
return self._aggregate_series_pure_python(obj, func)
- dummy = obj[:0]
- grouper = libreduction.SeriesBinGrouper(obj, func, self.bins, dummy)
+ grouper = libreduction.SeriesBinGrouper(obj, func, self.bins)
return grouper.get_result()
diff --git a/pandas/core/indexers.py b/pandas/core/indexers.py
index 0649cc3efc153..86d6b772fe2e4 100644
--- a/pandas/core/indexers.py
+++ b/pandas/core/indexers.py
@@ -344,7 +344,7 @@ def length_of_indexer(indexer, target=None) -> int:
raise AssertionError("cannot find the length of the indexer")
-def deprecate_ndim_indexing(result, stacklevel=3):
+def deprecate_ndim_indexing(result, stacklevel: int = 3):
"""
Helper function to raise the deprecation warning for multi-dimensional
indexing on 1D Series/Index.
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index b2c67ae2f0a00..70705d6988d86 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -732,13 +732,9 @@ def _intersection(self, other: Index, sort=False) -> Index:
result = self[:0]
else:
lslice = slice(*left.slice_locs(start, end))
- left_chunk = left._values[lslice]
- # error: Argument 1 to "_simple_new" of "DatetimeIndexOpsMixin" has
- # incompatible type "Union[ExtensionArray, Any]"; expected
- # "Union[DatetimeArray, TimedeltaArray, PeriodArray]"
- result = type(self)._simple_new(left_chunk) # type: ignore[arg-type]
+ result = left._values[lslice]
- return self._wrap_setop_result(other, result)
+ return result
def _can_fast_intersect(self: _T, other: _T) -> bool:
# Note: we only get here with len(self) > 0 and len(other) > 0
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 7ef81b0947a22..615cce8767de3 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -1122,7 +1122,7 @@ def _view(self) -> MultiIndex:
result = type(self)(
levels=self.levels,
codes=self.codes,
- sortorder=None,
+ sortorder=self.sortorder,
names=self.names,
verify_integrity=False,
)
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 7b4921080e2e1..cfe16627d5c64 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -2392,7 +2392,7 @@ def is_label_like(key) -> bool:
return not isinstance(key, slice) and not is_list_like_indexer(key)
-def need_slice(obj) -> bool:
+def need_slice(obj: slice) -> bool:
"""
Returns
-------
diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py
index 2cfe613b7072b..eb1a7a355f313 100644
--- a/pandas/core/internals/construction.py
+++ b/pandas/core/internals/construction.py
@@ -36,6 +36,7 @@
maybe_convert_platform,
maybe_infer_to_datetimelike,
maybe_upcast,
+ sanitize_to_nanoseconds,
)
from pandas.core.dtypes.common import (
is_datetime64tz_dtype,
@@ -377,7 +378,7 @@ def convert(v):
# this is equiv of np.asarray, but does object conversion
# and platform dtype preservation
try:
- if is_list_like(values[0]) or hasattr(values[0], "len"):
+ if is_list_like(values[0]):
values = np.array([convert(v) for v in values])
elif isinstance(values[0], np.ndarray) and values[0].ndim == 0:
# GH#21861
@@ -827,8 +828,7 @@ def sanitize_index(data, index: Index):
if isinstance(data, np.ndarray):
- # coerce datetimelike types
- if data.dtype.kind in ["M", "m"]:
- data = sanitize_array(data, index, copy=False)
+ # coerce datetimelike types to ns
+ data = sanitize_to_nanoseconds(data)
return data
diff --git a/pandas/tests/groupby/test_bin_groupby.py b/pandas/tests/groupby/test_bin_groupby.py
index ce46afc0ccd65..f873c93d90683 100644
--- a/pandas/tests/groupby/test_bin_groupby.py
+++ b/pandas/tests/groupby/test_bin_groupby.py
@@ -13,11 +13,10 @@
def test_series_grouper():
obj = Series(np.random.randn(10))
- dummy = obj.iloc[:0]
labels = np.array([-1, -1, -1, 0, 0, 0, 1, 1, 1, 1], dtype=np.int64)
- grouper = libreduction.SeriesGrouper(obj, np.mean, labels, 2, dummy)
+ grouper = libreduction.SeriesGrouper(obj, np.mean, labels, 2)
result, counts = grouper.get_result()
expected = np.array([obj[3:6].mean(), obj[6:].mean()])
@@ -34,16 +33,15 @@ def test_series_grouper_requires_nonempty_raises():
labels = np.array([-1, -1, -1, 0, 0, 0, 1, 1, 1, 1], dtype=np.int64)
with pytest.raises(ValueError, match="SeriesGrouper requires non-empty `series`"):
- libreduction.SeriesGrouper(dummy, np.mean, labels, 2, dummy)
+ libreduction.SeriesGrouper(dummy, np.mean, labels, 2)
def test_series_bin_grouper():
obj = Series(np.random.randn(10))
- dummy = obj[:0]
bins = np.array([3, 6])
- grouper = libreduction.SeriesBinGrouper(obj, np.mean, bins, dummy)
+ grouper = libreduction.SeriesBinGrouper(obj, np.mean, bins)
result, counts = grouper.get_result()
expected = np.array([obj[:3].mean(), obj[3:6].mean(), obj[6:].mean()])
| Also avoid passing unnecesary arg to libreduction, and use a lower-level sanitize function in sanitize_index | https://api.github.com/repos/pandas-dev/pandas/pulls/39798 | 2021-02-13T19:25:47Z | 2021-02-21T17:18:15Z | 2021-02-21T17:18:15Z | 2021-02-22T15:34:09Z |
CLN: Styler simplify existing builtin methods | diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index 735fb345363c7..fa55d163376ee 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -1296,33 +1296,6 @@ def hide_columns(self, subset) -> Styler:
# A collection of "builtin" styles
# -----------------------------------------------------------------------
- @staticmethod
- def _highlight_null(v, null_color: str) -> str:
- return f"background-color: {null_color}" if pd.isna(v) else ""
-
- def highlight_null(
- self,
- null_color: str = "red",
- subset: Optional[IndexLabel] = None,
- ) -> Styler:
- """
- Shade the background ``null_color`` for missing values.
-
- Parameters
- ----------
- null_color : str, default 'red'
- subset : label or list of labels, default None
- A valid slice for ``data`` to limit the style application to.
-
- .. versionadded:: 1.1.0
-
- Returns
- -------
- self : Styler
- """
- self.applymap(self._highlight_null, null_color=null_color, subset=subset)
- return self
-
def background_gradient(
self,
cmap="PuBu",
@@ -1638,8 +1611,39 @@ def bar(
return self
+ def highlight_null(
+ self,
+ null_color: str = "red",
+ subset: Optional[IndexLabel] = None,
+ ) -> Styler:
+ """
+ Shade the background ``null_color`` for missing values.
+
+ Parameters
+ ----------
+ null_color : str, default 'red'
+ subset : label or list of labels, default None
+ A valid slice for ``data`` to limit the style application to.
+
+ .. versionadded:: 1.1.0
+
+ Returns
+ -------
+ self : Styler
+ """
+
+ def f(data: DataFrame, props: str) -> np.ndarray:
+ return np.where(pd.isna(data).values, props, "")
+
+ return self.apply(
+ f, axis=None, subset=subset, props=f"background-color: {null_color};"
+ )
+
def highlight_max(
- self, subset=None, color: str = "yellow", axis: Optional[Axis] = 0
+ self,
+ subset: Optional[IndexLabel] = None,
+ color: str = "yellow",
+ axis: Optional[Axis] = 0,
) -> Styler:
"""
Highlight the maximum by shading the background.
@@ -1658,10 +1662,19 @@ def highlight_max(
-------
self : Styler
"""
- return self._highlight_handler(subset=subset, color=color, axis=axis, max_=True)
+
+ def f(data: FrameOrSeries, props: str) -> np.ndarray:
+ return np.where(data == np.nanmax(data.values), props, "")
+
+ return self.apply(
+ f, axis=axis, subset=subset, props=f"background-color: {color};"
+ )
def highlight_min(
- self, subset=None, color: str = "yellow", axis: Optional[Axis] = 0
+ self,
+ subset: Optional[IndexLabel] = None,
+ color: str = "yellow",
+ axis: Optional[Axis] = 0,
) -> Styler:
"""
Highlight the minimum by shading the background.
@@ -1680,43 +1693,13 @@ def highlight_min(
-------
self : Styler
"""
- return self._highlight_handler(
- subset=subset, color=color, axis=axis, max_=False
- )
- def _highlight_handler(
- self,
- subset=None,
- color: str = "yellow",
- axis: Optional[Axis] = None,
- max_: bool = True,
- ) -> Styler:
- subset = non_reducing_slice(maybe_numeric_slice(self.data, subset))
- self.apply(
- self._highlight_extrema, color=color, axis=axis, subset=subset, max_=max_
- )
- return self
+ def f(data: FrameOrSeries, props: str) -> np.ndarray:
+ return np.where(data == np.nanmin(data.values), props, "")
- @staticmethod
- def _highlight_extrema(
- data: FrameOrSeries, color: str = "yellow", max_: bool = True
- ):
- """
- Highlight the min or max in a Series or DataFrame.
- """
- attr = f"background-color: {color}"
-
- if max_:
- extrema = data == np.nanmax(data.to_numpy())
- else:
- extrema = data == np.nanmin(data.to_numpy())
-
- if data.ndim == 1: # Series from .apply
- return [attr if v else "" for v in extrema]
- else: # DataFrame from .tee
- return pd.DataFrame(
- np.where(extrema, attr, ""), index=data.index, columns=data.columns
- )
+ return self.apply(
+ f, axis=axis, subset=subset, props=f"background-color: {color};"
+ )
@classmethod
def from_custom_template(cls, searchpath, name):
| Now that `Styler.apply` can accept `ndarray` in all cases we can reorganise the module and wrap all the UI facing functions into one:
- highlight null
- highlight max
- highlight min | https://api.github.com/repos/pandas-dev/pandas/pulls/39797 | 2021-02-13T18:49:31Z | 2021-02-16T17:34:01Z | 2021-02-16T17:34:01Z | 2021-02-16T20:30:47Z |
DEP: Remove xlrd as being the default reader for xlsx | diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst
index d6934a3ca2a6c..67c74f9a04618 100644
--- a/doc/source/user_guide/io.rst
+++ b/doc/source/user_guide/io.rst
@@ -2853,14 +2853,12 @@ See the :ref:`cookbook<cookbook.excel>` for some advanced strategies.
The `xlrd <https://xlrd.readthedocs.io/en/latest/>`__ package is now only for reading
old-style ``.xls`` files.
- Before pandas 1.2.0, the default argument ``engine=None`` to :func:`~pandas.read_excel`
+ Before pandas 1.3.0, the default argument ``engine=None`` to :func:`~pandas.read_excel`
would result in using the ``xlrd`` engine in many cases, including new
- Excel 2007+ (``.xlsx``) files.
- If `openpyxl <https://openpyxl.readthedocs.io/en/stable/>`__ is installed,
- many of these cases will now default to using the ``openpyxl`` engine.
- See the :func:`read_excel` documentation for more details.
+ Excel 2007+ (``.xlsx``) files. pandas will now default to using the
+ `openpyxl <https://openpyxl.readthedocs.io/en/stable/>`__ engine.
- Thus, it is strongly encouraged to install ``openpyxl`` to read Excel 2007+
+ It is strongly encouraged to install ``openpyxl`` to read Excel 2007+
(``.xlsx``) files.
**Please do not report issues when using ``xlrd`` to read ``.xlsx`` files.**
This is no longer supported, switch to using ``openpyxl`` instead.
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 799bc88ffff4e..8e3978ed9fe1a 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -8,6 +8,16 @@ including other versions of pandas.
{{ header }}
+.. warning::
+
+ When reading new Excel 2007+ (``.xlsx``) files, the default argument
+ ``engine=None`` to :func:`~pandas.read_excel` will now result in using the
+ `openpyxl <https://openpyxl.readthedocs.io/en/stable/>`_ engine in all cases
+ when the option :attr:`io.excel.xlsx.reader` is set to ``"auto"``.
+ Previously, some cases would use the
+ `xlrd <https://xlrd.readthedocs.io/en/latest/>`_ engine instead. See
+ :ref:`What's new 1.2.0 <whatsnew_120>` for background on this change.
+
.. ---------------------------------------------------------------------------
Enhancements
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index f12a530ea6c34..f95e87b7a2b12 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -129,11 +129,9 @@
``pyxlsb`` will be used.
.. versionadded:: 1.3.0
- - Otherwise if `openpyxl <https://pypi.org/project/openpyxl/>`_ is installed,
- then ``openpyxl`` will be used.
- - Otherwise if ``xlrd >= 2.0`` is installed, a ``ValueError`` will be raised.
- - Otherwise ``xlrd`` will be used and a ``FutureWarning`` will be raised. This
- case will raise a ``ValueError`` in a future version of pandas.
+ - Otherwise ``openpyxl`` will be used.
+
+ .. versionchanged:: 1.3.0
converters : dict, default None
Dict of functions for converting values in certain columns. Keys can
@@ -997,7 +995,7 @@ class ExcelFile:
Parameters
----------
path_or_buffer : str, path object (pathlib.Path or py._path.local.LocalPath),
- a file-like object, xlrd workbook or openpypl workbook.
+ a file-like object, xlrd workbook or openpyxl workbook.
If a string or path object, expected to be a path to a
.xls, .xlsx, .xlsb, .xlsm, .odf, .ods, or .odt file.
engine : str, default None
@@ -1111,9 +1109,7 @@ def __init__(
stacklevel = 2
warnings.warn(
f"Your version of xlrd is {xlrd_version}. In xlrd >= 2.0, "
- f"only the xls format is supported. As a result, the "
- f"openpyxl engine will be used if it is installed and the "
- f"engine argument is not specified. Install "
+ f"only the xls format is supported. Install "
f"openpyxl instead.",
FutureWarning,
stacklevel=stacklevel,
diff --git a/pandas/io/excel/_util.py b/pandas/io/excel/_util.py
index 01ccc9d15a6a3..4e1d572aae569 100644
--- a/pandas/io/excel/_util.py
+++ b/pandas/io/excel/_util.py
@@ -62,13 +62,6 @@ def get_default_engine(ext, mode="reader"):
_default_writers["xlsx"] = "xlsxwriter"
return _default_writers[ext]
else:
- if (
- import_optional_dependency("openpyxl", errors="ignore") is None
- and import_optional_dependency("xlrd", errors="ignore") is not None
- ):
- # if no openpyxl but xlrd installed, return xlrd
- # the version is handled elsewhere
- _default_readers["xlsx"] = "xlrd"
return _default_readers[ext]
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
index a594718bd62d9..71abb11d2616d 100644
--- a/pandas/tests/io/excel/test_readers.py
+++ b/pandas/tests/io/excel/test_readers.py
@@ -117,6 +117,30 @@ def cd_and_set_engine(self, engine, datapath, monkeypatch):
monkeypatch.chdir(datapath("io", "data", "excel"))
monkeypatch.setattr(pd, "read_excel", func)
+ def test_engine_used(self, read_ext, engine, monkeypatch):
+ # GH 38884
+ def parser(self, *args, **kwargs):
+ return self.engine
+
+ monkeypatch.setattr(pd.ExcelFile, "parse", parser)
+
+ expected_defaults = {
+ "xlsx": "openpyxl",
+ "xlsm": "openpyxl",
+ "xlsb": "pyxlsb",
+ "xls": "xlrd",
+ "ods": "odf",
+ }
+
+ with open("test1" + read_ext, "rb") as f:
+ result = pd.read_excel(f)
+
+ if engine is not None:
+ expected = engine
+ else:
+ expected = expected_defaults[read_ext[1:]]
+ assert result == expected
+
def test_usecols_int(self, read_ext, df_ref):
df_ref = df_ref.reindex(columns=["A", "B", "C"])
@@ -1164,6 +1188,24 @@ def cd_and_set_engine(self, engine, datapath, monkeypatch):
monkeypatch.chdir(datapath("io", "data", "excel"))
monkeypatch.setattr(pd, "ExcelFile", func)
+ def test_engine_used(self, read_ext, engine, monkeypatch):
+ expected_defaults = {
+ "xlsx": "openpyxl",
+ "xlsm": "openpyxl",
+ "xlsb": "pyxlsb",
+ "xls": "xlrd",
+ "ods": "odf",
+ }
+
+ with pd.ExcelFile("test1" + read_ext) as excel:
+ result = excel.engine
+
+ if engine is not None:
+ expected = engine
+ else:
+ expected = expected_defaults[read_ext[1:]]
+ assert result == expected
+
def test_excel_passes_na(self, read_ext):
with pd.ExcelFile("test4" + read_ext) as excel:
parsed = pd.read_excel(
| - [x] closes #38884
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
One thing I noticed while working on this is that xlrd is in requirements-dev but not environment.yml; not sure if it should be removed from requirements-dev.
cc @jreback @jorisvandenbossche | https://api.github.com/repos/pandas-dev/pandas/pulls/39796 | 2021-02-13T16:41:32Z | 2021-02-16T23:08:53Z | 2021-02-16T23:08:52Z | 2021-02-16T23:21:23Z |
fix benchmark failure with numpy 1.20+ | diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py
index b457bce8fe138..b8f6cb53987b8 100644
--- a/asv_bench/benchmarks/series_methods.py
+++ b/asv_bench/benchmarks/series_methods.py
@@ -2,6 +2,8 @@
import numpy as np
+from pandas.compat.numpy import np_version_under1p20
+
from pandas import Categorical, NaT, Series, date_range
from .pandas_vb_common import tm
@@ -143,6 +145,10 @@ class IsInLongSeriesLookUpDominates:
def setup(self, dtype, MaxNumber, series_type):
N = 10 ** 7
+
+ if not np_version_under1p20 and dtype in ("Int64", "Float64"):
+ raise NotImplementedError
+
if series_type == "random_hits":
np.random.seed(42)
array = np.random.randint(0, MaxNumber, N)
| xref https://github.com/pandas-dev/pandas/pull/38379#pullrequestreview-580260176
This will be blocking using numpy 1.20 on Github actions Checks, xref https://github.com/pandas-dev/pandas/pull/36092#issuecomment-771112784 | https://api.github.com/repos/pandas-dev/pandas/pulls/39795 | 2021-02-13T15:09:21Z | 2021-02-16T13:52:26Z | 2021-02-16T13:52:25Z | 2021-02-16T15:35:58Z |
TYP: tidy comments for # type: ignore | diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py
index 0b2be53131af6..97a152d9ade1e 100644
--- a/pandas/_testing/__init__.py
+++ b/pandas/_testing/__init__.py
@@ -559,7 +559,7 @@ def makeCustomIndex(
"p": makePeriodIndex,
}.get(idx_type)
if idx_func:
- # pandas\_testing.py:2120: error: Cannot call function of unknown type
+ # error: Cannot call function of unknown type
idx = idx_func(nentries) # type: ignore[operator]
# but we need to fill in the name
if names:
diff --git a/pandas/_testing/_io.py b/pandas/_testing/_io.py
index 5f27b016b68a2..8d387ff5674f7 100644
--- a/pandas/_testing/_io.py
+++ b/pandas/_testing/_io.py
@@ -82,9 +82,8 @@ def dec(f):
is_decorating = not kwargs and len(args) == 1 and callable(args[0])
if is_decorating:
f = args[0]
- # pandas\_testing.py:2331: error: Incompatible types in assignment
- # (expression has type "List[<nothing>]", variable has type
- # "Tuple[Any, ...]")
+ # error: Incompatible types in assignment (expression has type
+ # "List[<nothing>]", variable has type "Tuple[Any, ...]")
args = [] # type: ignore[assignment]
return dec(f)
else:
@@ -205,8 +204,7 @@ def wrapper(*args, **kwargs):
except Exception as err:
errno = getattr(err, "errno", None)
if not errno and hasattr(errno, "reason"):
- # pandas\_testing.py:2521: error: "Exception" has no attribute
- # "reason"
+ # error: "Exception" has no attribute "reason"
errno = getattr(err.reason, "errno", None) # type: ignore[attr-defined]
if errno in skip_errnos:
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 162a69370bc61..bb152ba709cbc 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -445,8 +445,7 @@ def _validate_comparison_value(self, other):
raise InvalidComparison(other)
if isinstance(other, self._recognized_scalars) or other is NaT:
- # pandas\core\arrays\datetimelike.py:432: error: Too many arguments
- # for "object" [call-arg]
+ # error: Too many arguments for "object"
other = self._scalar_type(other) # type: ignore[call-arg]
try:
self._check_compatible_with(other)
@@ -497,8 +496,7 @@ def _validate_shift_value(self, fill_value):
if is_valid_na_for_dtype(fill_value, self.dtype):
fill_value = NaT
elif isinstance(fill_value, self._recognized_scalars):
- # pandas\core\arrays\datetimelike.py:746: error: Too many arguments
- # for "object" [call-arg]
+ # error: Too many arguments for "object"
fill_value = self._scalar_type(fill_value) # type: ignore[call-arg]
else:
# only warn if we're not going to raise
@@ -506,8 +504,7 @@ def _validate_shift_value(self, fill_value):
# kludge for #31971 since Period(integer) tries to cast to str
new_fill = Period._from_ordinal(fill_value, freq=self.freq)
else:
- # pandas\core\arrays\datetimelike.py:753: error: Too many
- # arguments for "object" [call-arg]
+ # error: Too many arguments for "object"
new_fill = self._scalar_type(fill_value) # type: ignore[call-arg]
# stacklevel here is chosen to be correct when called from
@@ -563,7 +560,7 @@ def _validate_scalar(
value = NaT
elif isinstance(value, self._recognized_scalars):
- # error: Too many arguments for "object" [call-arg]
+ # error: Too many arguments for "object"
value = self._scalar_type(value) # type: ignore[call-arg]
else:
@@ -1679,7 +1676,7 @@ def factorize(self, na_sentinel=-1, sort: bool = False):
# TODO: overload __getitem__, a slice indexer returns same type as self
# error: Incompatible types in assignment (expression has type
# "Union[DatetimeLikeArrayMixin, Union[Any, Any]]", variable
- # has type "TimelikeOps") [assignment]
+ # has type "TimelikeOps")
uniques = uniques[::-1] # type: ignore[assignment]
return codes, uniques
# FIXME: shouldn't get here; we are ignoring sort
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 0f3e028c34c05..50b5528692b8e 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -1508,7 +1508,7 @@ def isin(self, values) -> np.ndarray:
# GH#38353 instead of casting to object, operating on a
# complex128 ndarray is much more performant.
- # error: "ArrayLike" has no attribute "view" [attr-defined]
+ # error: "ArrayLike" has no attribute "view"
left = self._combined.view("complex128") # type:ignore[attr-defined]
right = values._combined.view("complex128")
return np.in1d(left, right)
diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py
index 65618ce32b6d7..b318757e8978a 100644
--- a/pandas/core/arrays/string_.py
+++ b/pandas/core/arrays/string_.py
@@ -190,9 +190,8 @@ def __init__(self, values, copy=False):
values = extract_array(values)
super().__init__(values, copy=copy)
- # pandas\core\arrays\string_.py:188: error: Incompatible types in
- # assignment (expression has type "StringDtype", variable has type
- # "PandasDtype") [assignment]
+ # error: Incompatible types in assignment (expression has type "StringDtype",
+ # variable has type "PandasDtype")
self._dtype = StringDtype() # type: ignore[assignment]
if not isinstance(values, type(self)):
self._validate()
diff --git a/pandas/core/base.py b/pandas/core/base.py
index da8ed8a59f981..3f3b4cd1afec1 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -95,8 +95,7 @@ def __sizeof__(self):
either a value or Series of values
"""
if hasattr(self, "memory_usage"):
- # pandas\core\base.py:84: error: "PandasObject" has no attribute
- # "memory_usage" [attr-defined]
+ # error: "PandasObject" has no attribute "memory_usage"
mem = self.memory_usage(deep=True) # type: ignore[attr-defined]
return int(mem if is_scalar(mem) else mem.sum())
@@ -206,17 +205,14 @@ def _selection_list(self):
@cache_readonly
def _selected_obj(self):
- # pandas\core\base.py:195: error: "SelectionMixin" has no attribute
- # "obj" [attr-defined]
+ # error: "SelectionMixin" has no attribute "obj"
if self._selection is None or isinstance(
self.obj, ABCSeries # type: ignore[attr-defined]
):
- # pandas\core\base.py:194: error: "SelectionMixin" has no attribute
- # "obj" [attr-defined]
+ # error: "SelectionMixin" has no attribute "obj"
return self.obj # type: ignore[attr-defined]
else:
- # pandas\core\base.py:204: error: "SelectionMixin" has no attribute
- # "obj" [attr-defined]
+ # error: "SelectionMixin" has no attribute "obj"
return self.obj[self._selection] # type: ignore[attr-defined]
@cache_readonly
@@ -225,29 +221,22 @@ def ndim(self) -> int:
@cache_readonly
def _obj_with_exclusions(self):
- # pandas\core\base.py:209: error: "SelectionMixin" has no attribute
- # "obj" [attr-defined]
+ # error: "SelectionMixin" has no attribute "obj"
if self._selection is not None and isinstance(
self.obj, ABCDataFrame # type: ignore[attr-defined]
):
- # pandas\core\base.py:217: error: "SelectionMixin" has no attribute
- # "obj" [attr-defined]
+ # error: "SelectionMixin" has no attribute "obj"
return self.obj.reindex( # type: ignore[attr-defined]
columns=self._selection_list
)
- # pandas\core\base.py:207: error: "SelectionMixin" has no attribute
- # "exclusions" [attr-defined]
+ # error: "SelectionMixin" has no attribute "exclusions"
if len(self.exclusions) > 0: # type: ignore[attr-defined]
- # pandas\core\base.py:208: error: "SelectionMixin" has no attribute
- # "obj" [attr-defined]
-
- # pandas\core\base.py:208: error: "SelectionMixin" has no attribute
- # "exclusions" [attr-defined]
+ # error: "SelectionMixin" has no attribute "obj"
+ # error: "SelectionMixin" has no attribute "exclusions"
return self.obj.drop(self.exclusions, axis=1) # type: ignore[attr-defined]
else:
- # pandas\core\base.py:210: error: "SelectionMixin" has no attribute
- # "obj" [attr-defined]
+ # error: "SelectionMixin" has no attribute "obj"
return self.obj # type: ignore[attr-defined]
def __getitem__(self, key):
@@ -255,13 +244,11 @@ def __getitem__(self, key):
raise IndexError(f"Column(s) {self._selection} already selected")
if isinstance(key, (list, tuple, ABCSeries, ABCIndex, np.ndarray)):
- # pandas\core\base.py:217: error: "SelectionMixin" has no attribute
- # "obj" [attr-defined]
+ # error: "SelectionMixin" has no attribute "obj"
if len(
self.obj.columns.intersection(key) # type: ignore[attr-defined]
) != len(key):
- # pandas\core\base.py:218: error: "SelectionMixin" has no
- # attribute "obj" [attr-defined]
+ # error: "SelectionMixin" has no attribute "obj"
bad_keys = list(
set(key).difference(self.obj.columns) # type: ignore[attr-defined]
)
@@ -269,13 +256,13 @@ def __getitem__(self, key):
return self._gotitem(list(key), ndim=2)
elif not getattr(self, "as_index", False):
- # error: "SelectionMixin" has no attribute "obj" [attr-defined]
+ # error: "SelectionMixin" has no attribute "obj"
if key not in self.obj.columns: # type: ignore[attr-defined]
raise KeyError(f"Column not found: {key}")
return self._gotitem(key, ndim=2)
else:
- # error: "SelectionMixin" has no attribute "obj" [attr-defined]
+ # error: "SelectionMixin" has no attribute "obj"
if key not in self.obj: # type: ignore[attr-defined]
raise KeyError(f"Column not found: {key}")
return self._gotitem(key, ndim=1)
@@ -601,8 +588,7 @@ def to_numpy(
dtype='datetime64[ns]')
"""
if is_extension_array_dtype(self.dtype):
- # pandas\core\base.py:837: error: Too many arguments for "to_numpy"
- # of "ExtensionArray" [call-arg]
+ # error: Too many arguments for "to_numpy" of "ExtensionArray"
return self.array.to_numpy( # type: ignore[call-arg]
dtype, copy=copy, na_value=na_value, **kwargs
)
@@ -914,13 +900,11 @@ def _map_values(self, mapper, na_action=None):
# use the built in categorical series mapper which saves
# time by mapping the categories instead of all values
- # pandas\core\base.py:893: error: Incompatible types in
- # assignment (expression has type "Categorical", variable has
- # type "IndexOpsMixin") [assignment]
+ # error: Incompatible types in assignment (expression has type
+ # "Categorical", variable has type "IndexOpsMixin")
self = cast("Categorical", self) # type: ignore[assignment]
- # pandas\core\base.py:894: error: Item "ExtensionArray" of
- # "Union[ExtensionArray, Any]" has no attribute "map"
- # [union-attr]
+ # error: Item "ExtensionArray" of "Union[ExtensionArray, Any]" has no
+ # attribute "map"
return self._values.map(mapper) # type: ignore[union-attr]
values = self._values
@@ -938,8 +922,7 @@ def _map_values(self, mapper, na_action=None):
raise NotImplementedError
map_f = lambda values, f: values.map(f)
else:
- # pandas\core\base.py:1142: error: "IndexOpsMixin" has no attribute
- # "astype" [attr-defined]
+ # error: "IndexOpsMixin" has no attribute "astype"
values = self.astype(object)._values # type: ignore[attr-defined]
if na_action == "ignore":
map_f = lambda values, f: lib.map_infer_mask(
@@ -1177,8 +1160,7 @@ def memory_usage(self, deep=False):
are not components of the array if deep=False or if used on PyPy
"""
if hasattr(self.array, "memory_usage"):
- # pandas\core\base.py:1379: error: "ExtensionArray" has no
- # attribute "memory_usage" [attr-defined]
+ # error: "ExtensionArray" has no attribute "memory_usage"
return self.array.memory_usage(deep=deep) # type: ignore[attr-defined]
v = self.array.nbytes
@@ -1313,8 +1295,7 @@ def searchsorted(self, value, side="left", sorter=None) -> np.ndarray:
def drop_duplicates(self, keep="first"):
duplicated = self.duplicated(keep=keep)
- # pandas\core\base.py:1507: error: Value of type "IndexOpsMixin" is not
- # indexable [index]
+ # error: Value of type "IndexOpsMixin" is not indexable
return self[~duplicated] # type: ignore[index]
def duplicated(self, keep="first"):
diff --git a/pandas/core/common.py b/pandas/core/common.py
index aa24e12bf2cf1..89ba33da92661 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -268,10 +268,6 @@ def maybe_iterable_to_list(obj: Union[Iterable[T], T]) -> Union[Collection[T], T
"""
if isinstance(obj, abc.Iterable) and not isinstance(obj, abc.Sized):
return list(obj)
- # error: Incompatible return value type (got
- # "Union[pandas.core.common.<subclass of "Iterable" and "Sized">,
- # pandas.core.common.<subclass of "Iterable" and "Sized">1, T]", expected
- # "Union[Collection[T], T]") [return-value]
obj = cast(Collection, obj)
return obj
diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py
index babf8116a5588..ee91ab4a282cf 100644
--- a/pandas/core/computation/expr.py
+++ b/pandas/core/computation/expr.py
@@ -659,8 +659,7 @@ def visit_Call(self, node, side=None, **kwargs):
raise
if res is None:
- # pandas\core\computation\expr.py:663: error: "expr" has no
- # attribute "id" [attr-defined]
+ # error: "expr" has no attribute "id"
raise ValueError(
f"Invalid function call {node.func.id}" # type: ignore[attr-defined]
)
@@ -684,8 +683,7 @@ def visit_Call(self, node, side=None, **kwargs):
for key in node.keywords:
if not isinstance(key, ast.keyword):
- # pandas\core\computation\expr.py:684: error: "expr" has no
- # attribute "id" [attr-defined]
+ # error: "expr" has no attribute "id"
raise ValueError(
"keyword error in function call " # type: ignore[attr-defined]
f"'{node.func.id}'"
diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py
index 7b42b21cadc1f..e8eae710623c5 100644
--- a/pandas/core/computation/ops.py
+++ b/pandas/core/computation/ops.py
@@ -71,8 +71,7 @@ def __init__(self, name: str, is_local: Optional[bool] = None):
class Term:
def __new__(cls, name, env, side=None, encoding=None):
klass = Constant if not isinstance(name, str) else cls
- # pandas\core\computation\ops.py:72: error: Argument 2 for "super" not
- # an instance of argument 1 [misc]
+ # error: Argument 2 for "super" not an instance of argument 1
supr_new = super(Term, klass).__new__ # type: ignore[misc]
return supr_new(klass)
@@ -593,7 +592,7 @@ def __init__(self, func, args):
self.func = func
def __call__(self, env):
- # pandas\core\computation\ops.py:592: error: "Op" not callable [operator]
+ # error: "Op" not callable
operands = [op(env) for op in self.operands] # type: ignore[operator]
with np.errstate(all="ignore"):
return self.func.func(*operands)
diff --git a/pandas/core/computation/scope.py b/pandas/core/computation/scope.py
index c2ba7f9892ef0..71d725051977f 100644
--- a/pandas/core/computation/scope.py
+++ b/pandas/core/computation/scope.py
@@ -131,17 +131,14 @@ def __init__(
# scope when we align terms (alignment accesses the underlying
# numpy array of pandas objects)
- # pandas\core\computation\scope.py:132: error: Incompatible types
- # in assignment (expression has type "ChainMap[str, Any]", variable
- # has type "DeepChainMap[str, Any]") [assignment]
+ # error: Incompatible types in assignment (expression has type
+ # "ChainMap[str, Any]", variable has type "DeepChainMap[str, Any]")
self.scope = self.scope.new_child( # type: ignore[assignment]
(global_dict or frame.f_globals).copy()
)
if not isinstance(local_dict, Scope):
- # pandas\core\computation\scope.py:134: error: Incompatible
- # types in assignment (expression has type "ChainMap[str,
- # Any]", variable has type "DeepChainMap[str, Any]")
- # [assignment]
+ # error: Incompatible types in assignment (expression has type
+ # "ChainMap[str, Any]", variable has type "DeepChainMap[str, Any]")
self.scope = self.scope.new_child( # type: ignore[assignment]
(local_dict or frame.f_locals).copy()
)
@@ -150,8 +147,7 @@ def __init__(
# assumes that resolvers are going from outermost scope to inner
if isinstance(local_dict, Scope):
- # pandas\core\computation\scope.py:140: error: Cannot determine
- # type of 'resolvers' [has-type]
+ # error: Cannot determine type of 'resolvers'
resolvers += tuple(local_dict.resolvers.maps) # type: ignore[has-type]
self.resolvers = DeepChainMap(*resolvers)
self.temps = {}
@@ -239,8 +235,7 @@ def swapkey(self, old_key: str, new_key: str, new_value=None):
for mapping in maps:
if old_key in mapping:
- # pandas\core\computation\scope.py:228: error: Unsupported
- # target for indexed assignment ("Mapping[Any, Any]") [index]
+ # error: Unsupported target for indexed assignment ("Mapping[Any, Any]")
mapping[new_key] = new_value # type: ignore[index]
return
@@ -260,10 +255,8 @@ def _get_vars(self, stack, scopes: List[str]):
for scope, (frame, _, _, _, _, _) in variables:
try:
d = getattr(frame, "f_" + scope)
- # pandas\core\computation\scope.py:247: error: Incompatible
- # types in assignment (expression has type "ChainMap[str,
- # Any]", variable has type "DeepChainMap[str, Any]")
- # [assignment]
+ # error: Incompatible types in assignment (expression has type
+ # "ChainMap[str, Any]", variable has type "DeepChainMap[str, Any]")
self.scope = self.scope.new_child(d) # type: ignore[assignment]
finally:
# won't remove it, but DECREF it
@@ -331,13 +324,10 @@ def full_scope(self):
vars : DeepChainMap
All variables in this scope.
"""
- # pandas\core\computation\scope.py:314: error: Unsupported operand
- # types for + ("List[Dict[Any, Any]]" and "List[Mapping[Any, Any]]")
- # [operator]
-
- # pandas\core\computation\scope.py:314: error: Unsupported operand
- # types for + ("List[Dict[Any, Any]]" and "List[Mapping[str, Any]]")
- # [operator]
+ # error: Unsupported operand types for + ("List[Dict[Any, Any]]" and
+ # "List[Mapping[Any, Any]]")
+ # error: Unsupported operand types for + ("List[Dict[Any, Any]]" and
+ # "List[Mapping[str, Any]]")
maps = (
[self.temps]
+ self.resolvers.maps # type: ignore[operator]
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 63d238da12101..f6db5d40c8409 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1163,8 +1163,8 @@ def __len__(self) -> int:
"""
return len(self.index)
- # pandas/core/frame.py:1146: error: Overloaded function signatures 1 and 2
- # overlap with incompatible return types [misc]
+ # error: Overloaded function signatures 1 and 2 overlap with incompatible return
+ # types
@overload
def dot(self, other: Series) -> Series: # type: ignore[misc]
...
@@ -4822,8 +4822,8 @@ def set_index(
elif isinstance(col, (Index, Series)):
# if Index then not MultiIndex (treated above)
- # error: Argument 1 to "append" of "list" has incompatible
- # type "Union[Index, Series]"; expected "Index" [arg-type]
+ # error: Argument 1 to "append" of "list" has incompatible type
+ # "Union[Index, Series]"; expected "Index"
arrays.append(col) # type:ignore[arg-type]
names.append(col.name)
elif isinstance(col, (list, np.ndarray)):
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index ec37da66760c3..6413489a74ae6 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -10530,8 +10530,7 @@ def _add_numeric_operations(cls):
def any(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs):
return NDFrame.any(self, axis, bool_only, skipna, level, **kwargs)
- # pandas\core\generic.py:10725: error: Cannot assign to a method
- # [assignment]
+ # error: Cannot assign to a method
cls.any = any # type: ignore[assignment]
@doc(
@@ -10547,13 +10546,11 @@ def any(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs):
def all(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs):
return NDFrame.all(self, axis, bool_only, skipna, level, **kwargs)
- # pandas\core\generic.py:10719: error: Cannot assign to a method
- # [assignment]
+ # error: Cannot assign to a method
- # pandas\core\generic.py:10719: error: Incompatible types in assignment
- # (expression has type "Callable[[Iterable[object]], bool]", variable
- # has type "Callable[[NDFrame, Any, Any, Any, Any, KwArg(Any)], Any]")
- # [assignment]
+ # error: Incompatible types in assignment (expression has type
+ # "Callable[[Iterable[object]], bool]", variable has type "Callable[[NDFrame,
+ # Any, Any, Any, Any, KwArg(Any)], Any]")
cls.all = all # type: ignore[assignment]
# error: Argument 1 to "doc" has incompatible type "Optional[str]"; expected
@@ -10571,8 +10568,7 @@ def all(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs):
def mad(self, axis=None, skipna=None, level=None):
return NDFrame.mad(self, axis, skipna, level)
- # pandas\core\generic.py:10736: error: Cannot assign to a method
- # [assignment]
+ # error: Cannot assign to a method
cls.mad = mad # type: ignore[assignment]
@doc(
@@ -10595,8 +10591,7 @@ def sem(
):
return NDFrame.sem(self, axis, skipna, level, ddof, numeric_only, **kwargs)
- # pandas\core\generic.py:10758: error: Cannot assign to a method
- # [assignment]
+ # error: Cannot assign to a method
cls.sem = sem # type: ignore[assignment]
@doc(
@@ -10618,8 +10613,7 @@ def var(
):
return NDFrame.var(self, axis, skipna, level, ddof, numeric_only, **kwargs)
- # pandas\core\generic.py:10779: error: Cannot assign to a method
- # [assignment]
+ # error: Cannot assign to a method
cls.var = var # type: ignore[assignment]
@doc(
@@ -10642,8 +10636,7 @@ def std(
):
return NDFrame.std(self, axis, skipna, level, ddof, numeric_only, **kwargs)
- # pandas\core\generic.py:10801: error: Cannot assign to a method
- # [assignment]
+ # error: Cannot assign to a method
cls.std = std # type: ignore[assignment]
@doc(
@@ -10658,8 +10651,7 @@ def std(
def cummin(self, axis=None, skipna=True, *args, **kwargs):
return NDFrame.cummin(self, axis, skipna, *args, **kwargs)
- # pandas\core\generic.py:10815: error: Cannot assign to a method
- # [assignment]
+ # error: Cannot assign to a method
cls.cummin = cummin # type: ignore[assignment]
@doc(
@@ -10674,8 +10666,7 @@ def cummin(self, axis=None, skipna=True, *args, **kwargs):
def cummax(self, axis=None, skipna=True, *args, **kwargs):
return NDFrame.cummax(self, axis, skipna, *args, **kwargs)
- # pandas\core\generic.py:10829: error: Cannot assign to a method
- # [assignment]
+ # error: Cannot assign to a method
cls.cummax = cummax # type: ignore[assignment]
@doc(
@@ -10690,8 +10681,7 @@ def cummax(self, axis=None, skipna=True, *args, **kwargs):
def cumsum(self, axis=None, skipna=True, *args, **kwargs):
return NDFrame.cumsum(self, axis, skipna, *args, **kwargs)
- # pandas\core\generic.py:10843: error: Cannot assign to a method
- # [assignment]
+ # error: Cannot assign to a method
cls.cumsum = cumsum # type: ignore[assignment]
@doc(
@@ -10706,8 +10696,7 @@ def cumsum(self, axis=None, skipna=True, *args, **kwargs):
def cumprod(self, axis=None, skipna=True, *args, **kwargs):
return NDFrame.cumprod(self, axis, skipna, *args, **kwargs)
- # pandas\core\generic.py:10857: error: Cannot assign to a method
- # [assignment]
+ # error: Cannot assign to a method
cls.cumprod = cumprod # type: ignore[assignment]
@doc(
@@ -10734,8 +10723,7 @@ def sum(
self, axis, skipna, level, numeric_only, min_count, **kwargs
)
- # pandas\core\generic.py:10883: error: Cannot assign to a method
- # [assignment]
+ # error: Cannot assign to a method
cls.sum = sum # type: ignore[assignment]
@doc(
@@ -10761,8 +10749,7 @@ def prod(
self, axis, skipna, level, numeric_only, min_count, **kwargs
)
- # pandas\core\generic.py:10908: error: Cannot assign to a method
- # [assignment]
+ # error: Cannot assign to a method
cls.prod = prod # type: ignore[assignment]
cls.product = prod
@@ -10779,8 +10766,7 @@ def prod(
def mean(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs):
return NDFrame.mean(self, axis, skipna, level, numeric_only, **kwargs)
- # pandas\core\generic.py:10924: error: Cannot assign to a method
- # [assignment]
+ # error: Cannot assign to a method
cls.mean = mean # type: ignore[assignment]
@doc(
@@ -10796,8 +10782,7 @@ def mean(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs):
def skew(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs):
return NDFrame.skew(self, axis, skipna, level, numeric_only, **kwargs)
- # pandas\core\generic.py:10939: error: Cannot assign to a method
- # [assignment]
+ # error: Cannot assign to a method
cls.skew = skew # type: ignore[assignment]
@doc(
@@ -10816,8 +10801,7 @@ def skew(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs):
def kurt(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs):
return NDFrame.kurt(self, axis, skipna, level, numeric_only, **kwargs)
- # pandas\core\generic.py:10957: error: Cannot assign to a method
- # [assignment]
+ # error: Cannot assign to a method
cls.kurt = kurt # type: ignore[assignment]
cls.kurtosis = kurt
@@ -10836,8 +10820,7 @@ def median(
):
return NDFrame.median(self, axis, skipna, level, numeric_only, **kwargs)
- # pandas\core\generic.py:10975: error: Cannot assign to a method
- # [assignment]
+ # error: Cannot assign to a method
cls.median = median # type: ignore[assignment]
@doc(
@@ -10855,8 +10838,7 @@ def median(
def max(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs):
return NDFrame.max(self, axis, skipna, level, numeric_only, **kwargs)
- # pandas\core\generic.py:10992: error: Cannot assign to a method
- # [assignment]
+ # error: Cannot assign to a method
cls.max = max # type: ignore[assignment]
@doc(
@@ -10874,8 +10856,7 @@ def max(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs):
def min(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs):
return NDFrame.min(self, axis, skipna, level, numeric_only, **kwargs)
- # pandas\core\generic.py:11009: error: Cannot assign to a method
- # [assignment]
+ # error: Cannot assign to a method
cls.min = min # type: ignore[assignment]
@final
diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py
index 594c5899209df..9f1446b359f66 100644
--- a/pandas/core/groupby/base.py
+++ b/pandas/core/groupby/base.py
@@ -57,8 +57,7 @@ def _gotitem(self, key, ndim, subset=None):
"""
# create a new object to prevent aliasing
if subset is None:
- # pandas\core\groupby\base.py:52: error: "GotItemMixin" has no
- # attribute "obj" [attr-defined]
+ # error: "GotItemMixin" has no attribute "obj"
subset = self.obj # type: ignore[attr-defined]
# we need to make a shallow copy of ourselves
@@ -70,22 +69,15 @@ def _gotitem(self, key, ndim, subset=None):
# Try to select from a DataFrame, falling back to a Series
try:
- # pandas\core\groupby\base.py:60: error: "GotItemMixin" has no
- # attribute "_groupby" [attr-defined]
+ # error: "GotItemMixin" has no attribute "_groupby"
groupby = self._groupby[key] # type: ignore[attr-defined]
except IndexError:
- # pandas\core\groupby\base.py:62: error: "GotItemMixin" has no
- # attribute "_groupby" [attr-defined]
+ # error: "GotItemMixin" has no attribute "_groupby"
groupby = self._groupby # type: ignore[attr-defined]
- # pandas\core\groupby\base.py:64: error: Too many arguments for
- # "GotItemMixin" [call-arg]
-
- # pandas\core\groupby\base.py:64: error: Unexpected keyword argument
- # "groupby" for "GotItemMixin" [call-arg]
-
- # pandas\core\groupby\base.py:64: error: Unexpected keyword argument
- # "parent" for "GotItemMixin" [call-arg]
+ # error: Too many arguments for "GotItemMixin"
+ # error: Unexpected keyword argument "groupby" for "GotItemMixin"
+ # error: Unexpected keyword argument "parent" for "GotItemMixin"
self = type(self)(
subset, groupby=groupby, parent=self, **kwargs # type: ignore[call-arg]
)
diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py
index c7dc6d021a4c3..6a789bc26cabc 100644
--- a/pandas/core/groupby/grouper.py
+++ b/pandas/core/groupby/grouper.py
@@ -281,9 +281,8 @@ def _get_grouper(self, obj, validate: bool = True):
a tuple of binner, grouper, obj (possibly sorted)
"""
self._set_grouper(obj)
- # pandas\core\groupby\grouper.py:310: error: Value of type variable
- # "FrameOrSeries" of "get_grouper" cannot be "Optional[Any]"
- # [type-var]
+ # error: Value of type variable "FrameOrSeries" of "get_grouper" cannot be
+ # "Optional[Any]"
self.grouper, _, self.obj = get_grouper( # type: ignore[type-var]
self.obj,
[self.key],
@@ -370,8 +369,7 @@ def _set_grouper(self, obj: FrameOrSeries, sort: bool = False):
@final
@property
def groups(self):
- # pandas\core\groupby\grouper.py:382: error: Item "None" of
- # "Optional[Any]" has no attribute "groups" [union-attr]
+ # error: Item "None" of "Optional[Any]" has no attribute "groups"
return self.grouper.groups # type: ignore[union-attr]
@final
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 789ca04b894cd..f12a4fd382e7a 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -6071,14 +6071,14 @@ def ensure_index(
if hasattr(index_like, "name"):
# https://github.com/python/mypy/issues/1424
# error: Item "ExtensionArray" of "Union[ExtensionArray,
- # Sequence[Any]]" has no attribute "name" [union-attr]
+ # Sequence[Any]]" has no attribute "name"
# error: Item "Sequence[Any]" of "Union[ExtensionArray, Sequence[Any]]"
- # has no attribute "name" [union-attr]
- # error: "Sequence[Any]" has no attribute "name" [attr-defined]
+ # has no attribute "name"
+ # error: "Sequence[Any]" has no attribute "name"
# error: Item "Sequence[Any]" of "Union[Series, Sequence[Any]]" has no
- # attribute "name" [union-attr]
+ # attribute "name"
# error: Item "Sequence[Any]" of "Union[Any, Sequence[Any]]" has no
- # attribute "name" [union-attr]
+ # attribute "name"
name = index_like.name # type: ignore[union-attr, attr-defined]
return Index(index_like, name=name, copy=copy)
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index 265170dd28a3b..7e6d7d911b065 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -318,8 +318,7 @@ def _format_attrs(self):
"categories",
ibase.default_pprint(self.categories, max_seq_items=max_categories),
),
- # pandas\core\indexes\category.py:315: error: "CategoricalIndex"
- # has no attribute "ordered" [attr-defined]
+ # error: "CategoricalIndex" has no attribute "ordered"
("ordered", self.ordered), # type: ignore[attr-defined]
]
if self.name is not None:
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index 00f47c0aaf538..2e6519a3b73ad 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -714,7 +714,7 @@ def _intersection(self, other: Index, sort=False) -> Index:
left_chunk = left._values[lslice]
# error: Argument 1 to "_simple_new" of "DatetimeIndexOpsMixin" has
# incompatible type "Union[ExtensionArray, Any]"; expected
- # "Union[DatetimeArray, TimedeltaArray, PeriodArray]" [arg-type]
+ # "Union[DatetimeArray, TimedeltaArray, PeriodArray]"
result = type(self)._simple_new(left_chunk) # type: ignore[arg-type]
return self._wrap_setop_result(other, result)
diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py
index ea3678a7e15d9..a0e783a74df3c 100644
--- a/pandas/core/indexes/extension.py
+++ b/pandas/core/indexes/extension.py
@@ -226,8 +226,8 @@ def __getitem__(self, key):
if result.ndim == 1:
return type(self)(result, name=self.name)
# Unpack to ndarray for MPL compat
- # pandas\core\indexes\extension.py:220: error: "ExtensionArray" has
- # no attribute "_data" [attr-defined]
+
+ # error: "ExtensionArray" has no attribute "_data"
result = result._data # type: ignore[attr-defined]
# Includes cases where we get a 2D ndarray back for MPL compat
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 26d59db1b08fd..1fdffcf8e5980 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -1448,8 +1448,7 @@ def _set_names(self, names, level=None, validate=True):
raise TypeError(
f"{type(self).__name__}.name must be a hashable type"
)
- # pandas\core\indexes\multi.py:1448: error: Cannot determine type
- # of '__setitem__' [has-type]
+ # error: Cannot determine type of '__setitem__'
self._names[lev] = name # type: ignore[has-type]
# If .levels has been accessed, the names in our cache will be stale.
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py
index a9561cc477d4a..9664f41362c8a 100644
--- a/pandas/core/indexes/period.py
+++ b/pandas/core/indexes/period.py
@@ -166,21 +166,21 @@ def to_timestamp(self, freq=None, how="start") -> DatetimeIndex:
return DatetimeIndex._simple_new(arr, name=self.name)
# https://github.com/python/mypy/issues/1362
- # error: Decorated property not supported [misc]
+ # error: Decorated property not supported
@property # type:ignore[misc]
@doc(PeriodArray.hour.fget)
def hour(self) -> Int64Index:
return Int64Index(self._data.hour, name=self.name)
# https://github.com/python/mypy/issues/1362
- # error: Decorated property not supported [misc]
+ # error: Decorated property not supported
@property # type:ignore[misc]
@doc(PeriodArray.minute.fget)
def minute(self) -> Int64Index:
return Int64Index(self._data.minute, name=self.name)
# https://github.com/python/mypy/issues/1362
- # error: Decorated property not supported [misc]
+ # error: Decorated property not supported
@property # type:ignore[misc]
@doc(PeriodArray.second.fget)
def second(self) -> Int64Index:
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 8ba6018e743bb..3c27e34dcbcf6 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -2475,6 +2475,7 @@ def _block_shape(values: ArrayLike, ndim: int = 1) -> ArrayLike:
# TODO(EA2D): https://github.com/pandas-dev/pandas/issues/23023
# block.shape is incorrect for "2D" ExtensionArrays
# We can't, and don't need to, reshape.
+
# error: "ExtensionArray" has no attribute "reshape"
values = values.reshape(tuple((1,) + shape)) # type: ignore[attr-defined]
return values
diff --git a/pandas/core/resample.py b/pandas/core/resample.py
index 68f791ac0a837..767dd312bb7df 100644
--- a/pandas/core/resample.py
+++ b/pandas/core/resample.py
@@ -96,9 +96,8 @@ def __init__(self, obj, groupby=None, axis=0, kind=None, **kwargs):
self.as_index = True
self.exclusions = set()
self.binner = None
- # pandas\core\resample.py:96: error: Incompatible types in assignment
- # (expression has type "None", variable has type "BaseGrouper")
- # [assignment]
+ # error: Incompatible types in assignment (expression has type "None", variable
+ # has type "BaseGrouper")
self.grouper = None # type: ignore[assignment]
if self.groupby is not None:
@@ -419,8 +418,7 @@ def _apply_loffset(self, result):
result : Series or DataFrame
the result of resample
"""
- # pandas\core\resample.py:409: error: Cannot determine type of
- # 'loffset' [has-type]
+ # error: Cannot determine type of 'loffset'
needs_offset = (
isinstance(
self.loffset, # type: ignore[has-type]
@@ -431,8 +429,7 @@ def _apply_loffset(self, result):
)
if needs_offset:
- # pandas\core\resample.py:415: error: Cannot determine type of
- # 'loffset' [has-type]
+ # error: Cannot determine type of 'loffset'
result.index = result.index + self.loffset # type: ignore[has-type]
self.loffset = None
@@ -869,8 +866,7 @@ def std(self, ddof=1, *args, **kwargs):
Standard deviation of values within each group.
"""
nv.validate_resampler_func("std", args, kwargs)
- # pandas\core\resample.py:850: error: Unexpected keyword argument
- # "ddof" for "_downsample" [call-arg]
+ # error: Unexpected keyword argument "ddof" for "_downsample"
return self._downsample("std", ddof=ddof) # type: ignore[call-arg]
def var(self, ddof=1, *args, **kwargs):
@@ -888,8 +884,7 @@ def var(self, ddof=1, *args, **kwargs):
Variance of values within each group.
"""
nv.validate_resampler_func("var", args, kwargs)
- # pandas\core\resample.py:867: error: Unexpected keyword argument
- # "ddof" for "_downsample" [call-arg]
+ # error: Unexpected keyword argument "ddof" for "_downsample"
return self._downsample("var", ddof=ddof) # type: ignore[call-arg]
@doc(GroupBy.size)
@@ -948,11 +943,8 @@ def quantile(self, q=0.5, **kwargs):
Return a DataFrame, where the coulmns are groupby columns,
and the values are its quantiles.
"""
- # pandas\core\resample.py:920: error: Unexpected keyword argument "q"
- # for "_downsample" [call-arg]
-
- # pandas\core\resample.py:920: error: Too many arguments for
- # "_downsample" [call-arg]
+ # error: Unexpected keyword argument "q" for "_downsample"
+ # error: Too many arguments for "_downsample"
return self._downsample("quantile", q=q, **kwargs) # type: ignore[call-arg]
@@ -1005,8 +997,7 @@ def __init__(self, obj, *args, **kwargs):
for attr in self._attributes:
setattr(self, attr, kwargs.get(attr, getattr(parent, attr)))
- # pandas\core\resample.py:972: error: Too many arguments for "__init__"
- # of "object" [call-arg]
+ # error: Too many arguments for "__init__" of "object"
super().__init__(None) # type: ignore[call-arg]
self._groupby = groupby
self._groupby.mutated = True
@@ -1070,8 +1061,8 @@ def _downsample(self, how, **kwargs):
return obj
# do we have a regular frequency
- # pandas\core\resample.py:1037: error: "BaseGrouper" has no
- # attribute "binlabels" [attr-defined]
+
+ # error: "BaseGrouper" has no attribute "binlabels"
if (
(ax.freq is not None or ax.inferred_freq is not None)
and len(self.grouper.binlabels) > len(ax) # type: ignore[attr-defined]
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 8704d757c3289..963d071dc2768 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -996,9 +996,8 @@ def _get_merge_keys(self):
"""
left_keys = []
right_keys = []
- # pandas\core\reshape\merge.py:966: error: Need type annotation for
- # 'join_names' (hint: "join_names: List[<type>] = ...")
- # [var-annotated]
+ # error: Need type annotation for 'join_names' (hint: "join_names: List[<type>]
+ # = ...")
join_names = [] # type: ignore[var-annotated]
right_drop = []
left_drop = []
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index f12a530ea6c34..8902d45144c56 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -893,8 +893,8 @@ def check_extension(cls, ext: str):
"""
if ext.startswith("."):
ext = ext[1:]
- # error: "Callable[[ExcelWriter], Any]" has no attribute "__iter__"
- # (not iterable) [attr-defined]
+ # error: "Callable[[ExcelWriter], Any]" has no attribute "__iter__" (not
+ # iterable)
if not any(
ext in extension
for extension in cls.supported_extensions # type: ignore[attr-defined]
diff --git a/pandas/io/formats/console.py b/pandas/io/formats/console.py
index ea291bcbfa44c..bdd2b3d6e4c6a 100644
--- a/pandas/io/formats/console.py
+++ b/pandas/io/formats/console.py
@@ -69,8 +69,7 @@ def check_main():
return not hasattr(main, "__file__") or get_option("mode.sim_interactive")
try:
- # pandas\io\formats\console.py:72: error: Name '__IPYTHON__' is not
- # defined [name-defined]
+ # error: Name '__IPYTHON__' is not defined
return __IPYTHON__ or check_main() # type: ignore[name-defined]
except NameError:
return check_main()
@@ -85,8 +84,7 @@ def in_ipython_frontend():
bool
"""
try:
- # pandas\io\formats\console.py:86: error: Name 'get_ipython' is not
- # defined [name-defined]
+ # error: Name 'get_ipython' is not defined
ip = get_ipython() # type: ignore[name-defined]
return "zmq" in str(type(ip)).lower()
except NameError:
diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py
index b027d8139f24b..13126c2fa7b06 100644
--- a/pandas/io/formats/excel.py
+++ b/pandas/io/formats/excel.py
@@ -613,9 +613,8 @@ def _format_header(self) -> Iterable[ExcelCell]:
""
] * len(self.columns)
if reduce(lambda x, y: x and y, map(lambda x: x != "", row)):
- # pandas\io\formats\excel.py:618: error: Incompatible types in
- # assignment (expression has type "Generator[ExcelCell, None,
- # None]", variable has type "Tuple[]") [assignment]
+ # error: Incompatible types in assignment (expression has type
+ # "Generator[ExcelCell, None, None]", variable has type "Tuple[]")
gen2 = ( # type: ignore[assignment]
ExcelCell(self.rowcounter, colindex, val, self.header_style)
for colindex, val in enumerate(row)
@@ -819,9 +818,8 @@ def write(
if isinstance(writer, ExcelWriter):
need_save = False
else:
- # pandas\io\formats\excel.py:808: error: Cannot instantiate
- # abstract class 'ExcelWriter' with abstract attributes 'engine',
- # 'save', 'supported_extensions' and 'write_cells' [abstract]
+ # error: Cannot instantiate abstract class 'ExcelWriter' with abstract
+ # attributes 'engine', 'save', 'supported_extensions' and 'write_cells'
writer = ExcelWriter( # type: ignore[abstract]
writer, engine=engine, storage_options=storage_options
)
diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py
index 05d94366e6623..48b2fae8c6de5 100644
--- a/pandas/io/formats/format.py
+++ b/pandas/io/formats/format.py
@@ -1347,11 +1347,9 @@ def _value_formatter(
def base_formatter(v):
assert float_format is not None # for mypy
- # pandas\io\formats\format.py:1411: error: "str" not callable
- # [operator]
-
- # pandas\io\formats\format.py:1411: error: Unexpected keyword
- # argument "value" for "__call__" of "EngFormatter" [call-arg]
+ # error: "str" not callable
+ # error: Unexpected keyword argument "value" for "__call__" of
+ # "EngFormatter"
return (
float_format(value=v) # type: ignore[operator,call-arg]
if notna(v)
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index 735fb345363c7..22e21761fa303 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -1740,8 +1740,8 @@ def from_custom_template(cls, searchpath, name):
loader = jinja2.ChoiceLoader([jinja2.FileSystemLoader(searchpath), cls.loader])
# mypy doesn't like dynamically-defined classes
- # error: Variable "cls" is not valid as a type [valid-type]
- # error: Invalid base class "cls" [misc]
+ # error: Variable "cls" is not valid as a type
+ # error: Invalid base class "cls"
class MyStyler(cls): # type:ignore[valid-type,misc]
env = jinja2.Environment(loader=loader)
template = env.get_template(name)
diff --git a/pandas/io/parsers/c_parser_wrapper.py b/pandas/io/parsers/c_parser_wrapper.py
index d1d77c5e044be..27f06dc84a275 100644
--- a/pandas/io/parsers/c_parser_wrapper.py
+++ b/pandas/io/parsers/c_parser_wrapper.py
@@ -25,29 +25,23 @@ def __init__(self, src: FilePathOrBuffer, **kwds):
for key in ("storage_options", "encoding", "memory_map", "compression"):
kwds.pop(key, None)
if self.handles.is_mmap and hasattr(self.handles.handle, "mmap"):
- # pandas\io\parsers.py:1861: error: Item "IO[Any]" of
- # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase,
- # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr]
+ # error: Item "IO[Any]" of "Union[IO[Any], RawIOBase, BufferedIOBase,
+ # TextIOBase, TextIOWrapper, mmap]" has no attribute "mmap"
- # pandas\io\parsers.py:1861: error: Item "RawIOBase" of
- # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase,
- # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr]
+ # error: Item "RawIOBase" of "Union[IO[Any], RawIOBase, BufferedIOBase,
+ # TextIOBase, TextIOWrapper, mmap]" has no attribute "mmap"
- # pandas\io\parsers.py:1861: error: Item "BufferedIOBase" of
- # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase,
- # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr]
+ # error: Item "BufferedIOBase" of "Union[IO[Any], RawIOBase, BufferedIOBase,
+ # TextIOBase, TextIOWrapper, mmap]" has no attribute "mmap"
- # pandas\io\parsers.py:1861: error: Item "TextIOBase" of
- # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase,
- # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr]
+ # error: Item "TextIOBase" of "Union[IO[Any], RawIOBase, BufferedIOBase,
+ # TextIOBase, TextIOWrapper, mmap]" has no attribute "mmap"
- # pandas\io\parsers.py:1861: error: Item "TextIOWrapper" of
- # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase,
- # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr]
+ # error: Item "TextIOWrapper" of "Union[IO[Any], RawIOBase, BufferedIOBase,
+ # TextIOBase, TextIOWrapper, mmap]" has no attribute "mmap"
- # pandas\io\parsers.py:1861: error: Item "mmap" of "Union[IO[Any],
- # RawIOBase, BufferedIOBase, TextIOBase, TextIOWrapper, mmap]" has
- # no attribute "mmap" [union-attr]
+ # error: Item "mmap" of "Union[IO[Any], RawIOBase, BufferedIOBase,
+ # TextIOBase, TextIOWrapper, mmap]" has no attribute "mmap"
self.handles.handle = self.handles.handle.mmap # type: ignore[union-attr]
try:
diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py
index 223acdea80ca6..cfd648636753d 100644
--- a/pandas/io/parsers/python_parser.py
+++ b/pandas/io/parsers/python_parser.py
@@ -217,10 +217,9 @@ def _read():
reader = _read()
- # pandas\io\parsers.py:2427: error: Incompatible types in assignment
- # (expression has type "_reader", variable has type "Union[IO[Any],
- # RawIOBase, BufferedIOBase, TextIOBase, TextIOWrapper, mmap, None]")
- # [assignment]
+ # error: Incompatible types in assignment (expression has type "_reader",
+ # variable has type "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase,
+ # TextIOWrapper, mmap, None]")
self.data = reader # type: ignore[assignment]
def read(self, rows=None):
@@ -278,8 +277,7 @@ def _exclude_implicit_index(self, alldata):
# legacy
def get_chunk(self, size=None):
if size is None:
- # pandas\io\parsers.py:2528: error: "PythonParser" has no attribute
- # "chunksize" [attr-defined]
+ # error: "PythonParser" has no attribute "chunksize"
size = self.chunksize # type: ignore[attr-defined]
return self.read(rows=size)
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 8917be1f558b2..077686d9bd642 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -3410,8 +3410,8 @@ def queryables(self) -> Dict[str, Any]:
(v.cname, v) for v in self.values_axes if v.name in set(self.data_columns)
]
- # error: Unsupported operand types for + ("List[Tuple[str, IndexCol]]"
- # and "List[Tuple[str, None]]")
+ # error: Unsupported operand types for + ("List[Tuple[str, IndexCol]]" and
+ # "List[Tuple[str, None]]")
return dict(d1 + d2 + d3) # type: ignore[operator]
def index_cols(self):
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py
index 7d743075674f1..2b6dd5347c3e7 100644
--- a/pandas/plotting/_matplotlib/core.py
+++ b/pandas/plotting/_matplotlib/core.py
@@ -594,17 +594,14 @@ def _make_legend(self):
if self.legend:
if self.legend == "reverse":
- # pandas\plotting\_matplotlib\core.py:578: error:
- # Incompatible types in assignment (expression has type
+ # error: Incompatible types in assignment (expression has type
# "Iterator[Any]", variable has type "List[Any]")
- # [assignment]
self.legend_handles = reversed( # type: ignore[assignment]
self.legend_handles
)
- # pandas\plotting\_matplotlib\core.py:579: error:
- # Incompatible types in assignment (expression has type
+ # error: Incompatible types in assignment (expression has type
# "Iterator[Optional[Hashable]]", variable has type
- # "List[Optional[Hashable]]") [assignment]
+ # "List[Optional[Hashable]]")
self.legend_labels = reversed( # type: ignore[assignment]
self.legend_labels
)
@@ -1149,10 +1146,9 @@ def _make_plot(self):
it = self._iter_data(data=data, keep_index=True)
else:
x = self._get_xticks(convert_period=True)
- # pandas\plotting\_matplotlib\core.py:1100: error: Incompatible
- # types in assignment (expression has type "Callable[[Any, Any,
- # Any, Any, Any, Any, KwArg(Any)], Any]", variable has type
- # "Callable[[Any, Any, Any, Any, KwArg(Any)], Any]") [assignment]
+ # error: Incompatible types in assignment (expression has type
+ # "Callable[[Any, Any, Any, Any, Any, Any, KwArg(Any)], Any]", variable has
+ # type "Callable[[Any, Any, Any, Any, KwArg(Any)], Any]")
plotf = self._plot # type: ignore[assignment]
it = self._iter_data()
@@ -1601,9 +1597,8 @@ def blank_labeler(label, value):
if labels is not None:
blabels = [blank_labeler(left, value) for left, value in zip(labels, y)]
else:
- # pandas\plotting\_matplotlib\core.py:1546: error: Incompatible
- # types in assignment (expression has type "None", variable has
- # type "List[Any]") [assignment]
+ # error: Incompatible types in assignment (expression has type "None",
+ # variable has type "List[Any]")
blabels = None # type: ignore[assignment]
results = ax.pie(y, labels=blabels, **kwds)
diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py
index 58f44104b99d6..e0a860b9d8709 100644
--- a/pandas/plotting/_misc.py
+++ b/pandas/plotting/_misc.py
@@ -530,8 +530,7 @@ def reset(self):
-------
None
"""
- # pandas\plotting\_misc.py:533: error: Cannot access "__init__"
- # directly [misc]
+ # error: Cannot access "__init__" directly
self.__init__() # type: ignore[misc]
def _get_canonical_key(self, key):
diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py
index 0a50ef2831534..3203b7fa1893d 100644
--- a/pandas/tests/internals/test_internals.py
+++ b/pandas/tests/internals/test_internals.py
@@ -1233,8 +1233,8 @@ def check_frame_setitem(self, elem, index: Index, inplace: bool):
if inplace:
# assertion here implies setting was done inplace
- # error: Item "ArrayManager" of "Union[ArrayManager, BlockManager]"
- # has no attribute "blocks" [union-attr]
+ # error: Item "ArrayManager" of "Union[ArrayManager, BlockManager]" has no
+ # attribute "blocks"
assert df._mgr.blocks[0].values is arr # type:ignore[union-attr]
else:
assert df.dtypes[0] == object
diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py
index a13fb1ce57f6c..268c636ab9353 100644
--- a/pandas/util/_decorators.py
+++ b/pandas/util/_decorators.py
@@ -78,8 +78,8 @@ def wrapper(*args, **kwargs) -> Callable[..., Any]:
{dedent(doc)}"""
)
- # error: Incompatible return value type (got "Callable[[VarArg(Any),
- # KwArg(Any)], Callable[...,Any]]", expected "Callable[[F], F]")
+ # error: Incompatible return value type (got "Callable[[VarArg(Any), KwArg(Any)],
+ # Callable[...,Any]]", expected "Callable[[F], F]")
return wrapper # type: ignore[return-value]
@@ -362,10 +362,10 @@ def decorator(decorated: F) -> F:
for docstring in docstrings:
if hasattr(docstring, "_docstring_components"):
- # error: Item "str" of "Union[str, Callable[..., Any]]" has no
- # attribute "_docstring_components" [union-attr]
- # error: Item "function" of "Union[str, Callable[..., Any]]"
- # has no attribute "_docstring_components" [union-attr]
+ # error: Item "str" of "Union[str, Callable[..., Any]]" has no attribute
+ # "_docstring_components"
+ # error: Item "function" of "Union[str, Callable[..., Any]]" has no
+ # attribute "_docstring_components"
docstring_components.extend(
docstring._docstring_components # type: ignore[union-attr]
)
| follow-up to #37556 | https://api.github.com/repos/pandas-dev/pandas/pulls/39794 | 2021-02-13T14:59:28Z | 2021-02-15T15:42:46Z | 2021-02-15T15:42:46Z | 2021-02-16T09:58:29Z |
CLN: Better method of determining read-only status of openpyxl worksheet | diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py
index 3a753a707166e..d0fe64a82d187 100644
--- a/pandas/io/excel/_openpyxl.py
+++ b/pandas/io/excel/_openpyxl.py
@@ -538,11 +538,7 @@ def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]:
version = LooseVersion(get_version(openpyxl))
- # There is no good way of determining if a sheet is read-only
- # https://foss.heptapod.net/openpyxl/openpyxl/-/issues/1605
- is_readonly = hasattr(sheet, "reset_dimensions")
-
- if version >= "3.0.0" and is_readonly:
+ if version >= "3.0.0" and self.book.read_only:
sheet.reset_dimensions()
data: List[List[Scalar]] = []
@@ -556,7 +552,7 @@ def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]:
# Trim trailing empty rows
data = data[: last_row_with_data + 1]
- if version >= "3.0.0" and is_readonly and len(data) > 0:
+ if version >= "3.0.0" and self.book.read_only and len(data) > 0:
# With dimension reset, openpyxl no longer pads rows
max_width = max(len(data_row) for data_row in data)
if min(len(data_row) for data_row in data) < max_width:
| - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them | https://api.github.com/repos/pandas-dev/pandas/pulls/39793 | 2021-02-13T14:13:35Z | 2021-02-15T07:16:02Z | 2021-02-15T07:16:02Z | 2021-02-15T09:43:35Z |
TYP: np.ndarray does not yet accept type parameters | diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 6088837550ecd..337c1910102a7 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -2208,7 +2208,7 @@ def _sort_mixed(values):
return np.concatenate([nums, np.asarray(strs, dtype=object)])
-def _sort_tuples(values: np.ndarray[tuple]):
+def _sort_tuples(values: np.ndarray):
"""
Convert array of tuples (1d) to array or array (2d).
We need to keep the columns separately as they contain different types and
| xref https://github.com/pandas-dev/pandas/pull/36092/files#r519455981 | https://api.github.com/repos/pandas-dev/pandas/pulls/39792 | 2021-02-13T12:49:51Z | 2021-02-15T15:44:50Z | 2021-02-15T15:44:50Z | 2021-02-16T09:55:33Z |
TST/REF: split/collect large tests | diff --git a/pandas/tests/frame/indexing/test_getitem.py b/pandas/tests/frame/indexing/test_getitem.py
index 4282db6933371..7c48c412fd694 100644
--- a/pandas/tests/frame/indexing/test_getitem.py
+++ b/pandas/tests/frame/indexing/test_getitem.py
@@ -10,6 +10,7 @@
MultiIndex,
Series,
Timestamp,
+ concat,
get_dummies,
period_range,
)
@@ -176,6 +177,87 @@ def test_getitem_bool_mask_categorical_index(self):
with pytest.raises(TypeError, match=msg):
df4[df4.index > 1]
+ @pytest.mark.parametrize(
+ "data1,data2,expected_data",
+ (
+ (
+ [[1, 2], [3, 4]],
+ [[0.5, 6], [7, 8]],
+ [[np.nan, 3.0], [np.nan, 4.0], [np.nan, 7.0], [6.0, 8.0]],
+ ),
+ (
+ [[1, 2], [3, 4]],
+ [[5, 6], [7, 8]],
+ [[np.nan, 3.0], [np.nan, 4.0], [5, 7], [6, 8]],
+ ),
+ ),
+ )
+ def test_getitem_bool_mask_duplicate_columns_mixed_dtypes(
+ self,
+ data1,
+ data2,
+ expected_data,
+ ):
+ # GH#31954
+
+ df1 = DataFrame(np.array(data1))
+ df2 = DataFrame(np.array(data2))
+ df = concat([df1, df2], axis=1)
+
+ result = df[df > 2]
+
+ exdict = {i: np.array(col) for i, col in enumerate(expected_data)}
+ expected = DataFrame(exdict).rename(columns={2: 0, 3: 1})
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.fixture
+ def df_dup_cols(self):
+ dups = ["A", "A", "C", "D"]
+ df = DataFrame(np.arange(12).reshape(3, 4), columns=dups, dtype="float64")
+ return df
+
+ def test_getitem_boolean_frame_unaligned_with_duplicate_columns(self, df_dup_cols):
+ # `df.A > 6` is a DataFrame with a different shape from df
+
+ # boolean with the duplicate raises
+ df = df_dup_cols
+ msg = "cannot reindex from a duplicate axis"
+ with pytest.raises(ValueError, match=msg):
+ df[df.A > 6]
+
+ def test_getitem_boolean_series_with_duplicate_columns(self, df_dup_cols):
+ # boolean indexing
+ # GH#4879
+ df = DataFrame(
+ np.arange(12).reshape(3, 4), columns=["A", "B", "C", "D"], dtype="float64"
+ )
+ expected = df[df.C > 6]
+ expected.columns = df_dup_cols.columns
+
+ df = df_dup_cols
+ result = df[df.C > 6]
+
+ tm.assert_frame_equal(result, expected)
+ result.dtypes
+ str(result)
+
+ def test_getitem_boolean_frame_with_duplicate_columns(self, df_dup_cols):
+
+ # where
+ df = DataFrame(
+ np.arange(12).reshape(3, 4), columns=["A", "B", "C", "D"], dtype="float64"
+ )
+ # `df > 6` is a DataFrame with the same shape+alignment as df
+ expected = df[df > 6]
+ expected.columns = df_dup_cols.columns
+
+ df = df_dup_cols
+ result = df[df > 6]
+
+ tm.assert_frame_equal(result, expected)
+ result.dtypes
+ str(result)
+
class TestGetitemSlice:
def test_getitem_slice_float64(self, frame_or_series):
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py
index 9318764a1b5ad..4dfbc0b918aaa 100644
--- a/pandas/tests/frame/indexing/test_setitem.py
+++ b/pandas/tests/frame/indexing/test_setitem.py
@@ -2,18 +2,26 @@
import pytest
from pandas.core.dtypes.base import registry as ea_registry
+from pandas.core.dtypes.common import (
+ is_categorical_dtype,
+ is_interval_dtype,
+ is_object_dtype,
+)
from pandas.core.dtypes.dtypes import DatetimeTZDtype, IntervalDtype, PeriodDtype
from pandas import (
Categorical,
DataFrame,
+ DatetimeIndex,
Index,
Interval,
+ IntervalIndex,
NaT,
Period,
PeriodIndex,
Series,
Timestamp,
+ cut,
date_range,
notna,
period_range,
@@ -395,6 +403,90 @@ def test_setitem_listlike_indexer_duplicate_columns_not_equal_length(self):
with pytest.raises(ValueError, match=msg):
df[["a", "b"]] = rhs
+ def test_setitem_intervals(self):
+
+ df = DataFrame({"A": range(10)})
+ ser = cut(df["A"], 5)
+ assert isinstance(ser.cat.categories, IntervalIndex)
+
+ # B & D end up as Categoricals
+ # the remainer are converted to in-line objects
+ # contining an IntervalIndex.values
+ df["B"] = ser
+ df["C"] = np.array(ser)
+ df["D"] = ser.values
+ df["E"] = np.array(ser.values)
+
+ assert is_categorical_dtype(df["B"].dtype)
+ assert is_interval_dtype(df["B"].cat.categories)
+ assert is_categorical_dtype(df["D"].dtype)
+ assert is_interval_dtype(df["D"].cat.categories)
+
+ assert is_object_dtype(df["C"])
+ assert is_object_dtype(df["E"])
+
+ # they compare equal as Index
+ # when converted to numpy objects
+ c = lambda x: Index(np.array(x))
+ tm.assert_index_equal(c(df.B), c(df.B))
+ tm.assert_index_equal(c(df.B), c(df.C), check_names=False)
+ tm.assert_index_equal(c(df.B), c(df.D), check_names=False)
+ tm.assert_index_equal(c(df.C), c(df.D), check_names=False)
+
+ # B & D are the same Series
+ tm.assert_series_equal(df["B"], df["B"])
+ tm.assert_series_equal(df["B"], df["D"], check_names=False)
+
+ # C & E are the same Series
+ tm.assert_series_equal(df["C"], df["C"])
+ tm.assert_series_equal(df["C"], df["E"], check_names=False)
+
+
+class TestSetitemTZAwareValues:
+ @pytest.fixture
+ def idx(self):
+ naive = DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B")
+ idx = naive.tz_localize("US/Pacific")
+ return idx
+
+ @pytest.fixture
+ def expected(self, idx):
+ expected = Series(np.array(idx.tolist(), dtype="object"), name="B")
+ assert expected.dtype == idx.dtype
+ return expected
+
+ def test_setitem_dt64series(self, idx, expected):
+ # convert to utc
+ df = DataFrame(np.random.randn(2, 1), columns=["A"])
+ df["B"] = idx
+
+ with tm.assert_produces_warning(FutureWarning) as m:
+ df["B"] = idx.to_series(keep_tz=False, index=[0, 1])
+ msg = "do 'idx.tz_convert(None)' before calling"
+ assert msg in str(m[0].message)
+
+ result = df["B"]
+ comp = Series(idx.tz_convert("UTC").tz_localize(None), name="B")
+ tm.assert_series_equal(result, comp)
+
+ def test_setitem_datetimeindex(self, idx, expected):
+ # setting a DataFrame column with a tzaware DTI retains the dtype
+ df = DataFrame(np.random.randn(2, 1), columns=["A"])
+
+ # assign to frame
+ df["B"] = idx
+ result = df["B"]
+ tm.assert_series_equal(result, expected)
+
+ def test_setitem_object_array_of_tzaware_datetimes(self, idx, expected):
+ # setting a DataFrame column with a tzaware DTI retains the dtype
+ df = DataFrame(np.random.randn(2, 1), columns=["A"])
+
+ # object array of datetimes with a tz
+ df["B"] = idx.to_pydatetime()
+ result = df["B"]
+ tm.assert_series_equal(result, expected)
+
class TestDataFrameSetItemWithExpansion:
def test_setitem_listlike_views(self):
diff --git a/pandas/tests/frame/methods/test_reindex.py b/pandas/tests/frame/methods/test_reindex.py
index e4e2656f4337c..fc4829ac41a26 100644
--- a/pandas/tests/frame/methods/test_reindex.py
+++ b/pandas/tests/frame/methods/test_reindex.py
@@ -21,6 +21,43 @@
import pandas.core.common as com
+class TestReindexSetIndex:
+ # Tests that check both reindex and set_index
+
+ def test_dti_set_index_reindex_datetimeindex(self):
+ # GH#6631
+ df = DataFrame(np.random.random(6))
+ idx1 = date_range("2011/01/01", periods=6, freq="M", tz="US/Eastern")
+ idx2 = date_range("2013", periods=6, freq="A", tz="Asia/Tokyo")
+
+ df = df.set_index(idx1)
+ tm.assert_index_equal(df.index, idx1)
+ df = df.reindex(idx2)
+ tm.assert_index_equal(df.index, idx2)
+
+ def test_dti_set_index_reindex_freq_with_tz(self):
+ # GH#11314 with tz
+ index = date_range(
+ datetime(2015, 10, 1), datetime(2015, 10, 1, 23), freq="H", tz="US/Eastern"
+ )
+ df = DataFrame(np.random.randn(24, 1), columns=["a"], index=index)
+ new_index = date_range(
+ datetime(2015, 10, 2), datetime(2015, 10, 2, 23), freq="H", tz="US/Eastern"
+ )
+
+ result = df.set_index(new_index)
+ assert result.index.freq == index.freq
+
+ def test_set_reset_index_intervalindex(self):
+
+ df = DataFrame({"A": range(10)})
+ ser = pd.cut(df.A, 5)
+ df["B"] = ser
+ df = df.set_index("B")
+
+ df = df.reset_index()
+
+
class TestDataFrameSelectReindex:
# These are specific reindex-based tests; other indexing tests should go in
# test_indexing
diff --git a/pandas/tests/frame/methods/test_set_index.py b/pandas/tests/frame/methods/test_set_index.py
index b66a95bae51c5..70232dfd1d79a 100644
--- a/pandas/tests/frame/methods/test_set_index.py
+++ b/pandas/tests/frame/methods/test_set_index.py
@@ -1,3 +1,7 @@
+"""
+See also: test_reindex.py:TestReindexSetIndex
+"""
+
from datetime import datetime, timedelta
import numpy as np
diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py
index 862f5b87785f5..c68171ab254c7 100644
--- a/pandas/tests/frame/test_alter_axes.py
+++ b/pandas/tests/frame/test_alter_axes.py
@@ -1,111 +1,13 @@
from datetime import datetime
-import numpy as np
-import pytest
import pytz
-from pandas.core.dtypes.common import (
- is_categorical_dtype,
- is_interval_dtype,
- is_object_dtype,
-)
-
-from pandas import (
- DataFrame,
- DatetimeIndex,
- Index,
- IntervalIndex,
- Series,
- Timestamp,
- cut,
- date_range,
-)
+from pandas import DataFrame
import pandas._testing as tm
class TestDataFrameAlterAxes:
- @pytest.fixture
- def idx_expected(self):
- idx = DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B").tz_localize(
- "US/Pacific"
- )
-
- expected = Series(
- np.array(
- [
- Timestamp("2013-01-01 13:00:00-0800", tz="US/Pacific"),
- Timestamp("2013-01-02 14:00:00-0800", tz="US/Pacific"),
- ],
- dtype="object",
- ),
- name="B",
- )
- assert expected.dtype == idx.dtype
- return idx, expected
-
- def test_to_series_keep_tz_deprecated_true(self, idx_expected):
- # convert to series while keeping the timezone
- idx, expected = idx_expected
-
- msg = "stop passing 'keep_tz'"
- with tm.assert_produces_warning(FutureWarning) as m:
- result = idx.to_series(keep_tz=True, index=[0, 1])
- assert msg in str(m[0].message)
-
- tm.assert_series_equal(result, expected)
-
- def test_to_series_keep_tz_deprecated_false(self, idx_expected):
- idx, expected = idx_expected
-
- with tm.assert_produces_warning(FutureWarning) as m:
- result = idx.to_series(keep_tz=False, index=[0, 1])
- tm.assert_series_equal(result, expected.dt.tz_convert(None))
- msg = "do 'idx.tz_convert(None)' before calling"
- assert msg in str(m[0].message)
-
- def test_setitem_dt64series(self, idx_expected):
- # convert to utc
- idx, expected = idx_expected
- df = DataFrame(np.random.randn(2, 1), columns=["A"])
- df["B"] = idx
-
- with tm.assert_produces_warning(FutureWarning) as m:
- df["B"] = idx.to_series(keep_tz=False, index=[0, 1])
- msg = "do 'idx.tz_convert(None)' before calling"
- assert msg in str(m[0].message)
-
- result = df["B"]
- comp = Series(idx.tz_convert("UTC").tz_localize(None), name="B")
- tm.assert_series_equal(result, comp)
-
- def test_setitem_datetimeindex(self, idx_expected):
- # setting a DataFrame column with a tzaware DTI retains the dtype
- idx, expected = idx_expected
- df = DataFrame(np.random.randn(2, 1), columns=["A"])
-
- # assign to frame
- df["B"] = idx
- result = df["B"]
- tm.assert_series_equal(result, expected)
-
- def test_setitem_object_array_of_tzaware_datetimes(self, idx_expected):
- # setting a DataFrame column with a tzaware DTI retains the dtype
- idx, expected = idx_expected
- df = DataFrame(np.random.randn(2, 1), columns=["A"])
-
- # object array of datetimes with a tz
- df["B"] = idx.to_pydatetime()
- result = df["B"]
- tm.assert_series_equal(result, expected)
-
- def test_constructor_from_tzaware_datetimeindex(self, idx_expected):
- # don't cast a DatetimeIndex WITH a tz, leave as object
- # GH 6032
- idx, expected = idx_expected
-
- # convert index to series
- result = Series(idx)
- tm.assert_series_equal(result, expected)
+ # Tests for setting index/columns attributes directly (i.e. __setattr__)
def test_set_axis_setattr_index(self):
# GH 6785
@@ -117,31 +19,6 @@ def test_set_axis_setattr_index(self):
df.pop("ts")
tm.assert_frame_equal(df, expected)
- def test_dti_set_index_reindex(self):
- # GH 6631
- df = DataFrame(np.random.random(6))
- idx1 = date_range("2011/01/01", periods=6, freq="M", tz="US/Eastern")
- idx2 = date_range("2013", periods=6, freq="A", tz="Asia/Tokyo")
-
- df = df.set_index(idx1)
- tm.assert_index_equal(df.index, idx1)
- df = df.reindex(idx2)
- tm.assert_index_equal(df.index, idx2)
-
- def test_dti_set_index_reindex_with_tz(self):
- # GH 11314
- # with tz
- index = date_range(
- datetime(2015, 10, 1), datetime(2015, 10, 1, 23), freq="H", tz="US/Eastern"
- )
- df = DataFrame(np.random.randn(24, 1), columns=["a"], index=index)
- new_index = date_range(
- datetime(2015, 10, 2), datetime(2015, 10, 2, 23), freq="H", tz="US/Eastern"
- )
-
- result = df.set_index(new_index)
- assert result.index.freq == index.freq
-
# Renaming
def test_assign_columns(self, float_frame):
@@ -151,52 +28,3 @@ def test_assign_columns(self, float_frame):
df.columns = ["foo", "bar", "baz", "quux", "foo2"]
tm.assert_series_equal(float_frame["C"], df["baz"], check_names=False)
tm.assert_series_equal(float_frame["hi"], df["foo2"], check_names=False)
-
-
-class TestIntervalIndex:
- def test_setitem(self):
-
- df = DataFrame({"A": range(10)})
- ser = cut(df["A"], 5)
- assert isinstance(ser.cat.categories, IntervalIndex)
-
- # B & D end up as Categoricals
- # the remainer are converted to in-line objects
- # contining an IntervalIndex.values
- df["B"] = ser
- df["C"] = np.array(ser)
- df["D"] = ser.values
- df["E"] = np.array(ser.values)
-
- assert is_categorical_dtype(df["B"].dtype)
- assert is_interval_dtype(df["B"].cat.categories)
- assert is_categorical_dtype(df["D"].dtype)
- assert is_interval_dtype(df["D"].cat.categories)
-
- assert is_object_dtype(df["C"])
- assert is_object_dtype(df["E"])
-
- # they compare equal as Index
- # when converted to numpy objects
- c = lambda x: Index(np.array(x))
- tm.assert_index_equal(c(df.B), c(df.B))
- tm.assert_index_equal(c(df.B), c(df.C), check_names=False)
- tm.assert_index_equal(c(df.B), c(df.D), check_names=False)
- tm.assert_index_equal(c(df.C), c(df.D), check_names=False)
-
- # B & D are the same Series
- tm.assert_series_equal(df["B"], df["B"])
- tm.assert_series_equal(df["B"], df["D"], check_names=False)
-
- # C & E are the same Series
- tm.assert_series_equal(df["C"], df["C"])
- tm.assert_series_equal(df["C"], df["E"], check_names=False)
-
- def test_set_reset_index(self):
-
- df = DataFrame({"A": range(10)})
- s = cut(df.A, 5)
- df["B"] = s
- df = df.set_index("B")
-
- df = df.reset_index()
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index 9ec745932514f..5fcab5200e305 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -20,6 +20,7 @@
Categorical,
CategoricalIndex,
DataFrame,
+ DatetimeIndex,
Index,
Interval,
MultiIndex,
@@ -48,6 +49,19 @@
class TestDataFrameConstructors:
+ def test_constructor_from_tzaware_datetimeindex(self):
+ # don't cast a DatetimeIndex WITH a tz, leave as object
+ # GH#6032
+ naive = DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B")
+ idx = naive.tz_localize("US/Pacific")
+
+ expected = Series(np.array(idx.tolist(), dtype="object"), name="B")
+ assert expected.dtype == idx.dtype
+
+ # convert index to series
+ result = Series(idx)
+ tm.assert_series_equal(result, expected)
+
def test_array_of_dt64_nat_with_td64dtype_raises(self, frame_or_series):
# GH#39462
nat = np.datetime64("NaT", "ns")
diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py
index 8dcf6f2188058..1f892c3a03e85 100644
--- a/pandas/tests/frame/test_nonunique_indexes.py
+++ b/pandas/tests/frame/test_nonunique_indexes.py
@@ -33,6 +33,7 @@ def test_column_dups_operations(self):
expected = DataFrame([[1, 1, 1, 5], [1, 1, 2, 5], [2, 1, 3, 5]], columns=idx)
check(df, expected)
+ def test_insert_with_duplicate_columns(self):
# insert
df = DataFrame(
[[1, 1, 1, 5], [1, 1, 2, 5], [2, 1, 3, 5]],
@@ -119,6 +120,7 @@ def test_column_dups_operations(self):
)
tm.assert_frame_equal(df, expected)
+ def test_dup_across_dtypes(self):
# dup across dtypes
df = DataFrame(
[[1, 1, 1.0, 5], [1, 1, 2.0, 5], [2, 1, 3.0, 5]],
@@ -155,12 +157,14 @@ def test_column_dups_operations(self):
)
check(df, expected)
+ def test_values_with_duplicate_columns(self):
# values
df = DataFrame([[1, 2.5], [3, 4.5]], index=[1, 2], columns=["x", "x"])
result = df.values
expected = np.array([[1, 2.5], [3, 4.5]])
assert (result == expected).all().all()
+ def test_rename_with_duplicate_columns(self):
# rename, GH 4403
df4 = DataFrame(
{"RT": [0.0454], "TClose": [22.02], "TExg": [0.0422]},
@@ -201,6 +205,8 @@ def test_column_dups_operations(self):
).set_index(["STK_ID", "RPT_Date"], drop=False)
tm.assert_frame_equal(result, expected)
+ def test_reindex_with_duplicate_columns(self):
+
# reindex is invalid!
df = DataFrame(
[[1, 5, 7.0], [1, 5, 7.0], [1, 5, 7.0]], columns=["bar", "a", "a"]
@@ -211,6 +217,8 @@ def test_column_dups_operations(self):
with pytest.raises(ValueError, match=msg):
df.reindex(columns=["bar", "foo"])
+ def test_drop_with_duplicate_columns(self):
+
# drop
df = DataFrame(
[[1, 5, 7.0], [1, 5, 7.0], [1, 5, 7.0]], columns=["bar", "a", "a"]
@@ -221,6 +229,7 @@ def test_column_dups_operations(self):
result = df.drop("a", axis=1)
check(result, expected)
+ def test_describe_with_duplicate_columns(self):
# describe
df = DataFrame(
[[1, 1, 1], [2, 2, 2], [3, 3, 3]],
@@ -232,6 +241,7 @@ def test_column_dups_operations(self):
expected = pd.concat([s, s, s], keys=df.columns, axis=1)
check(result, expected)
+ def test_column_dups_indexes(self):
# check column dups with index equal and not equal to df's index
df = DataFrame(
np.random.randn(5, 3),
@@ -248,6 +258,8 @@ def test_column_dups_operations(self):
this_df["A"] = index
check(this_df, expected_df)
+ def test_arithmetic_with_dups(self):
+
# operations
for op in ["__add__", "__mul__", "__sub__", "__truediv__"]:
df = DataFrame({"A": np.arange(10), "B": np.random.rand(10)})
@@ -257,6 +269,7 @@ def test_column_dups_operations(self):
result = getattr(df, op)(df)
check(result, expected)
+ def test_changing_dtypes_with_duplicate_columns(self):
# multiple assignments that change dtypes
# the location indexer is a slice
# GH 6120
@@ -272,7 +285,7 @@ def test_column_dups_operations(self):
df["that"] = 1
check(df, expected)
- def test_column_dups2(self):
+ def test_column_dups_drop(self):
# drop buggy GH 6240
df = DataFrame(
@@ -289,6 +302,7 @@ def test_column_dups2(self):
result = df2.drop("C", axis=1)
tm.assert_frame_equal(result, expected)
+ def test_column_dups_dropna(self):
# dropna
df = DataFrame(
{
@@ -310,43 +324,6 @@ def test_column_dups2(self):
result = df.dropna(subset=["A", "C"], how="all")
tm.assert_frame_equal(result, expected)
- def test_getitem_boolean_series_with_duplicate_columns(self):
- # boolean indexing
- # GH 4879
- dups = ["A", "A", "C", "D"]
- df = DataFrame(
- np.arange(12).reshape(3, 4), columns=["A", "B", "C", "D"], dtype="float64"
- )
- expected = df[df.C > 6]
- expected.columns = dups
- df = DataFrame(np.arange(12).reshape(3, 4), columns=dups, dtype="float64")
- result = df[df.C > 6]
- check(result, expected)
-
- def test_getitem_boolean_frame_with_duplicate_columns(self):
- dups = ["A", "A", "C", "D"]
-
- # where
- df = DataFrame(
- np.arange(12).reshape(3, 4), columns=["A", "B", "C", "D"], dtype="float64"
- )
- # `df > 6` is a DataFrame with the same shape+alignment as df
- expected = df[df > 6]
- expected.columns = dups
- df = DataFrame(np.arange(12).reshape(3, 4), columns=dups, dtype="float64")
- result = df[df > 6]
- check(result, expected)
-
- def test_getitem_boolean_frame_unaligned_with_duplicate_columns(self):
- # `df.A > 6` is a DataFrame with a different shape from df
- dups = ["A", "A", "C", "D"]
-
- # boolean with the duplicate raises
- df = DataFrame(np.arange(12).reshape(3, 4), columns=dups, dtype="float64")
- msg = "cannot reindex from a duplicate axis"
- with pytest.raises(ValueError, match=msg):
- df[df.A > 6]
-
def test_column_dups_indexing(self):
# dup aligning operations should work
@@ -357,6 +334,7 @@ def test_column_dups_indexing(self):
result = df1.sub(df2)
tm.assert_frame_equal(result, expected)
+ def test_dup_columns_comparisons(self):
# equality
df1 = DataFrame([[1, 2], [2, np.nan], [3, 4], [4, 4]], columns=["A", "B"])
df2 = DataFrame([[0, 1], [2, 4], [2, np.nan], [4, 5]], columns=["A", "A"])
@@ -374,6 +352,7 @@ def test_column_dups_indexing(self):
)
tm.assert_frame_equal(result, expected)
+ def test_mixed_column_selection(self):
# mixed column selection
# GH 5639
dfbool = DataFrame(
@@ -387,6 +366,7 @@ def test_column_dups_indexing(self):
result = dfbool[["one", "three", "one"]]
check(result, expected)
+ def test_multi_axis_dups(self):
# multi-axis dups
# GH 6121
df = DataFrame(
@@ -422,6 +402,7 @@ def test_columns_with_dups(self):
expected = DataFrame([[1, 2, 3]], columns=["b", "a", "a.1"])
tm.assert_frame_equal(df, expected)
+ def test_columns_with_dup_index(self):
# with a dup index
df = DataFrame([[1, 2]], columns=["a", "a"])
df.columns = ["b", "b"]
@@ -429,6 +410,7 @@ def test_columns_with_dups(self):
expected = DataFrame([[1, 2]], columns=["b", "b"])
tm.assert_frame_equal(df, expected)
+ def test_multi_dtype(self):
# multi-dtype
df = DataFrame(
[[1, 2, 1.0, 2.0, 3.0, "foo", "bar"]],
@@ -441,12 +423,14 @@ def test_columns_with_dups(self):
)
tm.assert_frame_equal(df, expected)
+ def test_multi_dtype2(self):
df = DataFrame([[1, 2, "foo", "bar"]], columns=["a", "a", "a", "a"])
df.columns = ["a", "a.1", "a.2", "a.3"]
str(df)
expected = DataFrame([[1, 2, "foo", "bar"]], columns=["a", "a.1", "a.2", "a.3"])
tm.assert_frame_equal(df, expected)
+ def test_dups_across_blocks(self):
# dups across blocks
df_float = DataFrame(np.random.randn(10, 3), dtype="float64")
df_int = DataFrame(np.random.randn(10, 3), dtype="int64")
@@ -464,6 +448,7 @@ def test_columns_with_dups(self):
for i in range(len(df.columns)):
df.iloc[:, i]
+ def test_dup_columns_across_dtype(self):
# dup columns across dtype GH 2079/2194
vals = [[1, -1, 2.0], [2, -2, 3.0]]
rs = DataFrame(vals, columns=["A", "A", "B"])
@@ -486,36 +471,3 @@ def test_set_value_by_index(self):
df.iloc[:, 0] = 3
tm.assert_series_equal(df.iloc[:, 1], expected)
-
- @pytest.mark.parametrize(
- "data1,data2,expected_data",
- (
- (
- [[1, 2], [3, 4]],
- [[0.5, 6], [7, 8]],
- [[np.nan, 3.0], [np.nan, 4.0], [np.nan, 7.0], [6.0, 8.0]],
- ),
- (
- [[1, 2], [3, 4]],
- [[5, 6], [7, 8]],
- [[np.nan, 3.0], [np.nan, 4.0], [5, 7], [6, 8]],
- ),
- ),
- )
- def test_masking_duplicate_columns_mixed_dtypes(
- self,
- data1,
- data2,
- expected_data,
- ):
- # GH31954
-
- df1 = DataFrame(np.array(data1))
- df2 = DataFrame(np.array(data2))
- df = pd.concat([df1, df2], axis=1)
-
- result = df[df > 2]
- expected = DataFrame(
- {i: np.array(col) for i, col in enumerate(expected_data)}
- ).rename(columns={2: 0, 3: 1})
- tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/indexes/datetimes/methods/test_to_series.py b/pandas/tests/indexes/datetimes/methods/test_to_series.py
new file mode 100644
index 0000000000000..5998fc0dde499
--- /dev/null
+++ b/pandas/tests/indexes/datetimes/methods/test_to_series.py
@@ -0,0 +1,37 @@
+import numpy as np
+import pytest
+
+from pandas import DatetimeIndex, Series
+import pandas._testing as tm
+
+
+class TestToSeries:
+ @pytest.fixture
+ def idx_expected(self):
+ naive = DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B")
+ idx = naive.tz_localize("US/Pacific")
+
+ expected = Series(np.array(idx.tolist(), dtype="object"), name="B")
+
+ assert expected.dtype == idx.dtype
+ return idx, expected
+
+ def test_to_series_keep_tz_deprecated_true(self, idx_expected):
+ # convert to series while keeping the timezone
+ idx, expected = idx_expected
+
+ msg = "stop passing 'keep_tz'"
+ with tm.assert_produces_warning(FutureWarning) as m:
+ result = idx.to_series(keep_tz=True, index=[0, 1])
+ assert msg in str(m[0].message)
+
+ tm.assert_series_equal(result, expected)
+
+ def test_to_series_keep_tz_deprecated_false(self, idx_expected):
+ idx, expected = idx_expected
+
+ with tm.assert_produces_warning(FutureWarning) as m:
+ result = idx.to_series(keep_tz=False, index=[0, 1])
+ tm.assert_series_equal(result, expected.dt.tz_convert(None))
+ msg = "do 'idx.tz_convert(None)' before calling"
+ assert msg in str(m[0].message)
| https://api.github.com/repos/pandas-dev/pandas/pulls/39789 | 2021-02-13T06:01:58Z | 2021-02-15T23:49:21Z | 2021-02-15T23:49:21Z | 2021-02-16T00:06:29Z | |
BUG: DTA/TDA/PA/Series/Index.view with datetimelike | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 388c5dbf6a7ee..2175a18a88e73 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -326,6 +326,7 @@ Numeric
Conversion
^^^^^^^^^^
- Bug in :meth:`Series.to_dict` with ``orient='records'`` now returns python native types (:issue:`25969`)
+- Bug in :meth:`Series.view` and :meth:`Index.view` when converting between datetime-like (``datetime64[ns]``, ``datetime64[ns, tz]``, ``timedelta64``, ``period``) dtypes (:issue:`39788`)
-
-
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 5dd55ff0f1fa2..a6ee95e131559 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -44,6 +44,7 @@
)
from pandas._libs.tslibs.timestamps import integer_op_not_supported
from pandas._typing import (
+ ArrayLike,
DatetimeLikeScalar,
Dtype,
DtypeObj,
@@ -79,6 +80,10 @@
is_unsigned_integer_dtype,
pandas_dtype,
)
+from pandas.core.dtypes.dtypes import (
+ DatetimeTZDtype,
+ PeriodDtype,
+)
from pandas.core.dtypes.missing import (
is_valid_na_for_dtype,
isna,
@@ -428,9 +433,30 @@ def astype(self, dtype, copy=True):
else:
return np.asarray(self, dtype=dtype)
- def view(self, dtype: Optional[Dtype] = None):
+ def view(self, dtype: Optional[Dtype] = None) -> ArrayLike:
+ # We handle datetime64, datetime64tz, timedelta64, and period
+ # dtypes here. Everything else we pass through to the underlying
+ # ndarray.
if dtype is None or dtype is self.dtype:
return type(self)(self._ndarray, dtype=self.dtype)
+
+ if isinstance(dtype, type):
+ # we sometimes pass non-dtype objects, e.g np.ndarray;
+ # pass those through to the underlying ndarray
+ return self._ndarray.view(dtype)
+
+ dtype = pandas_dtype(dtype)
+ if isinstance(dtype, (PeriodDtype, DatetimeTZDtype)):
+ cls = dtype.construct_array_type()
+ return cls._simple_new(self.asi8, dtype=dtype)
+ elif dtype == "M8[ns]":
+ from pandas.core.arrays import DatetimeArray
+
+ return DatetimeArray._simple_new(self.asi8, dtype=dtype)
+ elif dtype == "m8[ns]":
+ from pandas.core.arrays import TimedeltaArray
+
+ return TimedeltaArray._simple_new(self.asi8.view("m8[ns]"), dtype=dtype)
return self._ndarray.view(dtype=dtype)
# ------------------------------------------------------------------
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 71095b8f4113a..7d8d964f63496 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -793,6 +793,23 @@ def view(self, cls=None):
# we need to see if we are subclassing an
# index type here
if cls is not None and not hasattr(cls, "_typ"):
+ dtype = cls
+ if isinstance(cls, str):
+ dtype = pandas_dtype(cls)
+
+ if isinstance(dtype, (np.dtype, ExtensionDtype)) and needs_i8_conversion(
+ dtype
+ ):
+ if dtype.kind == "m" and dtype != "m8[ns]":
+ # e.g. m8[s]
+ return self._data.view(cls)
+
+ arr = self._data.view("i8")
+ idx_cls = self._dtype_to_subclass(dtype)
+ arr_cls = idx_cls._data_cls
+ arr = arr_cls._simple_new(self._data.view("i8"), dtype=dtype)
+ return idx_cls._simple_new(arr, name=self.name)
+
result = self._data.view(cls)
else:
result = self._view()
diff --git a/pandas/tests/series/methods/test_view.py b/pandas/tests/series/methods/test_view.py
index 48f7b47f6d25a..f0069cdb9b79c 100644
--- a/pandas/tests/series/methods/test_view.py
+++ b/pandas/tests/series/methods/test_view.py
@@ -1,5 +1,10 @@
+import numpy as np
+import pytest
+
from pandas import (
+ Index,
Series,
+ array as pd_array,
date_range,
)
import pandas._testing as tm
@@ -19,3 +24,23 @@ def test_view_tz(self):
]
)
tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "first", ["m8[ns]", "M8[ns]", "M8[ns, US/Central]", "period[D]"]
+ )
+ @pytest.mark.parametrize(
+ "second", ["m8[ns]", "M8[ns]", "M8[ns, US/Central]", "period[D]"]
+ )
+ @pytest.mark.parametrize("box", [Series, Index, pd_array])
+ def test_view_between_datetimelike(self, first, second, box):
+
+ dti = date_range("2016-01-01", periods=3)
+
+ orig = box(dti)
+ obj = orig.view(first)
+ assert obj.dtype == first
+ tm.assert_numpy_array_equal(np.asarray(obj.view("i8")), dti.asi8)
+
+ res = obj.view(second)
+ assert res.dtype == second
+ tm.assert_numpy_array_equal(np.asarray(obj.view("i8")), dti.asi8)
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
This makes it feasible to share some of the SetitemCastingEquivalents tests. | https://api.github.com/repos/pandas-dev/pandas/pulls/39788 | 2021-02-13T04:43:45Z | 2021-02-21T17:22:50Z | 2021-02-21T17:22:50Z | 2021-02-21T17:26:15Z |
CLN: Remove "how" return from agg | diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 828b460f84ec6..6e48d4b699977 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -147,18 +147,14 @@ def index(self) -> Index:
def apply(self) -> FrameOrSeriesUnion:
pass
- def agg(self) -> Tuple[Optional[FrameOrSeriesUnion], Optional[bool]]:
+ def agg(self) -> Optional[FrameOrSeriesUnion]:
"""
Provide an implementation for the aggregators.
Returns
-------
- tuple of result, how.
-
- Notes
- -----
- how can be a string describe the required post-processing, or
- None if not required.
+ Result of aggregation, or None if agg cannot be performed by
+ this method.
"""
obj = self.obj
arg = self.f
@@ -171,23 +167,21 @@ def agg(self) -> Tuple[Optional[FrameOrSeriesUnion], Optional[bool]]:
result = self.maybe_apply_str()
if result is not None:
- return result, None
+ return result
if is_dict_like(arg):
- return self.agg_dict_like(_axis), True
+ return self.agg_dict_like(_axis)
elif is_list_like(arg):
# we require a list, but not a 'str'
- return self.agg_list_like(_axis=_axis), None
- else:
- result = None
+ return self.agg_list_like(_axis=_axis)
if callable(arg):
f = obj._get_cython_func(arg)
if f and not args and not kwargs:
- return getattr(obj, f)(), None
+ return getattr(obj, f)()
# caller can react
- return result, True
+ return None
def agg_list_like(self, _axis: int) -> FrameOrSeriesUnion:
"""
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 63d238da12101..6b44776aeb9ef 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -7686,7 +7686,7 @@ def aggregate(self, func=None, axis: Axis = 0, *args, **kwargs):
result = None
try:
- result, how = self._aggregate(func, axis, *args, **kwargs)
+ result = self._aggregate(func, axis, *args, **kwargs)
except TypeError as err:
exc = TypeError(
"DataFrame constructor called with "
@@ -7720,14 +7720,14 @@ def _aggregate(self, arg, axis: Axis = 0, *args, **kwargs):
args=args,
kwargs=kwargs,
)
- result, how = op.agg()
+ result = op.agg()
if axis == 1:
# NDFrame.aggregate returns a tuple, and we need to transpose
# only result
result = result.T if result is not None else result
- return result, how
+ return result
agg = aggregate
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index a7297923f1034..dd8f0e5c0b777 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -46,6 +46,7 @@
ensure_platform_int,
is_bool,
is_categorical_dtype,
+ is_dict_like,
is_integer_dtype,
is_interval_dtype,
is_numeric_dtype,
@@ -962,8 +963,8 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs)
func = maybe_mangle_lambdas(func)
op = GroupByApply(self, func, args, kwargs)
- result, how = op.agg()
- if how is None:
+ result = op.agg()
+ if not is_dict_like(func) and result is not None:
return result
if result is None:
@@ -982,7 +983,7 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs)
# try to treat as if we are passing a list
try:
- result, _ = GroupByApply(
+ result = GroupByApply(
self, [func], args=(), kwargs={"_axis": self.axis}
).agg()
diff --git a/pandas/core/resample.py b/pandas/core/resample.py
index 68f791ac0a837..2cfb13da7dd45 100644
--- a/pandas/core/resample.py
+++ b/pandas/core/resample.py
@@ -301,7 +301,7 @@ def pipe(
def aggregate(self, func, *args, **kwargs):
self._set_binner()
- result, how = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg()
+ result = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg()
if result is None:
how = func
grouper = None
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 7d97c9f6189f3..f5a0dbc996c42 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -3973,7 +3973,7 @@ def aggregate(self, func=None, axis=0, *args, **kwargs):
func = dict(kwargs.items())
op = series_apply(self, func, args=args, kwargs=kwargs)
- result, how = op.agg()
+ result = op.agg()
if result is None:
# we can be called from an inner function which
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index b5714dbcd9e91..1538975b260c0 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -510,7 +510,7 @@ def calc(x):
return self._apply_tablewise(homogeneous_func, name)
def aggregate(self, func, *args, **kwargs):
- result, how = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg()
+ result = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg()
if result is None:
return self.apply(func, raw=False, args=args, kwargs=kwargs)
return result
@@ -994,7 +994,7 @@ def calc(x):
axis="",
)
def aggregate(self, func, *args, **kwargs):
- result, how = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg()
+ result = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg()
if result is None:
# these must apply directly
| - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/39786 | 2021-02-13T03:08:40Z | 2021-02-15T23:50:11Z | 2021-02-15T23:50:11Z | 2021-02-15T23:55:29Z |
TST: use more context managers | diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py
index 14ad97c058a55..0c61a8a18e153 100644
--- a/pandas/tests/io/excel/test_writers.py
+++ b/pandas/tests/io/excel/test_writers.py
@@ -342,8 +342,8 @@ def test_excel_sheet_by_name_raise(self, path, engine):
gt = DataFrame(np.random.randn(10, 2))
gt.to_excel(path)
- xl = ExcelFile(path)
- df = pd.read_excel(xl, sheet_name=0, index_col=0)
+ with ExcelFile(path) as xl:
+ df = pd.read_excel(xl, sheet_name=0, index_col=0)
tm.assert_frame_equal(gt, df)
@@ -419,8 +419,8 @@ def test_mixed(self, frame, path):
mixed_frame["foo"] = "bar"
mixed_frame.to_excel(path, "test1")
- reader = ExcelFile(path)
- recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
+ with ExcelFile(path) as reader:
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
tm.assert_frame_equal(mixed_frame, recons)
def test_ts_frame(self, tsframe, path):
@@ -431,9 +431,8 @@ def test_ts_frame(self, tsframe, path):
df.index = index
df.to_excel(path, "test1")
- reader = ExcelFile(path)
-
- recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
+ with ExcelFile(path) as reader:
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
tm.assert_frame_equal(df, recons)
def test_basics_with_nan(self, frame, path):
@@ -451,8 +450,8 @@ def test_int_types(self, np_type, path):
df = DataFrame(np.random.randint(-10, 10, size=(10, 2)), dtype=np_type)
df.to_excel(path, "test1")
- reader = ExcelFile(path)
- recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
+ with ExcelFile(path) as reader:
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
int_frame = df.astype(np.int64)
tm.assert_frame_equal(int_frame, recons)
@@ -475,8 +474,10 @@ def test_float_types(self, np_type, path):
df = DataFrame(np.random.random_sample(10), dtype=np_type)
df.to_excel(path, "test1")
- reader = ExcelFile(path)
- recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(np_type)
+ with ExcelFile(path) as reader:
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(
+ np_type
+ )
tm.assert_frame_equal(df, recons)
@@ -486,8 +487,10 @@ def test_bool_types(self, np_type, path):
df = DataFrame([1, 0, True, False], dtype=np_type)
df.to_excel(path, "test1")
- reader = ExcelFile(path)
- recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(np_type)
+ with ExcelFile(path) as reader:
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(
+ np_type
+ )
tm.assert_frame_equal(df, recons)
@@ -495,8 +498,8 @@ def test_inf_roundtrip(self, path):
df = DataFrame([(1, np.inf), (2, 3), (5, -np.inf)])
df.to_excel(path, "test1")
- reader = ExcelFile(path)
- recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
+ with ExcelFile(path) as reader:
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
tm.assert_frame_equal(df, recons)
@@ -518,11 +521,11 @@ def test_sheets(self, frame, tsframe, path):
with ExcelWriter(path) as writer:
frame.to_excel(writer, "test1")
tsframe.to_excel(writer, "test2")
- reader = ExcelFile(path)
- recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
- tm.assert_frame_equal(frame, recons)
- recons = pd.read_excel(reader, sheet_name="test2", index_col=0)
- tm.assert_frame_equal(tsframe, recons)
+ with ExcelFile(path) as reader:
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
+ tm.assert_frame_equal(frame, recons)
+ recons = pd.read_excel(reader, sheet_name="test2", index_col=0)
+ tm.assert_frame_equal(tsframe, recons)
assert 2 == len(reader.sheet_names)
assert "test1" == reader.sheet_names[0]
assert "test2" == reader.sheet_names[1]
@@ -539,8 +542,8 @@ def test_colaliases(self, frame, path):
# column aliases
col_aliases = Index(["AA", "X", "Y", "Z"])
frame.to_excel(path, "test1", header=col_aliases)
- reader = ExcelFile(path)
- rs = pd.read_excel(reader, sheet_name="test1", index_col=0)
+ with ExcelFile(path) as reader:
+ rs = pd.read_excel(reader, sheet_name="test1", index_col=0)
xp = frame.copy()
xp.columns = col_aliases
tm.assert_frame_equal(xp, rs)
@@ -557,8 +560,10 @@ def test_roundtrip_indexlabels(self, merge_cells, frame, path):
# test index_label
df = DataFrame(np.random.randn(10, 2)) >= 0
df.to_excel(path, "test1", index_label=["test"], merge_cells=merge_cells)
- reader = ExcelFile(path)
- recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(np.int64)
+ with ExcelFile(path) as reader:
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(
+ np.int64
+ )
df.index.names = ["test"]
assert df.index.names == recons.index.names
@@ -569,15 +574,19 @@ def test_roundtrip_indexlabels(self, merge_cells, frame, path):
index_label=["test", "dummy", "dummy2"],
merge_cells=merge_cells,
)
- reader = ExcelFile(path)
- recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(np.int64)
+ with ExcelFile(path) as reader:
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(
+ np.int64
+ )
df.index.names = ["test"]
assert df.index.names == recons.index.names
df = DataFrame(np.random.randn(10, 2)) >= 0
df.to_excel(path, "test1", index_label="test", merge_cells=merge_cells)
- reader = ExcelFile(path)
- recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(np.int64)
+ with ExcelFile(path) as reader:
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(
+ np.int64
+ )
df.index.names = ["test"]
tm.assert_frame_equal(df, recons.astype(bool))
@@ -592,8 +601,8 @@ def test_roundtrip_indexlabels(self, merge_cells, frame, path):
df = frame.copy()
df = df.set_index(["A", "B"])
- reader = ExcelFile(path)
- recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1])
+ with ExcelFile(path) as reader:
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1])
tm.assert_frame_equal(df, recons)
def test_excel_roundtrip_indexname(self, merge_cells, path):
@@ -602,8 +611,8 @@ def test_excel_roundtrip_indexname(self, merge_cells, path):
df.to_excel(path, merge_cells=merge_cells)
- xf = ExcelFile(path)
- result = pd.read_excel(xf, sheet_name=xf.sheet_names[0], index_col=0)
+ with ExcelFile(path) as xf:
+ result = pd.read_excel(xf, sheet_name=xf.sheet_names[0], index_col=0)
tm.assert_frame_equal(result, df)
assert result.index.name == "foo"
@@ -620,8 +629,8 @@ def test_excel_roundtrip_datetime(self, merge_cells, tsframe, path):
tsf.index = [x.date() for x in tsframe.index]
tsf.to_excel(path, "test1", merge_cells=merge_cells)
- reader = ExcelFile(path)
- recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
+ with ExcelFile(path) as reader:
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
tm.assert_frame_equal(tsframe, recons)
@@ -680,9 +689,8 @@ def test_to_excel_interval_no_labels(self, path):
expected["new"] = pd.cut(expected[0], 10).astype(str)
df.to_excel(path, "test1")
- reader = ExcelFile(path)
-
- recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
+ with ExcelFile(path) as reader:
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
tm.assert_frame_equal(expected, recons)
def test_to_excel_interval_labels(self, path):
@@ -698,9 +706,8 @@ def test_to_excel_interval_labels(self, path):
expected["new"] = pd.Series(list(intervals))
df.to_excel(path, "test1")
- reader = ExcelFile(path)
-
- recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
+ with ExcelFile(path) as reader:
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
tm.assert_frame_equal(expected, recons)
def test_to_excel_timedelta(self, path):
@@ -718,9 +725,8 @@ def test_to_excel_timedelta(self, path):
)
df.to_excel(path, "test1")
- reader = ExcelFile(path)
-
- recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
+ with ExcelFile(path) as reader:
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
tm.assert_frame_equal(expected, recons)
def test_to_excel_periodindex(self, tsframe, path):
@@ -728,8 +734,8 @@ def test_to_excel_periodindex(self, tsframe, path):
xp.to_excel(path, "sht1")
- reader = ExcelFile(path)
- rs = pd.read_excel(reader, sheet_name="sht1", index_col=0)
+ with ExcelFile(path) as reader:
+ rs = pd.read_excel(reader, sheet_name="sht1", index_col=0)
tm.assert_frame_equal(xp, rs.to_period("M"))
def test_to_excel_multiindex(self, merge_cells, frame, path):
@@ -742,8 +748,8 @@ def test_to_excel_multiindex(self, merge_cells, frame, path):
# round trip
frame.to_excel(path, "test1", merge_cells=merge_cells)
- reader = ExcelFile(path)
- df = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1])
+ with ExcelFile(path) as reader:
+ df = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1])
tm.assert_frame_equal(frame, df)
# GH13511
@@ -771,8 +777,10 @@ def test_to_excel_multiindex_cols(self, merge_cells, frame, path):
# round trip
frame.to_excel(path, "test1", merge_cells=merge_cells)
- reader = ExcelFile(path)
- df = pd.read_excel(reader, sheet_name="test1", header=header, index_col=[0, 1])
+ with ExcelFile(path) as reader:
+ df = pd.read_excel(
+ reader, sheet_name="test1", header=header, index_col=[0, 1]
+ )
if not merge_cells:
fm = frame.columns.format(sparsify=False, adjoin=False, names=False)
frame.columns = [".".join(map(str, q)) for q in zip(*fm)]
@@ -785,8 +793,8 @@ def test_to_excel_multiindex_dates(self, merge_cells, tsframe, path):
tsframe.index.names = ["time", "foo"]
tsframe.to_excel(path, "test1", merge_cells=merge_cells)
- reader = ExcelFile(path)
- recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1])
+ with ExcelFile(path) as reader:
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1])
tm.assert_frame_equal(tsframe, recons)
assert recons.index.names == ("time", "foo")
@@ -806,8 +814,8 @@ def test_to_excel_multiindex_no_write_index(self, path):
frame2.to_excel(path, "test1", index=False)
# Read it back in.
- reader = ExcelFile(path)
- frame3 = pd.read_excel(reader, sheet_name="test1")
+ with ExcelFile(path) as reader:
+ frame3 = pd.read_excel(reader, sheet_name="test1")
# Test that it is the same as the initial frame.
tm.assert_frame_equal(frame1, frame3)
@@ -820,8 +828,8 @@ def test_to_excel_float_format(self, path):
)
df.to_excel(path, "test1", float_format="%.2f")
- reader = ExcelFile(path)
- result = pd.read_excel(reader, sheet_name="test1", index_col=0)
+ with ExcelFile(path) as reader:
+ result = pd.read_excel(reader, sheet_name="test1", index_col=0)
expected = DataFrame(
[[0.12, 0.23, 0.57], [12.32, 123123.20, 321321.20]],
@@ -979,8 +987,10 @@ def test_excel_010_hemstring(
def roundtrip(data, header=True, parser_hdr=0, index=True):
data.to_excel(path, header=header, merge_cells=merge_cells, index=index)
- xf = ExcelFile(path)
- return pd.read_excel(xf, sheet_name=xf.sheet_names[0], header=parser_hdr)
+ with ExcelFile(path) as xf:
+ return pd.read_excel(
+ xf, sheet_name=xf.sheet_names[0], header=parser_hdr
+ )
# Basic test.
parser_header = 0 if use_headers else None
diff --git a/pandas/tests/io/formats/test_info.py b/pandas/tests/io/formats/test_info.py
index 2045557e5134a..4990a14f302a6 100644
--- a/pandas/tests/io/formats/test_info.py
+++ b/pandas/tests/io/formats/test_info.py
@@ -162,9 +162,9 @@ def test_info_verbose_with_counts_spacing(
):
"""Test header column, spacer, first line and last line in verbose mode."""
frame = DataFrame(np.random.randn(3, size))
- buf = StringIO()
- frame.info(verbose=True, show_counts=True, buf=buf)
- all_lines = buf.getvalue().splitlines()
+ with StringIO() as buf:
+ frame.info(verbose=True, show_counts=True, buf=buf)
+ all_lines = buf.getvalue().splitlines()
# Here table would contain only header, separator and table lines
# dframe repr, index summary, memory usage and dtypes are excluded
table = all_lines[3:-2]
diff --git a/pandas/tests/io/generate_legacy_storage_files.py b/pandas/tests/io/generate_legacy_storage_files.py
index be6cdf1696882..f33299a1b14de 100644
--- a/pandas/tests/io/generate_legacy_storage_files.py
+++ b/pandas/tests/io/generate_legacy_storage_files.py
@@ -327,9 +327,8 @@ def write_legacy_pickles(output_dir):
pth = f"{platform_name()}.pickle"
- fh = open(os.path.join(output_dir, pth), "wb")
- pickle.dump(create_pickle_data(), fh, pickle.DEFAULT_PROTOCOL)
- fh.close()
+ with open(os.path.join(output_dir, pth), "wb") as fh:
+ pickle.dump(create_pickle_data(), fh, pickle.DEFAULT_PROTOCOL)
print(f"created pickle file: {pth}")
diff --git a/pandas/tests/io/parser/test_c_parser_only.py b/pandas/tests/io/parser/test_c_parser_only.py
index da778093237b0..b23dfa6ef1548 100644
--- a/pandas/tests/io/parser/test_c_parser_only.py
+++ b/pandas/tests/io/parser/test_c_parser_only.py
@@ -305,9 +305,9 @@ def test_grow_boundary_at_cap(c_parser_only):
parser = c_parser_only
def test_empty_header_read(count):
- s = StringIO("," * count)
- expected = DataFrame(columns=[f"Unnamed: {i}" for i in range(count + 1)])
- df = parser.read_csv(s)
+ with StringIO("," * count) as s:
+ expected = DataFrame(columns=[f"Unnamed: {i}" for i in range(count + 1)])
+ df = parser.read_csv(s)
tm.assert_frame_equal(df, expected)
for cnt in range(1, 101):
diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py
index 3727fe9484084..657793450df5b 100644
--- a/pandas/tests/io/parser/test_network.py
+++ b/pandas/tests/io/parser/test_network.py
@@ -250,7 +250,8 @@ def test_read_csv_handles_boto_s3_object(self, s3_resource, tips_file):
Bucket="pandas-test", Key="tips.csv"
)
- result = read_csv(BytesIO(s3_object["Body"].read()), encoding="utf8")
+ with BytesIO(s3_object["Body"].read()) as buffer:
+ result = read_csv(buffer, encoding="utf8")
assert isinstance(result, DataFrame)
assert not result.empty
diff --git a/pandas/tests/io/test_user_agent.py b/pandas/tests/io/test_user_agent.py
index 0518ffca64cb2..87f08a42b91dd 100644
--- a/pandas/tests/io/test_user_agent.py
+++ b/pandas/tests/io/test_user_agent.py
@@ -209,16 +209,16 @@ def test_server_and_default_headers(responder, read_method, port, parquet_engine
if parquet_engine == "fastparquet":
pytest.importorskip("fsspec")
- server = http.server.HTTPServer(("localhost", port), responder)
- server_thread = threading.Thread(target=server.serve_forever)
- server_thread.start()
- if parquet_engine is None:
- df_http = read_method(f"http://localhost:{port}")
- else:
- df_http = read_method(f"http://localhost:{port}", engine=parquet_engine)
- server.shutdown()
- server.server_close()
- server_thread.join()
+ with http.server.HTTPServer(("localhost", port), responder) as server:
+ server_thread = threading.Thread(target=server.serve_forever)
+ server_thread.start()
+ if parquet_engine is None:
+ df_http = read_method(f"http://localhost:{port}")
+ else:
+ df_http = read_method(f"http://localhost:{port}", engine=parquet_engine)
+ server.shutdown()
+ server.server_close()
+ server_thread.join()
assert not df_http.empty
@@ -255,25 +255,25 @@ def test_server_and_custom_headers(responder, read_method, port, parquet_engine)
custom_user_agent = "Super Cool One"
df_true = pd.DataFrame({"header": [custom_user_agent]})
- server = http.server.HTTPServer(("localhost", port), responder)
- server_thread = threading.Thread(target=server.serve_forever)
- server_thread.start()
-
- if parquet_engine is None:
- df_http = read_method(
- f"http://localhost:{port}",
- storage_options={"User-Agent": custom_user_agent},
- )
- else:
- df_http = read_method(
- f"http://localhost:{port}",
- storage_options={"User-Agent": custom_user_agent},
- engine=parquet_engine,
- )
- server.shutdown()
-
- server.server_close()
- server_thread.join()
+ with http.server.HTTPServer(("localhost", port), responder) as server:
+ server_thread = threading.Thread(target=server.serve_forever)
+ server_thread.start()
+
+ if parquet_engine is None:
+ df_http = read_method(
+ f"http://localhost:{port}",
+ storage_options={"User-Agent": custom_user_agent},
+ )
+ else:
+ df_http = read_method(
+ f"http://localhost:{port}",
+ storage_options={"User-Agent": custom_user_agent},
+ engine=parquet_engine,
+ )
+ server.shutdown()
+
+ server.server_close()
+ server_thread.join()
tm.assert_frame_equal(df_true, df_http)
@@ -291,17 +291,17 @@ def test_server_and_all_custom_headers(responder, read_method, port):
"User-Agent": custom_user_agent,
"Auth": custom_auth_token,
}
- server = http.server.HTTPServer(("localhost", port), responder)
- server_thread = threading.Thread(target=server.serve_forever)
- server_thread.start()
+ with http.server.HTTPServer(("localhost", port), responder) as server:
+ server_thread = threading.Thread(target=server.serve_forever)
+ server_thread.start()
- df_http = read_method(
- f"http://localhost:{port}",
- storage_options=storage_options,
- )
- server.shutdown()
- server.server_close()
- server_thread.join()
+ df_http = read_method(
+ f"http://localhost:{port}",
+ storage_options=storage_options,
+ )
+ server.shutdown()
+ server.server_close()
+ server_thread.join()
df_http = df_http[df_http["0"].isin(storage_options.keys())]
df_http = df_http.sort_values(["0"]).reset_index()
| spin off from #39047: use a few more context managers | https://api.github.com/repos/pandas-dev/pandas/pulls/39785 | 2021-02-13T01:44:36Z | 2021-02-13T02:33:12Z | 2021-02-13T02:33:12Z | 2021-02-13T03:08:03Z |
DOC: Add reference to Text Extensions for Pandas project | diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst
index bb89b91954518..4b69d5b0c8c77 100644
--- a/doc/source/ecosystem.rst
+++ b/doc/source/ecosystem.rst
@@ -476,6 +476,14 @@ storing numeric arrays with units. These arrays can be stored inside pandas'
Series and DataFrame. Operations between Series and DataFrame columns which
use pint's extension array are then units aware.
+`Text Extensions for Pandas`_
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+``Text Extensions for Pandas <https://ibm.biz/text-extensions-for-pandas>``
+provides extension types to cover common data structures for representing natural language
+data, plus library integrations that convert the outputs of popular natural language
+processing libraries into Pandas DataFrames.
+
.. _ecosystem.accessors:
Accessors
| This PR adds a reference to our Text Extensions for Pandas library, which adds extension types for representing natural language processing data in Pandas DataFrames, to the "Pandas ecosystem" section of the documentation.
Main web page for our project: https://ibm.biz/text-extensions-for-pandas
Source code: https://github.com/CODAIT/text-extensions-for-pandas
API docs: https://text-extensions-for-pandas.readthedocs.io/
| https://api.github.com/repos/pandas-dev/pandas/pulls/39783 | 2021-02-13T00:07:59Z | 2021-02-15T22:43:18Z | 2021-02-15T22:43:18Z | 2021-02-15T22:43:49Z |
CLN: remove redundant openpyxl type conversions | diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py
index 3a753a707166e..6ebb04eb19534 100644
--- a/pandas/io/excel/_openpyxl.py
+++ b/pandas/io/excel/_openpyxl.py
@@ -509,24 +509,14 @@ def get_sheet_by_index(self, index: int):
def _convert_cell(self, cell, convert_float: bool) -> Scalar:
- from openpyxl.cell.cell import TYPE_BOOL, TYPE_ERROR, TYPE_NUMERIC
+ from openpyxl.cell.cell import TYPE_ERROR, TYPE_NUMERIC
if cell.value is None:
return "" # compat with xlrd
- elif cell.is_date:
- return cell.value
elif cell.data_type == TYPE_ERROR:
return np.nan
- elif cell.data_type == TYPE_BOOL:
- return bool(cell.value)
- elif cell.data_type == TYPE_NUMERIC:
- # GH5394
- if convert_float:
- val = int(cell.value)
- if val == cell.value:
- return val
- else:
- return float(cell.value)
+ elif not convert_float and cell.data_type == TYPE_NUMERIC:
+ return float(cell.value)
return cell.value
| openpyxl already converts cell values to Python types, preferring
integers where possible. For backwards-compatibility, we have to convert
integers back to float if not `convert_float`
- [ ] closes #xxxx
- [x] tests passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39782 | 2021-02-12T21:34:44Z | 2021-02-15T23:32:25Z | 2021-02-15T23:32:25Z | 2021-04-23T18:51:49Z |
REF: dispatch maybe_promote to infer_dtype_from_scalar for td64 dtype | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 74d750288bdeb..e176c13f4874b 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -590,24 +590,10 @@ def maybe_promote(dtype: np.dtype, fill_value=np.nan):
return np.dtype(object), fill_value
elif issubclass(dtype.type, np.timedelta64):
- if (
- is_integer(fill_value)
- or is_float(fill_value)
- or isinstance(fill_value, str)
- ):
- # TODO: What about str that can be a timedelta?
- dtype = np.dtype(np.object_)
- else:
- try:
- fv = Timedelta(fill_value)
- except ValueError:
- dtype = np.dtype(np.object_)
- else:
- if fv is NaT:
- # NaT has no `to_timedelta64` method
- fill_value = np.timedelta64("NaT", "ns")
- else:
- fill_value = fv.to_timedelta64()
+ inferred, fv = infer_dtype_from_scalar(fill_value, pandas_dtype=True)
+ if inferred == dtype:
+ return dtype, fv
+ return np.dtype(object), fill_value
elif is_float(fill_value):
if issubclass(dtype.type, np.bool_):
@@ -763,11 +749,12 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> Tuple[DtypeObj,
elif isinstance(val, (np.timedelta64, timedelta)):
try:
- val = Timedelta(val).value
+ val = Timedelta(val)
except (OutOfBoundsTimedelta, OverflowError):
dtype = np.dtype(object)
else:
dtype = np.dtype("m8[ns]")
+ val = np.timedelta64(val.value, "ns")
elif is_bool(val):
dtype = np.dtype(np.bool_)
| sits on top of #39767 | https://api.github.com/repos/pandas-dev/pandas/pulls/39781 | 2021-02-12T19:50:50Z | 2021-02-16T22:55:18Z | 2021-02-16T22:55:18Z | 2021-02-16T23:04:38Z |
STYLE use force-grid-wrap in isort | diff --git a/asv_bench/benchmarks/arithmetic.py b/asv_bench/benchmarks/arithmetic.py
index 7478efbf22609..a696f0e180e86 100644
--- a/asv_bench/benchmarks/arithmetic.py
+++ b/asv_bench/benchmarks/arithmetic.py
@@ -4,7 +4,13 @@
import numpy as np
import pandas as pd
-from pandas import DataFrame, Series, Timestamp, date_range, to_timedelta
+from pandas import (
+ DataFrame,
+ Series,
+ Timestamp,
+ date_range,
+ to_timedelta,
+)
import pandas._testing as tm
from pandas.core.algorithms import checked_add_with_arr
diff --git a/asv_bench/benchmarks/ctors.py b/asv_bench/benchmarks/ctors.py
index 7c43485f5ef45..5993b068feadf 100644
--- a/asv_bench/benchmarks/ctors.py
+++ b/asv_bench/benchmarks/ctors.py
@@ -1,6 +1,12 @@
import numpy as np
-from pandas import DatetimeIndex, Index, MultiIndex, Series, Timestamp
+from pandas import (
+ DatetimeIndex,
+ Index,
+ MultiIndex,
+ Series,
+ Timestamp,
+)
from .pandas_vb_common import tm
diff --git a/asv_bench/benchmarks/dtypes.py b/asv_bench/benchmarks/dtypes.py
index 3efcf46955e2b..9209e851289bb 100644
--- a/asv_bench/benchmarks/dtypes.py
+++ b/asv_bench/benchmarks/dtypes.py
@@ -5,7 +5,10 @@
import pandas as pd
from pandas import DataFrame
import pandas._testing as tm
-from pandas.api.types import is_extension_array_dtype, pandas_dtype
+from pandas.api.types import (
+ is_extension_array_dtype,
+ pandas_dtype,
+)
from .pandas_vb_common import (
datetime_dtypes,
diff --git a/asv_bench/benchmarks/frame_ctor.py b/asv_bench/benchmarks/frame_ctor.py
index e0a2257b0ca1f..3367898101528 100644
--- a/asv_bench/benchmarks/frame_ctor.py
+++ b/asv_bench/benchmarks/frame_ctor.py
@@ -1,12 +1,21 @@
import numpy as np
import pandas as pd
-from pandas import DataFrame, MultiIndex, Series, Timestamp, date_range
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+ Timestamp,
+ date_range,
+)
from .pandas_vb_common import tm
try:
- from pandas.tseries.offsets import Hour, Nano
+ from pandas.tseries.offsets import (
+ Hour,
+ Nano,
+ )
except ImportError:
# For compatibility with older versions
from pandas.core.datetools import * # noqa
diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py
index dc6fd2ff61423..bd068cec4641b 100644
--- a/asv_bench/benchmarks/frame_methods.py
+++ b/asv_bench/benchmarks/frame_methods.py
@@ -3,7 +3,15 @@
import numpy as np
-from pandas import DataFrame, MultiIndex, NaT, Series, date_range, isnull, period_range
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ NaT,
+ Series,
+ date_range,
+ isnull,
+ period_range,
+)
from .pandas_vb_common import tm
diff --git a/asv_bench/benchmarks/gil.py b/asv_bench/benchmarks/gil.py
index 47523005a877f..410668ca3c7cf 100644
--- a/asv_bench/benchmarks/gil.py
+++ b/asv_bench/benchmarks/gil.py
@@ -1,6 +1,12 @@
import numpy as np
-from pandas import DataFrame, Series, date_range, factorize, read_csv
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+ factorize,
+ read_csv,
+)
from pandas.core.algorithms import take_nd
from .pandas_vb_common import tm
diff --git a/asv_bench/benchmarks/inference.py b/asv_bench/benchmarks/inference.py
index e17c985321c47..b6808ace629db 100644
--- a/asv_bench/benchmarks/inference.py
+++ b/asv_bench/benchmarks/inference.py
@@ -1,8 +1,14 @@
import numpy as np
-from pandas import Series, to_numeric
-
-from .pandas_vb_common import lib, tm
+from pandas import (
+ Series,
+ to_numeric,
+)
+
+from .pandas_vb_common import (
+ lib,
+ tm,
+)
class ToNumeric:
diff --git a/asv_bench/benchmarks/io/csv.py b/asv_bench/benchmarks/io/csv.py
index 12de9b121ef6d..5ff9431fbf8e4 100644
--- a/asv_bench/benchmarks/io/csv.py
+++ b/asv_bench/benchmarks/io/csv.py
@@ -1,12 +1,24 @@
-from io import BytesIO, StringIO
+from io import (
+ BytesIO,
+ StringIO,
+)
import random
import string
import numpy as np
-from pandas import Categorical, DataFrame, date_range, read_csv, to_datetime
-
-from ..pandas_vb_common import BaseIO, tm
+from pandas import (
+ Categorical,
+ DataFrame,
+ date_range,
+ read_csv,
+ to_datetime,
+)
+
+from ..pandas_vb_common import (
+ BaseIO,
+ tm,
+)
class ToCSV(BaseIO):
diff --git a/asv_bench/benchmarks/io/excel.py b/asv_bench/benchmarks/io/excel.py
index 7efaeddecd423..3363b43f29b78 100644
--- a/asv_bench/benchmarks/io/excel.py
+++ b/asv_bench/benchmarks/io/excel.py
@@ -2,10 +2,19 @@
import numpy as np
from odf.opendocument import OpenDocumentSpreadsheet
-from odf.table import Table, TableCell, TableRow
+from odf.table import (
+ Table,
+ TableCell,
+ TableRow,
+)
from odf.text import P
-from pandas import DataFrame, ExcelWriter, date_range, read_excel
+from pandas import (
+ DataFrame,
+ ExcelWriter,
+ date_range,
+ read_excel,
+)
from ..pandas_vb_common import tm
diff --git a/asv_bench/benchmarks/io/hdf.py b/asv_bench/benchmarks/io/hdf.py
index 4ca399a293a4b..4a2c1c872e6eb 100644
--- a/asv_bench/benchmarks/io/hdf.py
+++ b/asv_bench/benchmarks/io/hdf.py
@@ -1,8 +1,16 @@
import numpy as np
-from pandas import DataFrame, HDFStore, date_range, read_hdf
-
-from ..pandas_vb_common import BaseIO, tm
+from pandas import (
+ DataFrame,
+ HDFStore,
+ date_range,
+ read_hdf,
+)
+
+from ..pandas_vb_common import (
+ BaseIO,
+ tm,
+)
class HDFStoreDataFrame(BaseIO):
diff --git a/asv_bench/benchmarks/io/json.py b/asv_bench/benchmarks/io/json.py
index ed0fb5b8fe342..00f3278ced98b 100644
--- a/asv_bench/benchmarks/io/json.py
+++ b/asv_bench/benchmarks/io/json.py
@@ -2,9 +2,18 @@
import numpy as np
-from pandas import DataFrame, concat, date_range, read_json, timedelta_range
-
-from ..pandas_vb_common import BaseIO, tm
+from pandas import (
+ DataFrame,
+ concat,
+ date_range,
+ read_json,
+ timedelta_range,
+)
+
+from ..pandas_vb_common import (
+ BaseIO,
+ tm,
+)
class ReadJSON(BaseIO):
diff --git a/asv_bench/benchmarks/io/pickle.py b/asv_bench/benchmarks/io/pickle.py
index 656fe2197bc8a..c71cdcdcc5c59 100644
--- a/asv_bench/benchmarks/io/pickle.py
+++ b/asv_bench/benchmarks/io/pickle.py
@@ -1,8 +1,15 @@
import numpy as np
-from pandas import DataFrame, date_range, read_pickle
-
-from ..pandas_vb_common import BaseIO, tm
+from pandas import (
+ DataFrame,
+ date_range,
+ read_pickle,
+)
+
+from ..pandas_vb_common import (
+ BaseIO,
+ tm,
+)
class Pickle(BaseIO):
diff --git a/asv_bench/benchmarks/io/sql.py b/asv_bench/benchmarks/io/sql.py
index b71bb832280b9..3cfa28de78c90 100644
--- a/asv_bench/benchmarks/io/sql.py
+++ b/asv_bench/benchmarks/io/sql.py
@@ -3,7 +3,12 @@
import numpy as np
from sqlalchemy import create_engine
-from pandas import DataFrame, date_range, read_sql_query, read_sql_table
+from pandas import (
+ DataFrame,
+ date_range,
+ read_sql_query,
+ read_sql_table,
+)
from ..pandas_vb_common import tm
diff --git a/asv_bench/benchmarks/io/stata.py b/asv_bench/benchmarks/io/stata.py
index 9faafa82ff46e..4ae2745af8bff 100644
--- a/asv_bench/benchmarks/io/stata.py
+++ b/asv_bench/benchmarks/io/stata.py
@@ -1,8 +1,15 @@
import numpy as np
-from pandas import DataFrame, date_range, read_stata
-
-from ..pandas_vb_common import BaseIO, tm
+from pandas import (
+ DataFrame,
+ date_range,
+ read_stata,
+)
+
+from ..pandas_vb_common import (
+ BaseIO,
+ tm,
+)
class Stata(BaseIO):
diff --git a/asv_bench/benchmarks/join_merge.py b/asv_bench/benchmarks/join_merge.py
index b0ad43ace88b5..27eaecff09d0f 100644
--- a/asv_bench/benchmarks/join_merge.py
+++ b/asv_bench/benchmarks/join_merge.py
@@ -2,7 +2,15 @@
import numpy as np
-from pandas import DataFrame, MultiIndex, Series, concat, date_range, merge, merge_asof
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+ concat,
+ date_range,
+ merge,
+ merge_asof,
+)
from .pandas_vb_common import tm
diff --git a/asv_bench/benchmarks/multiindex_object.py b/asv_bench/benchmarks/multiindex_object.py
index 18dbb7eae0615..25df5b0214959 100644
--- a/asv_bench/benchmarks/multiindex_object.py
+++ b/asv_bench/benchmarks/multiindex_object.py
@@ -2,7 +2,12 @@
import numpy as np
-from pandas import DataFrame, MultiIndex, RangeIndex, date_range
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ RangeIndex,
+ date_range,
+)
from .pandas_vb_common import tm
diff --git a/asv_bench/benchmarks/period.py b/asv_bench/benchmarks/period.py
index 74193ee62cfae..4f81aee62c202 100644
--- a/asv_bench/benchmarks/period.py
+++ b/asv_bench/benchmarks/period.py
@@ -2,7 +2,14 @@
Period benchmarks with non-tslibs dependencies. See
benchmarks.tslibs.period for benchmarks that rely only on tslibs.
"""
-from pandas import DataFrame, Period, PeriodIndex, Series, date_range, period_range
+from pandas import (
+ DataFrame,
+ Period,
+ PeriodIndex,
+ Series,
+ date_range,
+ period_range,
+)
from pandas.tseries.frequencies import to_offset
diff --git a/asv_bench/benchmarks/plotting.py b/asv_bench/benchmarks/plotting.py
index 5c718516360ed..11e43401f9395 100644
--- a/asv_bench/benchmarks/plotting.py
+++ b/asv_bench/benchmarks/plotting.py
@@ -1,7 +1,12 @@
import matplotlib
import numpy as np
-from pandas import DataFrame, DatetimeIndex, Series, date_range
+from pandas import (
+ DataFrame,
+ DatetimeIndex,
+ Series,
+ date_range,
+)
try:
from pandas.plotting import andrews_curves
diff --git a/asv_bench/benchmarks/reindex.py b/asv_bench/benchmarks/reindex.py
index 03394e6fe08cb..65392f2cea65b 100644
--- a/asv_bench/benchmarks/reindex.py
+++ b/asv_bench/benchmarks/reindex.py
@@ -1,8 +1,18 @@
import numpy as np
-from pandas import DataFrame, Index, MultiIndex, Series, date_range, period_range
-
-from .pandas_vb_common import lib, tm
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ date_range,
+ period_range,
+)
+
+from .pandas_vb_common import (
+ lib,
+ tm,
+)
class Reindex:
diff --git a/asv_bench/benchmarks/reshape.py b/asv_bench/benchmarks/reshape.py
index da1592a2f1ab0..faee9bc57464b 100644
--- a/asv_bench/benchmarks/reshape.py
+++ b/asv_bench/benchmarks/reshape.py
@@ -4,7 +4,13 @@
import numpy as np
import pandas as pd
-from pandas import DataFrame, MultiIndex, date_range, melt, wide_to_long
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ date_range,
+ melt,
+ wide_to_long,
+)
from pandas.api.types import CategoricalDtype
diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py
index b8f6cb53987b8..a6bffb1585f2a 100644
--- a/asv_bench/benchmarks/series_methods.py
+++ b/asv_bench/benchmarks/series_methods.py
@@ -4,7 +4,12 @@
from pandas.compat.numpy import np_version_under1p20
-from pandas import Categorical, NaT, Series, date_range
+from pandas import (
+ Categorical,
+ NaT,
+ Series,
+ date_range,
+)
from .pandas_vb_common import tm
diff --git a/asv_bench/benchmarks/sparse.py b/asv_bench/benchmarks/sparse.py
index 28ceb25eebd96..5006a0dbf1f98 100644
--- a/asv_bench/benchmarks/sparse.py
+++ b/asv_bench/benchmarks/sparse.py
@@ -2,7 +2,11 @@
import scipy.sparse
import pandas as pd
-from pandas import MultiIndex, Series, date_range
+from pandas import (
+ MultiIndex,
+ Series,
+ date_range,
+)
from pandas.arrays import SparseArray
diff --git a/asv_bench/benchmarks/strings.py b/asv_bench/benchmarks/strings.py
index 7c75ad031e7cd..76257e1b40f1a 100644
--- a/asv_bench/benchmarks/strings.py
+++ b/asv_bench/benchmarks/strings.py
@@ -2,7 +2,11 @@
import numpy as np
-from pandas import Categorical, DataFrame, Series
+from pandas import (
+ Categorical,
+ DataFrame,
+ Series,
+)
from .pandas_vb_common import tm
diff --git a/asv_bench/benchmarks/timedelta.py b/asv_bench/benchmarks/timedelta.py
index 207010b8cc943..9e221ee030e6d 100644
--- a/asv_bench/benchmarks/timedelta.py
+++ b/asv_bench/benchmarks/timedelta.py
@@ -5,7 +5,12 @@
import numpy as np
-from pandas import DataFrame, Series, timedelta_range, to_timedelta
+from pandas import (
+ DataFrame,
+ Series,
+ timedelta_range,
+ to_timedelta,
+)
class ToTimedelta:
diff --git a/asv_bench/benchmarks/tslibs/normalize.py b/asv_bench/benchmarks/tslibs/normalize.py
index 9a206410d8775..292f57d7f5c77 100644
--- a/asv_bench/benchmarks/tslibs/normalize.py
+++ b/asv_bench/benchmarks/tslibs/normalize.py
@@ -1,5 +1,8 @@
try:
- from pandas._libs.tslibs import is_date_array_normalized, normalize_i8_timestamps
+ from pandas._libs.tslibs import (
+ is_date_array_normalized,
+ normalize_i8_timestamps,
+ )
except ImportError:
from pandas._libs.tslibs.conversion import (
normalize_i8_timestamps,
@@ -8,7 +11,10 @@
import pandas as pd
-from .tslib import _sizes, _tzs
+from .tslib import (
+ _sizes,
+ _tzs,
+)
class Normalize:
diff --git a/asv_bench/benchmarks/tslibs/period.py b/asv_bench/benchmarks/tslibs/period.py
index 849e8ec864ac2..f2efee33c6da7 100644
--- a/asv_bench/benchmarks/tslibs/period.py
+++ b/asv_bench/benchmarks/tslibs/period.py
@@ -5,11 +5,17 @@
import numpy as np
-from pandas._libs.tslibs.period import Period, periodarr_to_dt64arr
+from pandas._libs.tslibs.period import (
+ Period,
+ periodarr_to_dt64arr,
+)
from pandas.tseries.frequencies import to_offset
-from .tslib import _sizes, _tzs
+from .tslib import (
+ _sizes,
+ _tzs,
+)
try:
from pandas._libs.tslibs.vectorized import dt64arr_to_periodarr
diff --git a/asv_bench/benchmarks/tslibs/resolution.py b/asv_bench/benchmarks/tslibs/resolution.py
index 280be7932d4db..0d22ff77ee308 100644
--- a/asv_bench/benchmarks/tslibs/resolution.py
+++ b/asv_bench/benchmarks/tslibs/resolution.py
@@ -17,9 +17,15 @@
df.loc[key] = (val.average, val.stdev)
"""
-from datetime import timedelta, timezone
-
-from dateutil.tz import gettz, tzlocal
+from datetime import (
+ timedelta,
+ timezone,
+)
+
+from dateutil.tz import (
+ gettz,
+ tzlocal,
+)
import numpy as np
import pytz
diff --git a/asv_bench/benchmarks/tslibs/timestamp.py b/asv_bench/benchmarks/tslibs/timestamp.py
index 40f8e561f5238..86c8d735bdb27 100644
--- a/asv_bench/benchmarks/tslibs/timestamp.py
+++ b/asv_bench/benchmarks/tslibs/timestamp.py
@@ -1,6 +1,14 @@
-from datetime import datetime, timedelta, timezone
-
-from dateutil.tz import gettz, tzlocal, tzutc
+from datetime import (
+ datetime,
+ timedelta,
+ timezone,
+)
+
+from dateutil.tz import (
+ gettz,
+ tzlocal,
+ tzutc,
+)
import numpy as np
import pytz
diff --git a/asv_bench/benchmarks/tslibs/tslib.py b/asv_bench/benchmarks/tslibs/tslib.py
index 5952a402bf89a..17beada916e46 100644
--- a/asv_bench/benchmarks/tslibs/tslib.py
+++ b/asv_bench/benchmarks/tslibs/tslib.py
@@ -15,9 +15,15 @@
val = %timeit -o tr.time_ints_to_pydatetime(box, size, tz)
df.loc[key] = (val.average, val.stdev)
"""
-from datetime import timedelta, timezone
+from datetime import (
+ timedelta,
+ timezone,
+)
-from dateutil.tz import gettz, tzlocal
+from dateutil.tz import (
+ gettz,
+ tzlocal,
+)
import numpy as np
import pytz
diff --git a/asv_bench/benchmarks/tslibs/tz_convert.py b/asv_bench/benchmarks/tslibs/tz_convert.py
index c2c90024ca5bd..89b39c1f8919f 100644
--- a/asv_bench/benchmarks/tslibs/tz_convert.py
+++ b/asv_bench/benchmarks/tslibs/tz_convert.py
@@ -3,7 +3,10 @@
from pandas._libs.tslibs.tzconversion import tz_localize_to_utc
-from .tslib import _sizes, _tzs
+from .tslib import (
+ _sizes,
+ _tzs,
+)
try:
old_sig = False
diff --git a/pandas/_config/config.py b/pandas/_config/config.py
index 512b638fc4877..47913c2a1cf7d 100644
--- a/pandas/_config/config.py
+++ b/pandas/_config/config.py
@@ -49,9 +49,22 @@
"""
from collections import namedtuple
-from contextlib import ContextDecorator, contextmanager
+from contextlib import (
+ ContextDecorator,
+ contextmanager,
+)
import re
-from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type, cast
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ Iterable,
+ List,
+ Optional,
+ Tuple,
+ Type,
+ cast,
+)
import warnings
from pandas._typing import F
diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx
index 080a84bef1e58..1a1b263ae356e 100644
--- a/pandas/_libs/algos.pyx
+++ b/pandas/_libs/algos.pyx
@@ -1,8 +1,14 @@
import cython
from cython import Py_ssize_t
-from libc.math cimport fabs, sqrt
-from libc.stdlib cimport free, malloc
+from libc.math cimport (
+ fabs,
+ sqrt,
+)
+from libc.stdlib cimport (
+ free,
+ malloc,
+)
from libc.string cimport memmove
import numpy as np
@@ -46,7 +52,10 @@ from pandas._libs.khash cimport (
kh_resize_int64,
khiter_t,
)
-from pandas._libs.util cimport get_nat, numeric
+from pandas._libs.util cimport (
+ get_nat,
+ numeric,
+)
import pandas._libs.missing as missing
diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx
index 553ecbc58e745..43bf6d9dd1fee 100644
--- a/pandas/_libs/groupby.pyx
+++ b/pandas/_libs/groupby.pyx
@@ -2,7 +2,10 @@ import cython
from cython import Py_ssize_t
from cython cimport floating
-from libc.stdlib cimport free, malloc
+from libc.stdlib cimport (
+ free,
+ malloc,
+)
import numpy as np
@@ -27,9 +30,16 @@ from numpy.math cimport NAN
cnp.import_array()
from pandas._libs.algos cimport swap
-from pandas._libs.util cimport get_nat, numeric
+from pandas._libs.util cimport (
+ get_nat,
+ numeric,
+)
-from pandas._libs.algos import groupsort_indexer, rank_1d, take_2d_axis1_float64_float64
+from pandas._libs.algos import (
+ groupsort_indexer,
+ rank_1d,
+ take_2d_axis1_float64_float64,
+)
from pandas._libs.missing cimport checknull
diff --git a/pandas/_libs/hashing.pyx b/pandas/_libs/hashing.pyx
index f2af04d91a3e3..ead967386ed1d 100644
--- a/pandas/_libs/hashing.pyx
+++ b/pandas/_libs/hashing.pyx
@@ -3,11 +3,20 @@
import cython
-from libc.stdlib cimport free, malloc
+from libc.stdlib cimport (
+ free,
+ malloc,
+)
import numpy as np
-from numpy cimport import_array, ndarray, uint8_t, uint32_t, uint64_t
+from numpy cimport (
+ import_array,
+ ndarray,
+ uint8_t,
+ uint32_t,
+ uint64_t,
+)
import_array()
diff --git a/pandas/_libs/hashtable.pxd b/pandas/_libs/hashtable.pxd
index cc9341665b8db..735d8c07f4774 100644
--- a/pandas/_libs/hashtable.pxd
+++ b/pandas/_libs/hashtable.pxd
@@ -1,4 +1,7 @@
-from numpy cimport intp_t, ndarray
+from numpy cimport (
+ intp_t,
+ ndarray,
+)
from pandas._libs.khash cimport (
complex64_t,
diff --git a/pandas/_libs/hashtable.pyx b/pandas/_libs/hashtable.pyx
index 3527fe2d8cd8d..1bbffaa7bb5d2 100644
--- a/pandas/_libs/hashtable.pyx
+++ b/pandas/_libs/hashtable.pyx
@@ -1,12 +1,26 @@
cimport cython
-from cpython.mem cimport PyMem_Free, PyMem_Malloc
-from cpython.ref cimport Py_INCREF, PyObject
-from libc.stdlib cimport free, malloc
+from cpython.mem cimport (
+ PyMem_Free,
+ PyMem_Malloc,
+)
+from cpython.ref cimport (
+ Py_INCREF,
+ PyObject,
+)
+from libc.stdlib cimport (
+ free,
+ malloc,
+)
import numpy as np
cimport numpy as cnp
-from numpy cimport float64_t, ndarray, uint8_t, uint32_t
+from numpy cimport (
+ float64_t,
+ ndarray,
+ uint8_t,
+ uint32_t,
+)
from numpy.math cimport NAN
cnp.import_array()
diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx
index e31c3739f456d..cb7b9f990a98e 100644
--- a/pandas/_libs/index.pyx
+++ b/pandas/_libs/index.pyx
@@ -28,7 +28,10 @@ from pandas._libs.tslibs.period cimport is_period_object
from pandas._libs.tslibs.timedeltas cimport _Timedelta
from pandas._libs.tslibs.timestamps cimport _Timestamp
-from pandas._libs import algos, hashtable as _hash
+from pandas._libs import (
+ algos,
+ hashtable as _hash,
+)
from pandas._libs.missing import checknull
diff --git a/pandas/_libs/internals.pyx b/pandas/_libs/internals.pyx
index 006fd34632d5a..150b7f62b4b26 100644
--- a/pandas/_libs/internals.pyx
+++ b/pandas/_libs/internals.pyx
@@ -12,7 +12,10 @@ cdef extern from "Python.h":
import numpy as np
cimport numpy as cnp
-from numpy cimport NPY_INT64, int64_t
+from numpy cimport (
+ NPY_INT64,
+ int64_t,
+)
cnp.import_array()
diff --git a/pandas/_libs/interval.pyx b/pandas/_libs/interval.pyx
index 10becdce5d6dd..9ed8b71c2ce17 100644
--- a/pandas/_libs/interval.pyx
+++ b/pandas/_libs/interval.pyx
@@ -1,7 +1,13 @@
import numbers
-from operator import le, lt
+from operator import (
+ le,
+ lt,
+)
-from cpython.datetime cimport PyDateTime_IMPORT, PyDelta_Check
+from cpython.datetime cimport (
+ PyDateTime_IMPORT,
+ PyDelta_Check,
+)
PyDateTime_IMPORT
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index 3a11e7fbbdf33..3a64ecb7a8a18 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -14,10 +14,16 @@ from cpython.datetime cimport (
)
from cpython.iterator cimport PyIter_Check
from cpython.number cimport PyNumber_Check
-from cpython.object cimport Py_EQ, PyObject_RichCompareBool
+from cpython.object cimport (
+ Py_EQ,
+ PyObject_RichCompareBool,
+)
from cpython.ref cimport Py_INCREF
from cpython.sequence cimport PySequence_Check
-from cpython.tuple cimport PyTuple_New, PyTuple_SET_ITEM
+from cpython.tuple cimport (
+ PyTuple_New,
+ PyTuple_SET_ITEM,
+)
PyDateTime_IMPORT
@@ -66,7 +72,12 @@ cdef extern from "src/parse_helper.h":
int floatify(object, float64_t *result, int *maybe_int) except -1
from pandas._libs cimport util
-from pandas._libs.util cimport INT64_MAX, INT64_MIN, UINT64_MAX, is_nan
+from pandas._libs.util cimport (
+ INT64_MAX,
+ INT64_MIN,
+ UINT64_MAX,
+ is_nan,
+)
from pandas._libs.tslib import array_to_datetime
from pandas._libs.tslibs.period import Period
@@ -80,7 +91,11 @@ from pandas._libs.missing cimport (
isnaobj,
)
from pandas._libs.tslibs.conversion cimport convert_to_tsobject
-from pandas._libs.tslibs.nattype cimport NPY_NAT, c_NaT as NaT, checknull_with_nat
+from pandas._libs.tslibs.nattype cimport (
+ NPY_NAT,
+ c_NaT as NaT,
+ checknull_with_nat,
+)
from pandas._libs.tslibs.offsets cimport is_offset_object
from pandas._libs.tslibs.period cimport is_period_object
from pandas._libs.tslibs.timedeltas cimport convert_to_timedelta64
diff --git a/pandas/_libs/missing.pxd b/pandas/_libs/missing.pxd
index ce8e8007e7630..9d32fcd3625db 100644
--- a/pandas/_libs/missing.pxd
+++ b/pandas/_libs/missing.pxd
@@ -1,4 +1,7 @@
-from numpy cimport ndarray, uint8_t
+from numpy cimport (
+ ndarray,
+ uint8_t,
+)
cpdef bint is_matching_na(object left, object right, bint nan_matches_none=*)
diff --git a/pandas/_libs/missing.pyx b/pandas/_libs/missing.pyx
index d91d0261a1b33..f6f9e7410d34c 100644
--- a/pandas/_libs/missing.pyx
+++ b/pandas/_libs/missing.pyx
@@ -5,7 +5,12 @@ from cython import Py_ssize_t
import numpy as np
cimport numpy as cnp
-from numpy cimport float64_t, int64_t, ndarray, uint8_t
+from numpy cimport (
+ float64_t,
+ int64_t,
+ ndarray,
+ uint8_t,
+)
cnp.import_array()
@@ -15,7 +20,10 @@ from pandas._libs.tslibs.nattype cimport (
checknull_with_nat,
is_null_datetimelike,
)
-from pandas._libs.tslibs.np_datetime cimport get_datetime64_value, get_timedelta64_value
+from pandas._libs.tslibs.np_datetime cimport (
+ get_datetime64_value,
+ get_timedelta64_value,
+)
from pandas._libs.ops_dispatch import maybe_dispatch_ufunc_to_dunder_op
from pandas.compat import IS64
diff --git a/pandas/_libs/ops.pyx b/pandas/_libs/ops.pyx
index d1f897d237c1b..1e51a578c44ea 100644
--- a/pandas/_libs/ops.pyx
+++ b/pandas/_libs/ops.pyx
@@ -14,13 +14,20 @@ import cython
from cython import Py_ssize_t
import numpy as np
-from numpy cimport import_array, ndarray, uint8_t
+from numpy cimport (
+ import_array,
+ ndarray,
+ uint8_t,
+)
import_array()
from pandas._libs.missing cimport checknull
-from pandas._libs.util cimport UINT8_MAX, is_nan
+from pandas._libs.util cimport (
+ UINT8_MAX,
+ is_nan,
+)
@cython.wraparound(False)
diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx
index a72a2ff8eaf28..c4d98ccb88ba5 100644
--- a/pandas/_libs/parsers.pyx
+++ b/pandas/_libs/parsers.pyx
@@ -1,22 +1,36 @@
# Copyright (c) 2012, Lambda Foundry, Inc.
# See LICENSE for the license
-from csv import QUOTE_MINIMAL, QUOTE_NONE, QUOTE_NONNUMERIC
+from csv import (
+ QUOTE_MINIMAL,
+ QUOTE_NONE,
+ QUOTE_NONNUMERIC,
+)
from errno import ENOENT
import sys
import time
import warnings
from libc.stdlib cimport free
-from libc.string cimport strcasecmp, strlen, strncpy
+from libc.string cimport (
+ strcasecmp,
+ strlen,
+ strncpy,
+)
import cython
from cython import Py_ssize_t
from cpython.bytes cimport PyBytes_AsString
-from cpython.exc cimport PyErr_Fetch, PyErr_Occurred
+from cpython.exc cimport (
+ PyErr_Fetch,
+ PyErr_Occurred,
+)
from cpython.object cimport PyObject
from cpython.ref cimport Py_XDECREF
-from cpython.unicode cimport PyUnicode_AsUTF8String, PyUnicode_Decode
+from cpython.unicode cimport (
+ PyUnicode_AsUTF8String,
+ PyUnicode_Decode,
+)
cdef extern from "Python.h":
@@ -26,12 +40,22 @@ cdef extern from "Python.h":
import numpy as np
cimport numpy as cnp
-from numpy cimport float64_t, int64_t, ndarray, uint8_t, uint64_t
+from numpy cimport (
+ float64_t,
+ int64_t,
+ ndarray,
+ uint8_t,
+ uint64_t,
+)
cnp.import_array()
from pandas._libs cimport util
-from pandas._libs.util cimport INT64_MAX, INT64_MIN, UINT64_MAX
+from pandas._libs.util cimport (
+ INT64_MAX,
+ INT64_MIN,
+ UINT64_MAX,
+)
import pandas._libs.lib as lib
@@ -62,7 +86,12 @@ from pandas._libs.khash cimport (
khiter_t,
)
-from pandas.errors import DtypeWarning, EmptyDataError, ParserError, ParserWarning
+from pandas.errors import (
+ DtypeWarning,
+ EmptyDataError,
+ ParserError,
+ ParserWarning,
+)
from pandas.core.dtypes.common import (
is_bool_dtype,
diff --git a/pandas/_libs/properties.pyx b/pandas/_libs/properties.pyx
index 9b936eed785b4..7b786e9c0493d 100644
--- a/pandas/_libs/properties.pyx
+++ b/pandas/_libs/properties.pyx
@@ -1,6 +1,10 @@
from cython import Py_ssize_t
-from cpython.dict cimport PyDict_Contains, PyDict_GetItem, PyDict_SetItem
+from cpython.dict cimport (
+ PyDict_Contains,
+ PyDict_GetItem,
+ PyDict_SetItem,
+)
cdef class CachedProperty:
diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx
index 25b41b020aee6..61568717ace68 100644
--- a/pandas/_libs/reduction.pyx
+++ b/pandas/_libs/reduction.pyx
@@ -1,17 +1,29 @@
from copy import copy
-from libc.stdlib cimport free, malloc
+from libc.stdlib cimport (
+ free,
+ malloc,
+)
import numpy as np
cimport numpy as cnp
-from numpy cimport int64_t, ndarray
+from numpy cimport (
+ int64_t,
+ ndarray,
+)
cnp.import_array()
-from pandas._libs.util cimport is_array, set_array_not_contiguous
+from pandas._libs.util cimport (
+ is_array,
+ set_array_not_contiguous,
+)
-from pandas._libs.lib import is_scalar, maybe_convert_objects
+from pandas._libs.lib import (
+ is_scalar,
+ maybe_convert_objects,
+)
cpdef check_result_array(object obj, Py_ssize_t cnt):
diff --git a/pandas/_libs/testing.pyx b/pandas/_libs/testing.pyx
index 7a2fa471b9ba8..ff15a2c720c2c 100644
--- a/pandas/_libs/testing.pyx
+++ b/pandas/_libs/testing.pyx
@@ -8,10 +8,17 @@ from numpy cimport import_array
import_array()
from pandas._libs.lib import is_complex
-from pandas._libs.util cimport is_array, is_real_number_object
+
+from pandas._libs.util cimport (
+ is_array,
+ is_real_number_object,
+)
from pandas.core.dtypes.common import is_dtype_equal
-from pandas.core.dtypes.missing import array_equivalent, isna
+from pandas.core.dtypes.missing import (
+ array_equivalent,
+ isna,
+)
cdef bint isiterable(obj):
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx
index 9578fed2d1fd9..605e2135edc9f 100644
--- a/pandas/_libs/tslib.pyx
+++ b/pandas/_libs/tslib.pyx
@@ -13,7 +13,11 @@ PyDateTime_IMPORT
cimport numpy as cnp
-from numpy cimport float64_t, int64_t, ndarray
+from numpy cimport (
+ float64_t,
+ int64_t,
+ ndarray,
+)
import numpy as np
@@ -31,7 +35,11 @@ from pandas._libs.tslibs.np_datetime cimport (
pydate_to_dt64,
pydatetime_to_dt64,
)
-from pandas._libs.util cimport is_datetime64_object, is_float_object, is_integer_object
+from pandas._libs.util cimport (
+ is_datetime64_object,
+ is_float_object,
+ is_integer_object,
+)
from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime
from pandas._libs.tslibs.parsing import parse_datetime_string
@@ -53,6 +61,7 @@ from pandas._libs.tslibs.timestamps cimport _Timestamp
from pandas._libs.tslibs.timestamps import Timestamp
# Note: this is the only non-tslibs intra-pandas dependency here
+
from pandas._libs.missing cimport checknull_with_nat_and_na
from pandas._libs.tslibs.tzconversion cimport tz_localize_to_utc_single
diff --git a/pandas/_libs/tslibs/__init__.py b/pandas/_libs/tslibs/__init__.py
index 6135e54a4502e..e38ed9a20e55b 100644
--- a/pandas/_libs/tslibs/__init__.py
+++ b/pandas/_libs/tslibs/__init__.py
@@ -28,7 +28,10 @@
]
from pandas._libs.tslibs import dtypes
-from pandas._libs.tslibs.conversion import OutOfBoundsTimedelta, localize_pydatetime
+from pandas._libs.tslibs.conversion import (
+ OutOfBoundsTimedelta,
+ localize_pydatetime,
+)
from pandas._libs.tslibs.dtypes import Resolution
from pandas._libs.tslibs.nattype import (
NaT,
@@ -38,8 +41,15 @@
nat_strings,
)
from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime
-from pandas._libs.tslibs.offsets import BaseOffset, Tick, to_offset
-from pandas._libs.tslibs.period import IncompatibleFrequency, Period
+from pandas._libs.tslibs.offsets import (
+ BaseOffset,
+ Tick,
+ to_offset,
+)
+from pandas._libs.tslibs.period import (
+ IncompatibleFrequency,
+ Period,
+)
from pandas._libs.tslibs.timedeltas import (
Timedelta,
delta_to_nanoseconds,
diff --git a/pandas/_libs/tslibs/ccalendar.pxd b/pandas/_libs/tslibs/ccalendar.pxd
index 388fd0c62b937..511c9f94a47d8 100644
--- a/pandas/_libs/tslibs/ccalendar.pxd
+++ b/pandas/_libs/tslibs/ccalendar.pxd
@@ -1,5 +1,8 @@
from cython cimport Py_ssize_t
-from numpy cimport int32_t, int64_t
+from numpy cimport (
+ int32_t,
+ int64_t,
+)
ctypedef (int32_t, int32_t, int32_t) iso_calendar_t
diff --git a/pandas/_libs/tslibs/ccalendar.pyx b/pandas/_libs/tslibs/ccalendar.pyx
index d8c83daa661a3..2aa049559d9e9 100644
--- a/pandas/_libs/tslibs/ccalendar.pyx
+++ b/pandas/_libs/tslibs/ccalendar.pyx
@@ -5,7 +5,10 @@ Cython implementations of functions resembling the stdlib calendar module
import cython
-from numpy cimport int32_t, int64_t
+from numpy cimport (
+ int32_t,
+ int64_t,
+)
# ----------------------------------------------------------------------
# Constants
diff --git a/pandas/_libs/tslibs/conversion.pxd b/pandas/_libs/tslibs/conversion.pxd
index c80be79a12d90..1b99e855da40f 100644
--- a/pandas/_libs/tslibs/conversion.pxd
+++ b/pandas/_libs/tslibs/conversion.pxd
@@ -1,5 +1,12 @@
-from cpython.datetime cimport datetime, tzinfo
-from numpy cimport int32_t, int64_t, ndarray
+from cpython.datetime cimport (
+ datetime,
+ tzinfo,
+)
+from numpy cimport (
+ int32_t,
+ int64_t,
+ ndarray,
+)
from pandas._libs.tslibs.np_datetime cimport npy_datetimestruct
diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx
index 0a22bd9b849a7..0646c58fa84b6 100644
--- a/pandas/_libs/tslibs/conversion.pyx
+++ b/pandas/_libs/tslibs/conversion.pyx
@@ -2,7 +2,12 @@ import cython
import numpy as np
cimport numpy as cnp
-from numpy cimport int32_t, int64_t, intp_t, ndarray
+from numpy cimport (
+ int32_t,
+ int64_t,
+ intp_t,
+ ndarray,
+)
cnp.import_array()
diff --git a/pandas/_libs/tslibs/fields.pyx b/pandas/_libs/tslibs/fields.pyx
index 2f25df9144f32..79d6a42075e83 100644
--- a/pandas/_libs/tslibs/fields.pyx
+++ b/pandas/_libs/tslibs/fields.pyx
@@ -9,13 +9,22 @@ from cython import Py_ssize_t
import numpy as np
cimport numpy as cnp
-from numpy cimport int8_t, int32_t, int64_t, ndarray, uint32_t
+from numpy cimport (
+ int8_t,
+ int32_t,
+ int64_t,
+ ndarray,
+ uint32_t,
+)
cnp.import_array()
from pandas._config.localization import set_locale
-from pandas._libs.tslibs.ccalendar import DAYS_FULL, MONTHS_FULL
+from pandas._libs.tslibs.ccalendar import (
+ DAYS_FULL,
+ MONTHS_FULL,
+)
from pandas._libs.tslibs.ccalendar cimport (
dayofweek,
diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx
index d5582d65a0c11..2879528b2c501 100644
--- a/pandas/_libs/tslibs/nattype.pyx
+++ b/pandas/_libs/tslibs/nattype.pyx
@@ -30,7 +30,10 @@ from numpy cimport int64_t
cnp.import_array()
cimport pandas._libs.tslibs.util as util
-from pandas._libs.tslibs.np_datetime cimport get_datetime64_value, get_timedelta64_value
+from pandas._libs.tslibs.np_datetime cimport (
+ get_datetime64_value,
+ get_timedelta64_value,
+)
# ----------------------------------------------------------------------
# Constants
diff --git a/pandas/_libs/tslibs/np_datetime.pxd b/pandas/_libs/tslibs/np_datetime.pxd
index 026fa719d1cc1..c2bbc4fe764fe 100644
--- a/pandas/_libs/tslibs/np_datetime.pxd
+++ b/pandas/_libs/tslibs/np_datetime.pxd
@@ -1,5 +1,11 @@
-from cpython.datetime cimport date, datetime
-from numpy cimport int32_t, int64_t
+from cpython.datetime cimport (
+ date,
+ datetime,
+)
+from numpy cimport (
+ int32_t,
+ int64_t,
+)
cdef extern from "numpy/ndarrayobject.h":
diff --git a/pandas/_libs/tslibs/np_datetime.pyx b/pandas/_libs/tslibs/np_datetime.pyx
index 12aaaf4ce3977..418730277ed6b 100644
--- a/pandas/_libs/tslibs/np_datetime.pyx
+++ b/pandas/_libs/tslibs/np_datetime.pyx
@@ -8,7 +8,14 @@ from cpython.datetime cimport (
PyDateTime_GET_YEAR,
PyDateTime_IMPORT,
)
-from cpython.object cimport Py_EQ, Py_GE, Py_GT, Py_LE, Py_LT, Py_NE
+from cpython.object cimport (
+ Py_EQ,
+ Py_GE,
+ Py_GT,
+ Py_LE,
+ Py_LT,
+ Py_NE,
+)
PyDateTime_IMPORT
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx
index 4dc14397a30f4..2d4704ad3bda6 100644
--- a/pandas/_libs/tslibs/offsets.pyx
+++ b/pandas/_libs/tslibs/offsets.pyx
@@ -24,7 +24,10 @@ from dateutil.relativedelta import relativedelta
import numpy as np
cimport numpy as cnp
-from numpy cimport int64_t, ndarray
+from numpy cimport (
+ int64_t,
+ ndarray,
+)
cnp.import_array()
@@ -57,7 +60,10 @@ from pandas._libs.tslibs.conversion cimport (
convert_datetime_to_tsobject,
localize_pydatetime,
)
-from pandas._libs.tslibs.nattype cimport NPY_NAT, c_NaT as NaT
+from pandas._libs.tslibs.nattype cimport (
+ NPY_NAT,
+ c_NaT as NaT,
+)
from pandas._libs.tslibs.np_datetime cimport (
dt64_to_dtstruct,
dtstruct_to_dt64,
diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx
index 5c3417ee2d93c..50b1804e1c5f9 100644
--- a/pandas/_libs/tslibs/parsing.pyx
+++ b/pandas/_libs/tslibs/parsing.pyx
@@ -9,7 +9,12 @@ from libc.string cimport strchr
import cython
from cython import Py_ssize_t
-from cpython.datetime cimport datetime, datetime_new, import_datetime, tzinfo
+from cpython.datetime cimport (
+ datetime,
+ datetime_new,
+ import_datetime,
+ tzinfo,
+)
from cpython.object cimport PyObject_Str
from cpython.version cimport PY_VERSION_HEX
@@ -31,7 +36,10 @@ cnp.import_array()
# dateutil compat
-from dateutil.parser import DEFAULTPARSER, parse as du_parse
+from dateutil.parser import (
+ DEFAULTPARSER,
+ parse as du_parse,
+)
from dateutil.relativedelta import relativedelta
from dateutil.tz import (
tzlocal as _dateutil_tzlocal,
@@ -43,9 +51,15 @@ from dateutil.tz import (
from pandas._config import get_option
from pandas._libs.tslibs.ccalendar cimport c_MONTH_NUMBERS
-from pandas._libs.tslibs.nattype cimport c_NaT as NaT, c_nat_strings as nat_strings
+from pandas._libs.tslibs.nattype cimport (
+ c_NaT as NaT,
+ c_nat_strings as nat_strings,
+)
from pandas._libs.tslibs.offsets cimport is_offset_object
-from pandas._libs.tslibs.util cimport get_c_string_buf_and_size, is_array
+from pandas._libs.tslibs.util cimport (
+ get_c_string_buf_and_size,
+ is_array,
+)
cdef extern from "../src/headers/portable.h":
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx
index d518729b6ce67..165f51d06af6d 100644
--- a/pandas/_libs/tslibs/period.pyx
+++ b/pandas/_libs/tslibs/period.pyx
@@ -1,16 +1,32 @@
import warnings
cimport numpy as cnp
-from cpython.object cimport Py_EQ, Py_NE, PyObject_RichCompareBool
-from numpy cimport int64_t, ndarray
+from cpython.object cimport (
+ Py_EQ,
+ Py_NE,
+ PyObject_RichCompareBool,
+)
+from numpy cimport (
+ int64_t,
+ ndarray,
+)
import numpy as np
cnp.import_array()
-from libc.stdlib cimport free, malloc
-from libc.string cimport memset, strlen
-from libc.time cimport strftime, tm
+from libc.stdlib cimport (
+ free,
+ malloc,
+)
+from libc.string cimport (
+ memset,
+ strlen,
+)
+from libc.time cimport (
+ strftime,
+ tm,
+)
import cython
@@ -54,7 +70,10 @@ from pandas._libs.tslibs.ccalendar cimport (
get_week_of_year,
is_leapyear,
)
-from pandas._libs.tslibs.timedeltas cimport delta_to_nanoseconds, is_any_td_scalar
+from pandas._libs.tslibs.timedeltas cimport (
+ delta_to_nanoseconds,
+ is_any_td_scalar,
+)
from pandas._libs.tslibs.conversion import ensure_datetime64ns
diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx
index bc4632ad028ab..ffa29b44a366a 100644
--- a/pandas/_libs/tslibs/strptime.pyx
+++ b/pandas/_libs/tslibs/strptime.pyx
@@ -5,14 +5,20 @@ import locale
import re
import time
-from cpython.datetime cimport date, tzinfo
+from cpython.datetime cimport (
+ date,
+ tzinfo,
+)
from _thread import allocate_lock as _thread_allocate_lock
import numpy as np
import pytz
-from numpy cimport int64_t, ndarray
+from numpy cimport (
+ int64_t,
+ ndarray,
+)
from pandas._libs.tslibs.nattype cimport (
NPY_NAT,
diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx
index 871819f82a672..9ebabd704475b 100644
--- a/pandas/_libs/tslibs/timedeltas.pyx
+++ b/pandas/_libs/tslibs/timedeltas.pyx
@@ -3,12 +3,19 @@ import warnings
import cython
-from cpython.object cimport Py_EQ, Py_NE, PyObject_RichCompare
+from cpython.object cimport (
+ Py_EQ,
+ Py_NE,
+ PyObject_RichCompare,
+)
import numpy as np
cimport numpy as cnp
-from numpy cimport int64_t, ndarray
+from numpy cimport (
+ int64_t,
+ ndarray,
+)
cnp.import_array()
@@ -24,7 +31,10 @@ PyDateTime_IMPORT
cimport pandas._libs.tslibs.util as util
from pandas._libs.tslibs.base cimport ABCTimestamp
-from pandas._libs.tslibs.conversion cimport cast_from_unit, precision_from_unit
+from pandas._libs.tslibs.conversion cimport (
+ cast_from_unit,
+ precision_from_unit,
+)
from pandas._libs.tslibs.nattype cimport (
NPY_NAT,
c_NaT as NaT,
@@ -47,7 +57,11 @@ from pandas._libs.tslibs.util cimport (
is_integer_object,
is_timedelta64_object,
)
-from pandas._libs.tslibs.fields import RoundTo, round_nsint64
+
+from pandas._libs.tslibs.fields import (
+ RoundTo,
+ round_nsint64,
+)
# ----------------------------------------------------------------------
# Constants
diff --git a/pandas/_libs/tslibs/timestamps.pxd b/pandas/_libs/tslibs/timestamps.pxd
index 45aae3581fe79..eadd7c7022acb 100644
--- a/pandas/_libs/tslibs/timestamps.pxd
+++ b/pandas/_libs/tslibs/timestamps.pxd
@@ -1,4 +1,7 @@
-from cpython.datetime cimport datetime, tzinfo
+from cpython.datetime cimport (
+ datetime,
+ tzinfo,
+)
from numpy cimport int64_t
from pandas._libs.tslibs.base cimport ABCTimestamp
diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx
index 5f6b614ac3d81..60ffa3dd46989 100644
--- a/pandas/_libs/tslibs/timestamps.pyx
+++ b/pandas/_libs/tslibs/timestamps.pyx
@@ -13,7 +13,12 @@ cimport cython
import numpy as np
cimport numpy as cnp
-from numpy cimport int8_t, int64_t, ndarray, uint8_t
+from numpy cimport (
+ int8_t,
+ int64_t,
+ ndarray,
+ uint8_t,
+)
cnp.import_array()
@@ -63,7 +68,10 @@ from pandas._libs.tslibs.fields import (
round_nsint64,
)
-from pandas._libs.tslibs.nattype cimport NPY_NAT, c_NaT as NaT
+from pandas._libs.tslibs.nattype cimport (
+ NPY_NAT,
+ c_NaT as NaT,
+)
from pandas._libs.tslibs.np_datetime cimport (
check_dts_bounds,
cmp_scalar,
@@ -74,8 +82,14 @@ from pandas._libs.tslibs.np_datetime cimport (
from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime
-from pandas._libs.tslibs.offsets cimport is_offset_object, to_offset
-from pandas._libs.tslibs.timedeltas cimport delta_to_nanoseconds, is_any_td_scalar
+from pandas._libs.tslibs.offsets cimport (
+ is_offset_object,
+ to_offset,
+)
+from pandas._libs.tslibs.timedeltas cimport (
+ delta_to_nanoseconds,
+ is_any_td_scalar,
+)
from pandas._libs.tslibs.timedeltas import Timedelta
diff --git a/pandas/_libs/tslibs/timezones.pxd b/pandas/_libs/tslibs/timezones.pxd
index 753c881ed505c..13f196a567952 100644
--- a/pandas/_libs/tslibs/timezones.pxd
+++ b/pandas/_libs/tslibs/timezones.pxd
@@ -1,4 +1,8 @@
-from cpython.datetime cimport datetime, timedelta, tzinfo
+from cpython.datetime cimport (
+ datetime,
+ timedelta,
+ tzinfo,
+)
cdef tzinfo utc_pytz
diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx
index 73d06d4641368..92065e1c3d4c5 100644
--- a/pandas/_libs/tslibs/timezones.pyx
+++ b/pandas/_libs/tslibs/timezones.pyx
@@ -1,6 +1,13 @@
-from datetime import timedelta, timezone
+from datetime import (
+ timedelta,
+ timezone,
+)
-from cpython.datetime cimport datetime, timedelta, tzinfo
+from cpython.datetime cimport (
+ datetime,
+ timedelta,
+ tzinfo,
+)
# dateutil compat
@@ -24,7 +31,10 @@ from numpy cimport int64_t
cnp.import_array()
# ----------------------------------------------------------------------
-from pandas._libs.tslibs.util cimport get_nat, is_integer_object
+from pandas._libs.tslibs.util cimport (
+ get_nat,
+ is_integer_object,
+)
cdef int64_t NPY_NAT = get_nat()
diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx
index 1049682af08e8..8e82d8a180aa6 100644
--- a/pandas/_libs/tslibs/tzconversion.pyx
+++ b/pandas/_libs/tslibs/tzconversion.pyx
@@ -19,13 +19,24 @@ import numpy as np
import pytz
cimport numpy as cnp
-from numpy cimport int64_t, intp_t, ndarray, uint8_t
+from numpy cimport (
+ int64_t,
+ intp_t,
+ ndarray,
+ uint8_t,
+)
cnp.import_array()
-from pandas._libs.tslibs.ccalendar cimport DAY_NANOS, HOUR_NANOS
+from pandas._libs.tslibs.ccalendar cimport (
+ DAY_NANOS,
+ HOUR_NANOS,
+)
from pandas._libs.tslibs.nattype cimport NPY_NAT
-from pandas._libs.tslibs.np_datetime cimport dt64_to_dtstruct, npy_datetimestruct
+from pandas._libs.tslibs.np_datetime cimport (
+ dt64_to_dtstruct,
+ npy_datetimestruct,
+)
from pandas._libs.tslibs.timezones cimport (
get_dst_info,
get_utcoffset,
diff --git a/pandas/_libs/tslibs/util.pxd b/pandas/_libs/tslibs/util.pxd
index 16d801f69df05..150516aadffc6 100644
--- a/pandas/_libs/tslibs/util.pxd
+++ b/pandas/_libs/tslibs/util.pxd
@@ -27,7 +27,10 @@ cdef extern from "Python.h":
const char* PyUnicode_AsUTF8AndSize(object obj,
Py_ssize_t* length) except NULL
-from numpy cimport float64_t, int64_t
+from numpy cimport (
+ float64_t,
+ int64_t,
+)
cdef extern from "numpy/arrayobject.h":
diff --git a/pandas/_libs/tslibs/vectorized.pyx b/pandas/_libs/tslibs/vectorized.pyx
index c3c78ca54885a..30d9f5e64b282 100644
--- a/pandas/_libs/tslibs/vectorized.pyx
+++ b/pandas/_libs/tslibs/vectorized.pyx
@@ -1,21 +1,40 @@
import cython
-from cpython.datetime cimport date, datetime, time, tzinfo
+from cpython.datetime cimport (
+ date,
+ datetime,
+ time,
+ tzinfo,
+)
import numpy as np
-from numpy cimport int64_t, intp_t, ndarray
+from numpy cimport (
+ int64_t,
+ intp_t,
+ ndarray,
+)
from .conversion cimport normalize_i8_stamp
from .dtypes import Resolution
-from .nattype cimport NPY_NAT, c_NaT as NaT
-from .np_datetime cimport dt64_to_dtstruct, npy_datetimestruct
+from .nattype cimport (
+ NPY_NAT,
+ c_NaT as NaT,
+)
+from .np_datetime cimport (
+ dt64_to_dtstruct,
+ npy_datetimestruct,
+)
from .offsets cimport to_offset
from .period cimport get_period_ordinal
from .timestamps cimport create_timestamp_from_ts
-from .timezones cimport get_dst_info, is_tzlocal, is_utc
+from .timezones cimport (
+ get_dst_info,
+ is_tzlocal,
+ is_utc,
+)
from .tzconversion cimport tz_convert_utc_to_tzlocal
# -------------------------------------------------------------------------
diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx
index 5e02e6119815c..5a95b0ec4e08a 100644
--- a/pandas/_libs/window/aggregations.pyx
+++ b/pandas/_libs/window/aggregations.pyx
@@ -8,7 +8,12 @@ from libcpp.deque cimport deque
import numpy as np
cimport numpy as cnp
-from numpy cimport float32_t, float64_t, int64_t, ndarray
+from numpy cimport (
+ float32_t,
+ float64_t,
+ int64_t,
+ ndarray,
+)
cnp.import_array()
diff --git a/pandas/_libs/window/indexers.pyx b/pandas/_libs/window/indexers.pyx
index 6a49a5bb34855..b8b9a8553161f 100644
--- a/pandas/_libs/window/indexers.pyx
+++ b/pandas/_libs/window/indexers.pyx
@@ -2,7 +2,10 @@
import numpy as np
-from numpy cimport int64_t, ndarray
+from numpy cimport (
+ int64_t,
+ ndarray,
+)
# Cython routines for window indexers
diff --git a/pandas/_libs/writers.pyx b/pandas/_libs/writers.pyx
index 06f180eef0c65..6577f3604d14b 100644
--- a/pandas/_libs/writers.pyx
+++ b/pandas/_libs/writers.pyx
@@ -1,8 +1,14 @@
import cython
import numpy as np
-from cpython cimport PyBytes_GET_SIZE, PyUnicode_GET_LENGTH
-from numpy cimport ndarray, uint8_t
+from cpython cimport (
+ PyBytes_GET_SIZE,
+ PyUnicode_GET_LENGTH,
+)
+from numpy cimport (
+ ndarray,
+ uint8_t,
+)
ctypedef fused pandas_string:
str
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py
index 97a152d9ade1e..bbf1a7a9929e6 100644
--- a/pandas/_testing/__init__.py
+++ b/pandas/_testing/__init__.py
@@ -99,10 +99,18 @@
use_numexpr,
with_csv_dialect,
)
-from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray, period_array
+from pandas.core.arrays import (
+ DatetimeArray,
+ PeriodArray,
+ TimedeltaArray,
+ period_array,
+)
if TYPE_CHECKING:
- from pandas import PeriodIndex, TimedeltaIndex
+ from pandas import (
+ PeriodIndex,
+ TimedeltaIndex,
+ )
_N = 30
_K = 4
diff --git a/pandas/_testing/_io.py b/pandas/_testing/_io.py
index 8d387ff5674f7..e327f48f9a888 100644
--- a/pandas/_testing/_io.py
+++ b/pandas/_testing/_io.py
@@ -1,11 +1,22 @@
import bz2
from functools import wraps
import gzip
-from typing import Any, Callable, Optional, Tuple
+from typing import (
+ Any,
+ Callable,
+ Optional,
+ Tuple,
+)
import zipfile
-from pandas._typing import FilePathOrBuffer, FrameOrSeries
-from pandas.compat import get_lzma_file, import_lzma
+from pandas._typing import (
+ FilePathOrBuffer,
+ FrameOrSeries,
+)
+from pandas.compat import (
+ get_lzma_file,
+ import_lzma,
+)
import pandas as pd
from pandas._testing._random import rands
@@ -394,7 +405,10 @@ def write_to_compressed(compression, path, data, dest="test"):
def close(fignum=None):
- from matplotlib.pyplot import close as _close, get_fignums
+ from matplotlib.pyplot import (
+ close as _close,
+ get_fignums,
+ )
if fignum is None:
for fignum in get_fignums():
diff --git a/pandas/_testing/_warnings.py b/pandas/_testing/_warnings.py
index 6429f74637f01..ee32abe19278e 100644
--- a/pandas/_testing/_warnings.py
+++ b/pandas/_testing/_warnings.py
@@ -1,6 +1,12 @@
from contextlib import contextmanager
import re
-from typing import Optional, Sequence, Type, Union, cast
+from typing import (
+ Optional,
+ Sequence,
+ Type,
+ Union,
+ cast,
+)
import warnings
@@ -163,7 +169,10 @@ def _is_unexpected_warning(
def _assert_raised_with_correct_stacklevel(
actual_warning: warnings.WarningMessage,
) -> None:
- from inspect import getframeinfo, stack
+ from inspect import (
+ getframeinfo,
+ stack,
+ )
caller = getframeinfo(stack()[4][0])
msg = (
diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py
index 6b67459c47c38..829472f24852a 100644
--- a/pandas/_testing/asserters.py
+++ b/pandas/_testing/asserters.py
@@ -1,4 +1,7 @@
-from typing import Union, cast
+from typing import (
+ Union,
+ cast,
+)
import warnings
import numpy as np
@@ -29,7 +32,10 @@
Series,
TimedeltaIndex,
)
-from pandas.core.algorithms import safe_sort, take_nd
+from pandas.core.algorithms import (
+ safe_sort,
+ take_nd,
+)
from pandas.core.arrays import (
DatetimeArray,
ExtensionArray,
diff --git a/pandas/_testing/contexts.py b/pandas/_testing/contexts.py
index 71530b9537fc8..a14e87c04c913 100644
--- a/pandas/_testing/contexts.py
+++ b/pandas/_testing/contexts.py
@@ -5,7 +5,11 @@
from shutil import rmtree
import string
import tempfile
-from typing import IO, Any, Union
+from typing import (
+ IO,
+ Any,
+ Union,
+)
import numpy as np
diff --git a/pandas/_typing.py b/pandas/_typing.py
index f03b3c9eaf65a..074b57054c0d1 100644
--- a/pandas/_typing.py
+++ b/pandas/_typing.py
@@ -1,5 +1,14 @@
-from datetime import datetime, timedelta, tzinfo
-from io import BufferedIOBase, RawIOBase, TextIOBase, TextIOWrapper
+from datetime import (
+ datetime,
+ timedelta,
+ tzinfo,
+)
+from io import (
+ BufferedIOBase,
+ RawIOBase,
+ TextIOBase,
+ TextIOWrapper,
+)
from mmap import mmap
from os import PathLike
from typing import (
@@ -29,7 +38,11 @@
if TYPE_CHECKING:
from typing import final
- from pandas._libs import Period, Timedelta, Timestamp
+ from pandas._libs import (
+ Period,
+ Timedelta,
+ Timestamp,
+ )
from pandas.core.dtypes.dtypes import ExtensionDtype
@@ -37,9 +50,15 @@
from pandas.core.arrays.base import ExtensionArray # noqa: F401
from pandas.core.frame import DataFrame
from pandas.core.generic import NDFrame # noqa: F401
- from pandas.core.groupby.generic import DataFrameGroupBy, SeriesGroupBy
+ from pandas.core.groupby.generic import (
+ DataFrameGroupBy,
+ SeriesGroupBy,
+ )
from pandas.core.indexes.base import Index
- from pandas.core.internals import ArrayManager, BlockManager
+ from pandas.core.internals import (
+ ArrayManager,
+ BlockManager,
+ )
from pandas.core.resample import Resampler
from pandas.core.series import Series
from pandas.core.window.rolling import BaseWindow
diff --git a/pandas/api/__init__.py b/pandas/api/__init__.py
index bebbb38b4aefa..c22f37f2ef292 100644
--- a/pandas/api/__init__.py
+++ b/pandas/api/__init__.py
@@ -1,2 +1,6 @@
""" public toolkit API """
-from pandas.api import extensions, indexers, types # noqa
+from pandas.api import ( # noqa
+ extensions,
+ indexers,
+ types,
+)
diff --git a/pandas/api/extensions/__init__.py b/pandas/api/extensions/__init__.py
index 401e7081d2422..ea5f1ba926899 100644
--- a/pandas/api/extensions/__init__.py
+++ b/pandas/api/extensions/__init__.py
@@ -4,7 +4,10 @@
from pandas._libs.lib import no_default
-from pandas.core.dtypes.base import ExtensionDtype, register_extension_dtype
+from pandas.core.dtypes.base import (
+ ExtensionDtype,
+ register_extension_dtype,
+)
from pandas.core.accessor import (
register_dataframe_accessor,
@@ -12,7 +15,10 @@
register_series_accessor,
)
from pandas.core.algorithms import take
-from pandas.core.arrays import ExtensionArray, ExtensionScalarOpsMixin
+from pandas.core.arrays import (
+ ExtensionArray,
+ ExtensionScalarOpsMixin,
+)
__all__ = [
"no_default",
diff --git a/pandas/compat/chainmap.py b/pandas/compat/chainmap.py
index a84dbb4a661e4..035963e8255ea 100644
--- a/pandas/compat/chainmap.py
+++ b/pandas/compat/chainmap.py
@@ -1,4 +1,9 @@
-from typing import ChainMap, MutableMapping, TypeVar, cast
+from typing import (
+ ChainMap,
+ MutableMapping,
+ TypeVar,
+ cast,
+)
_KT = TypeVar("_KT")
_VT = TypeVar("_VT")
diff --git a/pandas/compat/numpy/function.py b/pandas/compat/numpy/function.py
index c47c31fabeb70..8934a02a8f5bc 100644
--- a/pandas/compat/numpy/function.py
+++ b/pandas/compat/numpy/function.py
@@ -16,11 +16,22 @@
easier to adjust to future upstream changes in the analogous numpy signatures.
"""
from distutils.version import LooseVersion
-from typing import Any, Dict, Optional, Union
+from typing import (
+ Any,
+ Dict,
+ Optional,
+ Union,
+)
-from numpy import __version__, ndarray
+from numpy import (
+ __version__,
+ ndarray,
+)
-from pandas._libs.lib import is_bool, is_integer
+from pandas._libs.lib import (
+ is_bool,
+ is_integer,
+)
from pandas.errors import UnsupportedFunctionCall
from pandas.util._validators import (
validate_args,
diff --git a/pandas/compat/pickle_compat.py b/pandas/compat/pickle_compat.py
index e6940d78dbaa2..9d48035213126 100644
--- a/pandas/compat/pickle_compat.py
+++ b/pandas/compat/pickle_compat.py
@@ -7,7 +7,10 @@
import copy
import io
import pickle as pkl
-from typing import TYPE_CHECKING, Optional
+from typing import (
+ TYPE_CHECKING,
+ Optional,
+)
import warnings
from pandas._libs.tslibs import BaseOffset
@@ -15,7 +18,10 @@
from pandas import Index
if TYPE_CHECKING:
- from pandas import DataFrame, Series
+ from pandas import (
+ DataFrame,
+ Series,
+ )
def load_reduce(self):
diff --git a/pandas/conftest.py b/pandas/conftest.py
index 79204c8896854..ce572e42abec6 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -19,27 +19,52 @@
"""
from collections import abc
-from datetime import date, datetime, time, timedelta, timezone
+from datetime import (
+ date,
+ datetime,
+ time,
+ timedelta,
+ timezone,
+)
from decimal import Decimal
import operator
import os
-from dateutil.tz import tzlocal, tzutc
+from dateutil.tz import (
+ tzlocal,
+ tzutc,
+)
import hypothesis
from hypothesis import strategies as st
import numpy as np
import pytest
-from pytz import FixedOffset, utc
+from pytz import (
+ FixedOffset,
+ utc,
+)
import pandas.util._test_decorators as td
-from pandas.core.dtypes.dtypes import DatetimeTZDtype, IntervalDtype
+from pandas.core.dtypes.dtypes import (
+ DatetimeTZDtype,
+ IntervalDtype,
+)
import pandas as pd
-from pandas import DataFrame, Interval, Period, Series, Timedelta, Timestamp
+from pandas import (
+ DataFrame,
+ Interval,
+ Period,
+ Series,
+ Timedelta,
+ Timestamp,
+)
import pandas._testing as tm
from pandas.core import ops
-from pandas.core.indexes.api import Index, MultiIndex
+from pandas.core.indexes.api import (
+ Index,
+ MultiIndex,
+)
# ----------------------------------------------------------------
diff --git a/pandas/core/accessor.py b/pandas/core/accessor.py
index 15c2a4a6c5c04..2b6dd379ea47c 100644
--- a/pandas/core/accessor.py
+++ b/pandas/core/accessor.py
@@ -4,7 +4,11 @@
that can be mixed into or pinned onto other pandas classes.
"""
-from typing import FrozenSet, List, Set
+from typing import (
+ FrozenSet,
+ List,
+ Set,
+)
import warnings
from pandas.util._decorators import doc
diff --git a/pandas/core/aggregation.py b/pandas/core/aggregation.py
index 4dbce8f75898f..744a1ffa5fea1 100644
--- a/pandas/core/aggregation.py
+++ b/pandas/core/aggregation.py
@@ -32,8 +32,14 @@
FrameOrSeriesUnion,
)
-from pandas.core.dtypes.common import is_dict_like, is_list_like
-from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
+from pandas.core.dtypes.common import (
+ is_dict_like,
+ is_list_like,
+)
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCSeries,
+)
from pandas.core.algorithms import safe_sort
from pandas.core.base import SpecificationError
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 337c1910102a7..40533cdd554b3 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -6,13 +6,34 @@
import operator
from textwrap import dedent
-from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union, cast
-from warnings import catch_warnings, simplefilter, warn
+from typing import (
+ TYPE_CHECKING,
+ Dict,
+ Optional,
+ Tuple,
+ Union,
+ cast,
+)
+from warnings import (
+ catch_warnings,
+ simplefilter,
+ warn,
+)
import numpy as np
-from pandas._libs import algos, hashtable as htable, iNaT, lib
-from pandas._typing import AnyArrayLike, ArrayLike, DtypeObj, FrameOrSeriesUnion
+from pandas._libs import (
+ algos,
+ hashtable as htable,
+ iNaT,
+ lib,
+)
+from pandas._typing import (
+ AnyArrayLike,
+ ArrayLike,
+ DtypeObj,
+ FrameOrSeriesUnion,
+)
from pandas.util._decorators import doc
from pandas.core.dtypes.cast import (
@@ -57,7 +78,10 @@
ABCSeries,
ABCTimedeltaArray,
)
-from pandas.core.dtypes.missing import isna, na_value_for_dtype
+from pandas.core.dtypes.missing import (
+ isna,
+ na_value_for_dtype,
+)
from pandas.core.construction import (
array,
@@ -67,8 +91,16 @@
from pandas.core.indexers import validate_indices
if TYPE_CHECKING:
- from pandas import Categorical, DataFrame, Index, Series
- from pandas.core.arrays import DatetimeArray, TimedeltaArray
+ from pandas import (
+ Categorical,
+ DataFrame,
+ Index,
+ Series,
+ )
+ from pandas.core.arrays import (
+ DatetimeArray,
+ TimedeltaArray,
+ )
_shared_docs: Dict[str, str] = {}
diff --git a/pandas/core/api.py b/pandas/core/api.py
index 67e86c2076329..2677530455b07 100644
--- a/pandas/core/api.py
+++ b/pandas/core/api.py
@@ -1,6 +1,11 @@
# flake8: noqa
-from pandas._libs import NaT, Period, Timedelta, Timestamp
+from pandas._libs import (
+ NaT,
+ Period,
+ Timedelta,
+ Timestamp,
+)
from pandas._libs.missing import NA
from pandas.core.dtypes.dtypes import (
@@ -9,12 +14,24 @@
IntervalDtype,
PeriodDtype,
)
-from pandas.core.dtypes.missing import isna, isnull, notna, notnull
+from pandas.core.dtypes.missing import (
+ isna,
+ isnull,
+ notna,
+ notnull,
+)
-from pandas.core.algorithms import factorize, unique, value_counts
+from pandas.core.algorithms import (
+ factorize,
+ unique,
+ value_counts,
+)
from pandas.core.arrays import Categorical
from pandas.core.arrays.boolean import BooleanDtype
-from pandas.core.arrays.floating import Float32Dtype, Float64Dtype
+from pandas.core.arrays.floating import (
+ Float32Dtype,
+ Float64Dtype,
+)
from pandas.core.arrays.integer import (
Int8Dtype,
Int16Dtype,
@@ -28,7 +45,10 @@
from pandas.core.arrays.string_ import StringDtype
from pandas.core.construction import array
from pandas.core.flags import Flags
-from pandas.core.groupby import Grouper, NamedAgg
+from pandas.core.groupby import (
+ Grouper,
+ NamedAgg,
+)
from pandas.core.indexes.api import (
CategoricalIndex,
DatetimeIndex,
@@ -42,8 +62,14 @@
TimedeltaIndex,
UInt64Index,
)
-from pandas.core.indexes.datetimes import bdate_range, date_range
-from pandas.core.indexes.interval import Interval, interval_range
+from pandas.core.indexes.datetimes import (
+ bdate_range,
+ date_range,
+)
+from pandas.core.indexes.interval import (
+ Interval,
+ interval_range,
+)
from pandas.core.indexes.period import period_range
from pandas.core.indexes.timedeltas import timedelta_range
from pandas.core.indexing import IndexSlice
diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index 6e48d4b699977..b41c432dff172 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -37,10 +37,17 @@
is_list_like,
is_sequence,
)
-from pandas.core.dtypes.generic import ABCDataFrame, ABCNDFrame, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCNDFrame,
+ ABCSeries,
+)
from pandas.core.algorithms import safe_sort
-from pandas.core.base import DataError, SpecificationError
+from pandas.core.base import (
+ DataError,
+ SpecificationError,
+)
import pandas.core.common as com
from pandas.core.construction import (
array as pd_array,
@@ -48,8 +55,15 @@
)
if TYPE_CHECKING:
- from pandas import DataFrame, Index, Series
- from pandas.core.groupby import DataFrameGroupBy, SeriesGroupBy
+ from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ )
+ from pandas.core.groupby import (
+ DataFrameGroupBy,
+ SeriesGroupBy,
+ )
from pandas.core.resample import Resampler
from pandas.core.window.rolling import BaseWindow
diff --git a/pandas/core/array_algos/putmask.py b/pandas/core/array_algos/putmask.py
index 917aace233ee5..cfa1f59f3d4ca 100644
--- a/pandas/core/array_algos/putmask.py
+++ b/pandas/core/array_algos/putmask.py
@@ -1,7 +1,10 @@
"""
EA-compatible analogue to to np.putmask
"""
-from typing import Any, Tuple
+from typing import (
+ Any,
+ Tuple,
+)
import warnings
import numpy as np
@@ -14,7 +17,11 @@
find_common_type,
infer_dtype_from,
)
-from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype, is_list_like
+from pandas.core.dtypes.common import (
+ is_float_dtype,
+ is_integer_dtype,
+ is_list_like,
+)
from pandas.core.dtypes.missing import isna_compat
from pandas.core.arrays import ExtensionArray
diff --git a/pandas/core/array_algos/replace.py b/pandas/core/array_algos/replace.py
index d0565dfff0eb1..201b9fdcc51cc 100644
--- a/pandas/core/array_algos/replace.py
+++ b/pandas/core/array_algos/replace.py
@@ -3,11 +3,19 @@
"""
import operator
import re
-from typing import Any, Optional, Pattern, Union
+from typing import (
+ Any,
+ Optional,
+ Pattern,
+ Union,
+)
import numpy as np
-from pandas._typing import ArrayLike, Scalar
+from pandas._typing import (
+ ArrayLike,
+ Scalar,
+)
from pandas.core.dtypes.common import (
is_datetimelike_v_numeric,
diff --git a/pandas/core/arraylike.py b/pandas/core/arraylike.py
index e17ba45f30d6c..3f45f503d0f62 100644
--- a/pandas/core/arraylike.py
+++ b/pandas/core/arraylike.py
@@ -5,7 +5,10 @@
ExtensionArray
"""
import operator
-from typing import Any, Callable
+from typing import (
+ Any,
+ Callable,
+)
import warnings
import numpy as np
@@ -13,7 +16,10 @@
from pandas._libs import lib
from pandas.core.construction import extract_array
-from pandas.core.ops import maybe_dispatch_ufunc_to_dunder_op, roperator
+from pandas.core.ops import (
+ maybe_dispatch_ufunc_to_dunder_op,
+ roperator,
+)
from pandas.core.ops.common import unpack_zerodim_and_defer
diff --git a/pandas/core/arrays/__init__.py b/pandas/core/arrays/__init__.py
index b6d98eb17eb6c..22f15ca9650db 100644
--- a/pandas/core/arrays/__init__.py
+++ b/pandas/core/arrays/__init__.py
@@ -11,7 +11,10 @@
from pandas.core.arrays.interval import IntervalArray
from pandas.core.arrays.masked import BaseMaskedArray
from pandas.core.arrays.numpy_ import PandasArray
-from pandas.core.arrays.period import PeriodArray, period_array
+from pandas.core.arrays.period import (
+ PeriodArray,
+ period_array,
+)
from pandas.core.arrays.sparse import SparseArray
from pandas.core.arrays.string_ import StringArray
from pandas.core.arrays.timedeltas import TimedeltaArray
diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py
index eb7c9e69d962b..825757ddffee4 100644
--- a/pandas/core/arrays/_mixins.py
+++ b/pandas/core/arrays/_mixins.py
@@ -1,7 +1,14 @@
from __future__ import annotations
from functools import wraps
-from typing import Any, Optional, Sequence, Type, TypeVar, Union
+from typing import (
+ Any,
+ Optional,
+ Sequence,
+ Type,
+ TypeVar,
+ Union,
+)
import numpy as np
@@ -9,7 +16,10 @@
from pandas._typing import Shape
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
-from pandas.util._decorators import cache_readonly, doc
+from pandas.util._decorators import (
+ cache_readonly,
+ doc,
+)
from pandas.util._validators import validate_fillna_kwargs
from pandas.core.dtypes.common import is_dtype_equal
@@ -17,7 +27,11 @@
from pandas.core.dtypes.missing import array_equivalent
from pandas.core import missing
-from pandas.core.algorithms import take, unique, value_counts
+from pandas.core.algorithms import (
+ take,
+ unique,
+ value_counts,
+)
from pandas.core.array_algos.transforms import shift
from pandas.core.arrays.base import ExtensionArray
from pandas.core.construction import extract_array
@@ -389,7 +403,10 @@ def value_counts(self, dropna: bool = True):
if self.ndim != 1:
raise NotImplementedError
- from pandas import Index, Series
+ from pandas import (
+ Index,
+ Series,
+ )
if dropna:
values = self[~self.isna()]._ndarray
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index a62a5ec4ec7f7..edc8fa14ca142 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -25,12 +25,22 @@
import numpy as np
from pandas._libs import lib
-from pandas._typing import ArrayLike, Dtype, Shape
+from pandas._typing import (
+ ArrayLike,
+ Dtype,
+ Shape,
+)
from pandas.compat import set_function_name
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
-from pandas.util._decorators import Appender, Substitution
-from pandas.util._validators import validate_bool_kwarg, validate_fillna_kwargs
+from pandas.util._decorators import (
+ Appender,
+ Substitution,
+)
+from pandas.util._validators import (
+ validate_bool_kwarg,
+ validate_fillna_kwargs,
+)
from pandas.core.dtypes.cast import maybe_cast_to_extension_array
from pandas.core.dtypes.common import (
@@ -41,13 +51,24 @@
pandas_dtype,
)
from pandas.core.dtypes.dtypes import ExtensionDtype
-from pandas.core.dtypes.generic import ABCDataFrame, ABCIndex, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCIndex,
+ ABCSeries,
+)
from pandas.core.dtypes.missing import isna
from pandas.core import ops
-from pandas.core.algorithms import factorize_array, isin, unique
+from pandas.core.algorithms import (
+ factorize_array,
+ isin,
+ unique,
+)
from pandas.core.missing import get_fill_func
-from pandas.core.sorting import nargminmax, nargsort
+from pandas.core.sorting import (
+ nargminmax,
+ nargsort,
+)
_extension_array_shared_docs: Dict[str, str] = {}
diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py
index 86eafb34e847f..260cd08707473 100644
--- a/pandas/core/arrays/boolean.py
+++ b/pandas/core/arrays/boolean.py
@@ -1,13 +1,26 @@
from __future__ import annotations
import numbers
-from typing import TYPE_CHECKING, List, Optional, Tuple, Type, Union
+from typing import (
+ TYPE_CHECKING,
+ List,
+ Optional,
+ Tuple,
+ Type,
+ Union,
+)
import warnings
import numpy as np
-from pandas._libs import lib, missing as libmissing
-from pandas._typing import ArrayLike, Dtype
+from pandas._libs import (
+ lib,
+ missing as libmissing,
+)
+from pandas._typing import (
+ ArrayLike,
+ Dtype,
+)
from pandas.compat.numpy import function as nv
from pandas.core.dtypes.common import (
@@ -19,11 +32,17 @@
is_numeric_dtype,
pandas_dtype,
)
-from pandas.core.dtypes.dtypes import ExtensionDtype, register_extension_dtype
+from pandas.core.dtypes.dtypes import (
+ ExtensionDtype,
+ register_extension_dtype,
+)
from pandas.core.dtypes.missing import isna
from pandas.core import ops
-from pandas.core.arrays.masked import BaseMaskedArray, BaseMaskedDtype
+from pandas.core.arrays.masked import (
+ BaseMaskedArray,
+ BaseMaskedDtype,
+)
if TYPE_CHECKING:
import pyarrow
@@ -596,7 +615,10 @@ def _logical_method(self, other, op):
return BooleanArray(result, mask)
def _cmp_method(self, other, op):
- from pandas.arrays import FloatingArray, IntegerArray
+ from pandas.arrays import (
+ FloatingArray,
+ IntegerArray,
+ )
if isinstance(other, (IntegerArray, FloatingArray)):
return NotImplemented
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 0d1465da7297e..916d4f9f2fd28 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -22,12 +22,28 @@
from pandas._config import get_option
-from pandas._libs import NaT, algos as libalgos, hashtable as htable
+from pandas._libs import (
+ NaT,
+ algos as libalgos,
+ hashtable as htable,
+)
from pandas._libs.lib import no_default
-from pandas._typing import ArrayLike, Dtype, NpDtype, Ordered, Scalar
+from pandas._typing import (
+ ArrayLike,
+ Dtype,
+ NpDtype,
+ Ordered,
+ Scalar,
+)
from pandas.compat.numpy import function as nv
-from pandas.util._decorators import cache_readonly, deprecate_kwarg
-from pandas.util._validators import validate_bool_kwarg, validate_fillna_kwargs
+from pandas.util._decorators import (
+ cache_readonly,
+ deprecate_kwarg,
+)
+from pandas.util._validators import (
+ validate_bool_kwarg,
+ validate_fillna_kwargs,
+)
from pandas.core.dtypes.cast import (
coerce_indexer_dtype,
@@ -53,17 +69,40 @@
pandas_dtype,
)
from pandas.core.dtypes.dtypes import CategoricalDtype
-from pandas.core.dtypes.generic import ABCIndex, ABCSeries
-from pandas.core.dtypes.missing import is_valid_na_for_dtype, isna, notna
+from pandas.core.dtypes.generic import (
+ ABCIndex,
+ ABCSeries,
+)
+from pandas.core.dtypes.missing import (
+ is_valid_na_for_dtype,
+ isna,
+ notna,
+)
from pandas.core import ops
-from pandas.core.accessor import PandasDelegate, delegate_names
+from pandas.core.accessor import (
+ PandasDelegate,
+ delegate_names,
+)
import pandas.core.algorithms as algorithms
-from pandas.core.algorithms import factorize, get_data_algo, take_nd, unique1d
+from pandas.core.algorithms import (
+ factorize,
+ get_data_algo,
+ take_nd,
+ unique1d,
+)
from pandas.core.arrays._mixins import NDArrayBackedExtensionArray
-from pandas.core.base import ExtensionArray, NoNewAttributesMixin, PandasObject
+from pandas.core.base import (
+ ExtensionArray,
+ NoNewAttributesMixin,
+ PandasObject,
+)
import pandas.core.common as com
-from pandas.core.construction import array, extract_array, sanitize_array
+from pandas.core.construction import (
+ array,
+ extract_array,
+ sanitize_array,
+)
from pandas.core.indexers import deprecate_ndim_indexing
from pandas.core.missing import interpolate_2d
from pandas.core.ops.common import unpack_zerodim_and_defer
@@ -522,7 +561,12 @@ def _from_inferred_categories(
-------
Categorical
"""
- from pandas import Index, to_datetime, to_numeric, to_timedelta
+ from pandas import (
+ Index,
+ to_datetime,
+ to_numeric,
+ to_timedelta,
+ )
cats = Index(inferred_categories)
known_categories = (
@@ -1435,7 +1479,10 @@ def value_counts(self, dropna: bool = True):
--------
Series.value_counts
"""
- from pandas import CategoricalIndex, Series
+ from pandas import (
+ CategoricalIndex,
+ Series,
+ )
code, cat = self._codes, self.categories
ncat, mask = (len(cat), code >= 0)
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 3dd170f60a62c..5dd55ff0f1fa2 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -1,6 +1,9 @@
from __future__ import annotations
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import operator
from typing import (
TYPE_CHECKING,
@@ -18,7 +21,10 @@
import numpy as np
-from pandas._libs import algos, lib
+from pandas._libs import (
+ algos,
+ lib,
+)
from pandas._libs.tslibs import (
BaseOffset,
IncompatibleFrequency,
@@ -32,12 +38,28 @@
iNaT,
to_offset,
)
-from pandas._libs.tslibs.fields import RoundTo, round_nsint64
+from pandas._libs.tslibs.fields import (
+ RoundTo,
+ round_nsint64,
+)
from pandas._libs.tslibs.timestamps import integer_op_not_supported
-from pandas._typing import DatetimeLikeScalar, Dtype, DtypeObj, NpDtype
+from pandas._typing import (
+ DatetimeLikeScalar,
+ Dtype,
+ DtypeObj,
+ NpDtype,
+)
from pandas.compat.numpy import function as nv
-from pandas.errors import AbstractMethodError, NullFrequencyError, PerformanceWarning
-from pandas.util._decorators import Appender, Substitution, cache_readonly
+from pandas.errors import (
+ AbstractMethodError,
+ NullFrequencyError,
+ PerformanceWarning,
+)
+from pandas.util._decorators import (
+ Appender,
+ Substitution,
+ cache_readonly,
+)
from pandas.core.dtypes.common import (
is_categorical_dtype,
@@ -57,22 +79,47 @@
is_unsigned_integer_dtype,
pandas_dtype,
)
-from pandas.core.dtypes.missing import is_valid_na_for_dtype, isna
+from pandas.core.dtypes.missing import (
+ is_valid_na_for_dtype,
+ isna,
+)
-from pandas.core import nanops, ops
-from pandas.core.algorithms import checked_add_with_arr, isin, unique1d
+from pandas.core import (
+ nanops,
+ ops,
+)
+from pandas.core.algorithms import (
+ checked_add_with_arr,
+ isin,
+ unique1d,
+)
from pandas.core.arraylike import OpsMixin
-from pandas.core.arrays._mixins import NDArrayBackedExtensionArray, ravel_compat
+from pandas.core.arrays._mixins import (
+ NDArrayBackedExtensionArray,
+ ravel_compat,
+)
import pandas.core.common as com
-from pandas.core.construction import array, extract_array
-from pandas.core.indexers import check_array_indexer, check_setitem_lengths
+from pandas.core.construction import (
+ array,
+ extract_array,
+)
+from pandas.core.indexers import (
+ check_array_indexer,
+ check_setitem_lengths,
+)
from pandas.core.ops.common import unpack_zerodim_and_defer
-from pandas.core.ops.invalid import invalid_comparison, make_invalid_op
+from pandas.core.ops.invalid import (
+ invalid_comparison,
+ make_invalid_op,
+)
from pandas.tseries import frequencies
if TYPE_CHECKING:
- from pandas.core.arrays import DatetimeArray, TimedeltaArray
+ from pandas.core.arrays import (
+ DatetimeArray,
+ TimedeltaArray,
+ )
DTScalarOrNaT = Union[DatetimeLikeScalar, NaTType]
DatetimeLikeArrayT = TypeVar("DatetimeLikeArrayT", bound="DatetimeLikeArrayMixin")
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index 70c2015c6d41c..05184ea02e7a2 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -1,12 +1,24 @@
from __future__ import annotations
-from datetime import datetime, time, timedelta, tzinfo
-from typing import Optional, Union, cast
+from datetime import (
+ datetime,
+ time,
+ timedelta,
+ tzinfo,
+)
+from typing import (
+ Optional,
+ Union,
+ cast,
+)
import warnings
import numpy as np
-from pandas._libs import lib, tslib
+from pandas._libs import (
+ lib,
+ tslib,
+)
from pandas._libs.tslibs import (
BaseOffset,
NaT,
@@ -47,7 +59,11 @@
pandas_dtype,
)
from pandas.core.dtypes.dtypes import DatetimeTZDtype
-from pandas.core.dtypes.generic import ABCIndex, ABCPandasArray, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCIndex,
+ ABCPandasArray,
+ ABCSeries,
+)
from pandas.core.dtypes.missing import isna
from pandas.core.algorithms import checked_add_with_arr
@@ -56,7 +72,11 @@
import pandas.core.common as com
from pandas.tseries.frequencies import get_period_alias
-from pandas.tseries.offsets import BDay, Day, Tick
+from pandas.tseries.offsets import (
+ BDay,
+ Day,
+ Tick,
+)
_midnight = time(0, 0)
diff --git a/pandas/core/arrays/floating.py b/pandas/core/arrays/floating.py
index bc8f2af4f3801..a43b30f5043e2 100644
--- a/pandas/core/arrays/floating.py
+++ b/pandas/core/arrays/floating.py
@@ -1,12 +1,23 @@
from __future__ import annotations
-from typing import List, Optional, Tuple, Type
+from typing import (
+ List,
+ Optional,
+ Tuple,
+ Type,
+)
import warnings
import numpy as np
-from pandas._libs import lib, missing as libmissing
-from pandas._typing import ArrayLike, DtypeObj
+from pandas._libs import (
+ lib,
+ missing as libmissing,
+)
+from pandas._typing import (
+ ArrayLike,
+ DtypeObj,
+)
from pandas.compat.numpy import function as nv
from pandas.util._decorators import cache_readonly
@@ -20,10 +31,16 @@
is_object_dtype,
pandas_dtype,
)
-from pandas.core.dtypes.dtypes import ExtensionDtype, register_extension_dtype
+from pandas.core.dtypes.dtypes import (
+ ExtensionDtype,
+ register_extension_dtype,
+)
from pandas.core.dtypes.missing import isna
-from pandas.core.arrays.numeric import NumericArray, NumericDtype
+from pandas.core.arrays.numeric import (
+ NumericArray,
+ NumericDtype,
+)
from pandas.core.ops import invalid_comparison
from pandas.core.tools.numeric import to_numeric
@@ -303,7 +320,10 @@ def _values_for_argsort(self) -> np.ndarray:
return self._data
def _cmp_method(self, other, op):
- from pandas.arrays import BooleanArray, IntegerArray
+ from pandas.arrays import (
+ BooleanArray,
+ IntegerArray,
+ )
mask = None
diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py
index 363832ec89240..d62a05253b265 100644
--- a/pandas/core/arrays/integer.py
+++ b/pandas/core/arrays/integer.py
@@ -1,16 +1,33 @@
from __future__ import annotations
-from typing import Dict, List, Optional, Tuple, Type
+from typing import (
+ Dict,
+ List,
+ Optional,
+ Tuple,
+ Type,
+)
import warnings
import numpy as np
-from pandas._libs import iNaT, lib, missing as libmissing
-from pandas._typing import ArrayLike, Dtype, DtypeObj
+from pandas._libs import (
+ iNaT,
+ lib,
+ missing as libmissing,
+)
+from pandas._typing import (
+ ArrayLike,
+ Dtype,
+ DtypeObj,
+)
from pandas.compat.numpy import function as nv
from pandas.util._decorators import cache_readonly
-from pandas.core.dtypes.base import ExtensionDtype, register_extension_dtype
+from pandas.core.dtypes.base import (
+ ExtensionDtype,
+ register_extension_dtype,
+)
from pandas.core.dtypes.common import (
is_bool_dtype,
is_datetime64_dtype,
@@ -23,8 +40,14 @@
)
from pandas.core.dtypes.missing import isna
-from pandas.core.arrays.masked import BaseMaskedArray, BaseMaskedDtype
-from pandas.core.arrays.numeric import NumericArray, NumericDtype
+from pandas.core.arrays.masked import (
+ BaseMaskedArray,
+ BaseMaskedDtype,
+)
+from pandas.core.arrays.numeric import (
+ NumericArray,
+ NumericDtype,
+)
from pandas.core.ops import invalid_comparison
from pandas.core.tools.numeric import to_numeric
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index c720f4bdacaff..6cfc0e1853b74 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -1,9 +1,18 @@
from __future__ import annotations
import operator
-from operator import le, lt
+from operator import (
+ le,
+ lt,
+)
import textwrap
-from typing import Optional, Sequence, Type, TypeVar, cast
+from typing import (
+ Optional,
+ Sequence,
+ Type,
+ TypeVar,
+ cast,
+)
import numpy as np
@@ -17,7 +26,11 @@
intervals_to_interval_bounds,
)
from pandas._libs.missing import NA
-from pandas._typing import ArrayLike, Dtype, NpDtype
+from pandas._typing import (
+ ArrayLike,
+ Dtype,
+ NpDtype,
+)
from pandas.compat.numpy import function as nv
from pandas.util._decorators import Appender
@@ -45,10 +58,21 @@
ABCPeriodIndex,
ABCSeries,
)
-from pandas.core.dtypes.missing import is_valid_na_for_dtype, isna, notna
+from pandas.core.dtypes.missing import (
+ is_valid_na_for_dtype,
+ isna,
+ notna,
+)
-from pandas.core.algorithms import isin, take, value_counts
-from pandas.core.arrays.base import ExtensionArray, _extension_array_shared_docs
+from pandas.core.algorithms import (
+ isin,
+ take,
+ value_counts,
+)
+from pandas.core.arrays.base import (
+ ExtensionArray,
+ _extension_array_shared_docs,
+)
from pandas.core.arrays.categorical import Categorical
import pandas.core.common as com
from pandas.core.construction import (
@@ -58,7 +82,10 @@
)
from pandas.core.indexers import check_array_indexer
from pandas.core.indexes.base import ensure_index
-from pandas.core.ops import invalid_comparison, unpack_zerodim_and_defer
+from pandas.core.ops import (
+ invalid_comparison,
+ unpack_zerodim_and_defer,
+)
IntervalArrayT = TypeVar("IntervalArrayT", bound="IntervalArray")
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index a6ed75c65b2e9..bae14f4e560c2 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -1,13 +1,33 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Any, Optional, Sequence, Tuple, Type, TypeVar, Union
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Optional,
+ Sequence,
+ Tuple,
+ Type,
+ TypeVar,
+ Union,
+)
import numpy as np
-from pandas._libs import lib, missing as libmissing
-from pandas._typing import ArrayLike, Dtype, NpDtype, Scalar
+from pandas._libs import (
+ lib,
+ missing as libmissing,
+)
+from pandas._typing import (
+ ArrayLike,
+ Dtype,
+ NpDtype,
+ Scalar,
+)
from pandas.errors import AbstractMethodError
-from pandas.util._decorators import cache_readonly, doc
+from pandas.util._decorators import (
+ cache_readonly,
+ doc,
+)
from pandas.core.dtypes.base import ExtensionDtype
from pandas.core.dtypes.common import (
@@ -18,10 +38,17 @@
is_string_dtype,
pandas_dtype,
)
-from pandas.core.dtypes.missing import isna, notna
+from pandas.core.dtypes.missing import (
+ isna,
+ notna,
+)
from pandas.core import nanops
-from pandas.core.algorithms import factorize_array, isin, take
+from pandas.core.algorithms import (
+ factorize_array,
+ isin,
+ take,
+)
from pandas.core.array_algos import masked_reductions
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays import ExtensionArray
@@ -377,7 +404,10 @@ def value_counts(self, dropna: bool = True) -> Series:
--------
Series.value_counts
"""
- from pandas import Index, Series
+ from pandas import (
+ Index,
+ Series,
+ )
from pandas.arrays import IntegerArray
# compute counts on the data with no nans
diff --git a/pandas/core/arrays/numeric.py b/pandas/core/arrays/numeric.py
index 69499bc7e4a77..57017e44a66e9 100644
--- a/pandas/core/arrays/numeric.py
+++ b/pandas/core/arrays/numeric.py
@@ -2,11 +2,19 @@
import datetime
import numbers
-from typing import TYPE_CHECKING, Any, List, Union
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ List,
+ Union,
+)
import numpy as np
-from pandas._libs import Timedelta, missing as libmissing
+from pandas._libs import (
+ Timedelta,
+ missing as libmissing,
+)
from pandas.errors import AbstractMethodError
from pandas.core.dtypes.common import (
@@ -18,7 +26,10 @@
)
from pandas.core import ops
-from pandas.core.arrays.masked import BaseMaskedArray, BaseMaskedDtype
+from pandas.core.arrays.masked import (
+ BaseMaskedArray,
+ BaseMaskedDtype,
+)
if TYPE_CHECKING:
import pyarrow
diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py
index 9999a9ed411d8..78f3b0c966d16 100644
--- a/pandas/core/arrays/numpy_.py
+++ b/pandas/core/arrays/numpy_.py
@@ -1,19 +1,30 @@
from __future__ import annotations
import numbers
-from typing import Optional, Tuple, Union
+from typing import (
+ Optional,
+ Tuple,
+ Union,
+)
import numpy as np
from numpy.lib.mixins import NDArrayOperatorsMixin
from pandas._libs import lib
-from pandas._typing import Dtype, NpDtype, Scalar
+from pandas._typing import (
+ Dtype,
+ NpDtype,
+ Scalar,
+)
from pandas.compat.numpy import function as nv
from pandas.core.dtypes.dtypes import PandasDtype
from pandas.core.dtypes.missing import isna
-from pandas.core import nanops, ops
+from pandas.core import (
+ nanops,
+ ops,
+)
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays._mixins import NDArrayBackedExtensionArray
from pandas.core.strings.object_array import ObjectStringArrayMixin
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index e0149f27ad6a6..109be2c67bb1a 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -2,7 +2,15 @@
from datetime import timedelta
import operator
-from typing import Any, Callable, List, Optional, Sequence, Type, Union
+from typing import (
+ Any,
+ Callable,
+ List,
+ Optional,
+ Sequence,
+ Type,
+ Union,
+)
import numpy as np
@@ -20,7 +28,10 @@
)
from pandas._libs.tslibs.dtypes import FreqGroup
from pandas._libs.tslibs.fields import isleapyear_arr
-from pandas._libs.tslibs.offsets import Tick, delta_to_tick
+from pandas._libs.tslibs.offsets import (
+ Tick,
+ delta_to_tick,
+)
from pandas._libs.tslibs.period import (
DIFFERENT_FREQ,
IncompatibleFrequency,
@@ -29,8 +40,15 @@
get_period_field_arr,
period_asfreq_arr,
)
-from pandas._typing import AnyArrayLike, Dtype, NpDtype
-from pandas.util._decorators import cache_readonly, doc
+from pandas._typing import (
+ AnyArrayLike,
+ Dtype,
+ NpDtype,
+)
+from pandas.util._decorators import (
+ cache_readonly,
+ doc,
+)
from pandas.core.dtypes.common import (
TD64NS_DTYPE,
@@ -49,7 +67,10 @@
ABCSeries,
ABCTimedeltaArray,
)
-from pandas.core.dtypes.missing import isna, notna
+from pandas.core.dtypes.missing import (
+ isna,
+ notna,
+)
import pandas.core.algorithms as algos
from pandas.core.arrays import datetimelike as dtl
diff --git a/pandas/core/arrays/sparse/__init__.py b/pandas/core/arrays/sparse/__init__.py
index e9ff4b7d4ffc2..18294ead0329d 100644
--- a/pandas/core/arrays/sparse/__init__.py
+++ b/pandas/core/arrays/sparse/__init__.py
@@ -1,6 +1,9 @@
# flake8: noqa: F401
-from pandas.core.arrays.sparse.accessor import SparseAccessor, SparseFrameAccessor
+from pandas.core.arrays.sparse.accessor import (
+ SparseAccessor,
+ SparseFrameAccessor,
+)
from pandas.core.arrays.sparse.array import (
BlockIndex,
IntIndex,
diff --git a/pandas/core/arrays/sparse/accessor.py b/pandas/core/arrays/sparse/accessor.py
index c0bc88dc54e43..c3d11793dbd8c 100644
--- a/pandas/core/arrays/sparse/accessor.py
+++ b/pandas/core/arrays/sparse/accessor.py
@@ -6,7 +6,10 @@
from pandas.core.dtypes.cast import find_common_type
-from pandas.core.accessor import PandasDelegate, delegate_names
+from pandas.core.accessor import (
+ PandasDelegate,
+ delegate_names,
+)
from pandas.core.arrays.sparse.array import SparseArray
from pandas.core.arrays.sparse.dtype import SparseDtype
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index 4f68ed3d9a79d..a209037f9a9a6 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -6,16 +6,32 @@
from collections import abc
import numbers
import operator
-from typing import Any, Callable, Optional, Sequence, Type, TypeVar, Union
+from typing import (
+ Any,
+ Callable,
+ Optional,
+ Sequence,
+ Type,
+ TypeVar,
+ Union,
+)
import warnings
import numpy as np
from pandas._libs import lib
import pandas._libs.sparse as splib
-from pandas._libs.sparse import BlockIndex, IntIndex, SparseIndex
+from pandas._libs.sparse import (
+ BlockIndex,
+ IntIndex,
+ SparseIndex,
+)
from pandas._libs.tslibs import NaT
-from pandas._typing import Dtype, NpDtype, Scalar
+from pandas._typing import (
+ Dtype,
+ NpDtype,
+ Scalar,
+)
from pandas.compat.numpy import function as nv
from pandas.errors import PerformanceWarning
@@ -37,8 +53,15 @@
is_string_dtype,
pandas_dtype,
)
-from pandas.core.dtypes.generic import ABCIndex, ABCSeries
-from pandas.core.dtypes.missing import isna, na_value_for_dtype, notna
+from pandas.core.dtypes.generic import (
+ ABCIndex,
+ ABCSeries,
+)
+from pandas.core.dtypes.missing import (
+ isna,
+ na_value_for_dtype,
+ notna,
+)
import pandas.core.algorithms as algos
from pandas.core.arraylike import OpsMixin
@@ -46,7 +69,10 @@
from pandas.core.arrays.sparse.dtype import SparseDtype
from pandas.core.base import PandasObject
import pandas.core.common as com
-from pandas.core.construction import extract_array, sanitize_array
+from pandas.core.construction import (
+ extract_array,
+ sanitize_array,
+)
from pandas.core.indexers import check_array_indexer
from pandas.core.missing import interpolate_2d
from pandas.core.nanops import check_below_min_count
@@ -738,7 +764,10 @@ def value_counts(self, dropna: bool = True):
-------
counts : Series
"""
- from pandas import Index, Series
+ from pandas import (
+ Index,
+ Series,
+ )
keys, counts = algos.value_counts_arraylike(self.sp_values, dropna=dropna)
fcounts = self.sp_index.ngaps
diff --git a/pandas/core/arrays/sparse/dtype.py b/pandas/core/arrays/sparse/dtype.py
index 4c1c1b42ff6fa..948edcbd99e64 100644
--- a/pandas/core/arrays/sparse/dtype.py
+++ b/pandas/core/arrays/sparse/dtype.py
@@ -2,15 +2,28 @@
from __future__ import annotations
import re
-from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Type
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ List,
+ Optional,
+ Tuple,
+ Type,
+)
import warnings
import numpy as np
-from pandas._typing import Dtype, DtypeObj
+from pandas._typing import (
+ Dtype,
+ DtypeObj,
+)
from pandas.errors import PerformanceWarning
-from pandas.core.dtypes.base import ExtensionDtype, register_extension_dtype
+from pandas.core.dtypes.base import (
+ ExtensionDtype,
+ register_extension_dtype,
+)
from pandas.core.dtypes.cast import astype_nansafe
from pandas.core.dtypes.common import (
is_bool_dtype,
@@ -20,7 +33,10 @@
is_string_dtype,
pandas_dtype,
)
-from pandas.core.dtypes.missing import isna, na_value_for_dtype
+from pandas.core.dtypes.missing import (
+ isna,
+ na_value_for_dtype,
+)
if TYPE_CHECKING:
from pandas.core.arrays.sparse.array import SparseArray
diff --git a/pandas/core/arrays/sparse/scipy_sparse.py b/pandas/core/arrays/sparse/scipy_sparse.py
index 56c678c88b9c7..ad2c5f75fc32c 100644
--- a/pandas/core/arrays/sparse/scipy_sparse.py
+++ b/pandas/core/arrays/sparse/scipy_sparse.py
@@ -3,7 +3,10 @@
Currently only includes to_coo helpers.
"""
-from pandas.core.indexes.api import Index, MultiIndex
+from pandas.core.indexes.api import (
+ Index,
+ MultiIndex,
+)
from pandas.core.series import Series
diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py
index b318757e8978a..6fd68050bc8dc 100644
--- a/pandas/core/arrays/string_.py
+++ b/pandas/core/arrays/string_.py
@@ -1,14 +1,28 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Optional, Type, Union
+from typing import (
+ TYPE_CHECKING,
+ Optional,
+ Type,
+ Union,
+)
import numpy as np
-from pandas._libs import lib, missing as libmissing
-from pandas._typing import Dtype, Scalar
+from pandas._libs import (
+ lib,
+ missing as libmissing,
+)
+from pandas._typing import (
+ Dtype,
+ Scalar,
+)
from pandas.compat.numpy import function as nv
-from pandas.core.dtypes.base import ExtensionDtype, register_extension_dtype
+from pandas.core.dtypes.base import (
+ ExtensionDtype,
+ register_extension_dtype,
+)
from pandas.core.dtypes.common import (
is_array_like,
is_bool_dtype,
@@ -21,7 +35,11 @@
from pandas.core import ops
from pandas.core.array_algos import masked_reductions
-from pandas.core.arrays import FloatingArray, IntegerArray, PandasArray
+from pandas.core.arrays import (
+ FloatingArray,
+ IntegerArray,
+ PandasArray,
+)
from pandas.core.arrays.floating import FloatingDtype
from pandas.core.arrays.integer import _IntegerDtype
from pandas.core.construction import extract_array
@@ -385,7 +403,11 @@ def _cmp_method(self, other, op):
_str_na_value = StringDtype.na_value
def _str_map(self, f, na_value=None, dtype: Optional[Dtype] = None):
- from pandas.arrays import BooleanArray, IntegerArray, StringArray
+ from pandas.arrays import (
+ BooleanArray,
+ IntegerArray,
+ StringArray,
+ )
from pandas.core.arrays.string_ import StringDtype
if dtype is None:
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index 252e9a84022db..e2b0ad372bf88 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -1,12 +1,25 @@
from __future__ import annotations
from distutils.version import LooseVersion
-from typing import TYPE_CHECKING, Any, Optional, Sequence, Type, Union
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Optional,
+ Sequence,
+ Type,
+ Union,
+)
import numpy as np
-from pandas._libs import lib, missing as libmissing
-from pandas._typing import Dtype, NpDtype
+from pandas._libs import (
+ lib,
+ missing as libmissing,
+)
+from pandas._typing import (
+ Dtype,
+ NpDtype,
+)
from pandas.util._validators import validate_fillna_kwargs
from pandas.core.dtypes.base import ExtensionDtype
@@ -22,7 +35,10 @@
)
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays.base import ExtensionArray
-from pandas.core.indexers import check_array_indexer, validate_indices
+from pandas.core.indexers import (
+ check_array_indexer,
+ validate_indices,
+)
from pandas.core.missing import get_fill_func
try:
@@ -615,7 +631,10 @@ def value_counts(self, dropna: bool = True) -> Series:
--------
Series.value_counts
"""
- from pandas import Index, Series
+ from pandas import (
+ Index,
+ Series,
+ )
vc = self._data.value_counts()
diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py
index 480aaf3d48f62..893644be23a0e 100644
--- a/pandas/core/arrays/timedeltas.py
+++ b/pandas/core/arrays/timedeltas.py
@@ -1,11 +1,18 @@
from __future__ import annotations
from datetime import timedelta
-from typing import List, Optional, Union
+from typing import (
+ List,
+ Optional,
+ Union,
+)
import numpy as np
-from pandas._libs import lib, tslibs
+from pandas._libs import (
+ lib,
+ tslibs,
+)
from pandas._libs.tslibs import (
BaseOffset,
NaT,
@@ -42,12 +49,18 @@
pandas_dtype,
)
from pandas.core.dtypes.dtypes import DatetimeTZDtype
-from pandas.core.dtypes.generic import ABCSeries, ABCTimedeltaIndex
+from pandas.core.dtypes.generic import (
+ ABCSeries,
+ ABCTimedeltaIndex,
+)
from pandas.core.dtypes.missing import isna
from pandas.core import nanops
from pandas.core.algorithms import checked_add_with_arr
-from pandas.core.arrays import IntegerArray, datetimelike as dtl
+from pandas.core.arrays import (
+ IntegerArray,
+ datetimelike as dtl,
+)
from pandas.core.arrays._ranges import generate_regular_range
import pandas.core.common as com
from pandas.core.construction import extract_array
diff --git a/pandas/core/base.py b/pandas/core/base.py
index 3f3b4cd1afec1..fd40e0467720d 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -19,11 +19,18 @@
import numpy as np
import pandas._libs.lib as lib
-from pandas._typing import Dtype, DtypeObj, IndexLabel
+from pandas._typing import (
+ Dtype,
+ DtypeObj,
+ IndexLabel,
+)
from pandas.compat import PYPY
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
-from pandas.util._decorators import cache_readonly, doc
+from pandas.util._decorators import (
+ cache_readonly,
+ doc,
+)
from pandas.core.dtypes.common import (
is_categorical_dtype,
@@ -32,12 +39,23 @@
is_object_dtype,
is_scalar,
)
-from pandas.core.dtypes.generic import ABCDataFrame, ABCIndex, ABCSeries
-from pandas.core.dtypes.missing import isna, remove_na_arraylike
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCIndex,
+ ABCSeries,
+)
+from pandas.core.dtypes.missing import (
+ isna,
+ remove_na_arraylike,
+)
from pandas.core import algorithms
from pandas.core.accessor import DirNamesMixin
-from pandas.core.algorithms import duplicated, unique1d, value_counts
+from pandas.core.algorithms import (
+ duplicated,
+ unique1d,
+ value_counts,
+)
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays import ExtensionArray
from pandas.core.construction import create_series_with_explicit_dtype
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 89ba33da92661..50aed70bf275d 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -4,7 +4,10 @@
Note: pandas.core.common is *not* part of the public API.
"""
-from collections import abc, defaultdict
+from collections import (
+ abc,
+ defaultdict,
+)
import contextlib
from functools import partial
import inspect
@@ -25,7 +28,12 @@
import numpy as np
from pandas._libs import lib
-from pandas._typing import AnyArrayLike, NpDtype, Scalar, T
+from pandas._typing import (
+ AnyArrayLike,
+ NpDtype,
+ Scalar,
+ T,
+)
from pandas.compat import np_version_under1p18
from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
@@ -35,9 +43,17 @@
is_extension_array_dtype,
is_integer,
)
-from pandas.core.dtypes.generic import ABCExtensionArray, ABCIndex, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCExtensionArray,
+ ABCIndex,
+ ABCSeries,
+)
from pandas.core.dtypes.inference import iterable_not_string
-from pandas.core.dtypes.missing import isna, isnull, notnull # noqa
+from pandas.core.dtypes.missing import ( # noqa
+ isna,
+ isnull,
+ notnull,
+)
class SettingWithCopyError(ValueError):
diff --git a/pandas/core/computation/align.py b/pandas/core/computation/align.py
index 5ad3e78a76866..94724d559e501 100644
--- a/pandas/core/computation/align.py
+++ b/pandas/core/computation/align.py
@@ -3,8 +3,19 @@
"""
from __future__ import annotations
-from functools import partial, wraps
-from typing import TYPE_CHECKING, Dict, Optional, Sequence, Tuple, Type, Union
+from functools import (
+ partial,
+ wraps,
+)
+from typing import (
+ TYPE_CHECKING,
+ Dict,
+ Optional,
+ Sequence,
+ Tuple,
+ Type,
+ Union,
+)
import warnings
import numpy as np
@@ -12,7 +23,10 @@
from pandas._typing import FrameOrSeries
from pandas.errors import PerformanceWarning
-from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCSeries,
+)
from pandas.core.base import PandasObject
import pandas.core.common as com
diff --git a/pandas/core/computation/engines.py b/pandas/core/computation/engines.py
index 77a378369ca34..5b2dbed7af6ea 100644
--- a/pandas/core/computation/engines.py
+++ b/pandas/core/computation/engines.py
@@ -3,10 +3,19 @@
"""
import abc
-from typing import Dict, Type
-
-from pandas.core.computation.align import align_terms, reconstruct_object
-from pandas.core.computation.ops import MATHOPS, REDUCTIONS
+from typing import (
+ Dict,
+ Type,
+)
+
+from pandas.core.computation.align import (
+ align_terms,
+ reconstruct_object,
+)
+from pandas.core.computation.ops import (
+ MATHOPS,
+ REDUCTIONS,
+)
import pandas.io.formats.printing as printing
diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py
index 12f16343362e2..51fcbb02fd926 100644
--- a/pandas/core/computation/eval.py
+++ b/pandas/core/computation/eval.py
@@ -10,7 +10,10 @@
from pandas.util._validators import validate_bool_kwarg
from pandas.core.computation.engines import ENGINES
-from pandas.core.computation.expr import PARSERS, Expr
+from pandas.core.computation.expr import (
+ PARSERS,
+ Expr,
+)
from pandas.core.computation.parsing import tokenize_string
from pandas.core.computation.scope import ensure_scope
diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py
index ee91ab4a282cf..02660539f4981 100644
--- a/pandas/core/computation/expr.py
+++ b/pandas/core/computation/expr.py
@@ -3,10 +3,20 @@
"""
import ast
-from functools import partial, reduce
+from functools import (
+ partial,
+ reduce,
+)
from keyword import iskeyword
import tokenize
-from typing import Callable, Optional, Set, Tuple, Type, TypeVar
+from typing import (
+ Callable,
+ Optional,
+ Set,
+ Tuple,
+ Type,
+ TypeVar,
+)
import numpy as np
@@ -31,7 +41,10 @@
UndefinedVariableError,
is_term,
)
-from pandas.core.computation.parsing import clean_backtick_quoted_toks, tokenize_string
+from pandas.core.computation.parsing import (
+ clean_backtick_quoted_toks,
+ tokenize_string,
+)
from pandas.core.computation.scope import Scope
import pandas.io.formats.printing as printing
diff --git a/pandas/core/computation/expressions.py b/pandas/core/computation/expressions.py
index 087b7f39e3374..4e6ec4c6a7d93 100644
--- a/pandas/core/computation/expressions.py
+++ b/pandas/core/computation/expressions.py
@@ -6,7 +6,11 @@
"""
import operator
-from typing import List, Optional, Set
+from typing import (
+ List,
+ Optional,
+ Set,
+)
import warnings
import numpy as np
diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py
index e8eae710623c5..2f7623060e7dc 100644
--- a/pandas/core/computation/ops.py
+++ b/pandas/core/computation/ops.py
@@ -8,19 +8,33 @@
from distutils.version import LooseVersion
from functools import partial
import operator
-from typing import Callable, Iterable, Optional, Union
+from typing import (
+ Callable,
+ Iterable,
+ Optional,
+ Union,
+)
import numpy as np
from pandas._libs.tslibs import Timestamp
-from pandas.core.dtypes.common import is_list_like, is_scalar
+from pandas.core.dtypes.common import (
+ is_list_like,
+ is_scalar,
+)
import pandas.core.common as com
-from pandas.core.computation.common import ensure_decoded, result_type_many
+from pandas.core.computation.common import (
+ ensure_decoded,
+ result_type_many,
+)
from pandas.core.computation.scope import DEFAULT_GLOBALS
-from pandas.io.formats.printing import pprint_thing, pprint_thing_encoded
+from pandas.io.formats.printing import (
+ pprint_thing,
+ pprint_thing_encoded,
+)
REDUCTIONS = ("sum", "prod")
@@ -604,7 +618,10 @@ def __repr__(self) -> str:
class FuncNode:
def __init__(self, name: str):
- from pandas.core.computation.check import NUMEXPR_INSTALLED, NUMEXPR_VERSION
+ from pandas.core.computation.check import (
+ NUMEXPR_INSTALLED,
+ NUMEXPR_VERSION,
+ )
if name not in MATHOPS or (
NUMEXPR_INSTALLED
diff --git a/pandas/core/computation/parsing.py b/pandas/core/computation/parsing.py
index 3c2f7f2793358..f3321fc55ad80 100644
--- a/pandas/core/computation/parsing.py
+++ b/pandas/core/computation/parsing.py
@@ -6,7 +6,11 @@
from keyword import iskeyword
import token
import tokenize
-from typing import Hashable, Iterator, Tuple
+from typing import (
+ Hashable,
+ Iterator,
+ Tuple,
+)
# A token value Python's tokenizer probably will never use.
BACKTICK_QUOTED_STRING = 100
diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py
index 6a3b95186d666..5e7fdb8dc9c7d 100644
--- a/pandas/core/computation/pytables.py
+++ b/pandas/core/computation/pytables.py
@@ -3,24 +3,42 @@
import ast
from functools import partial
-from typing import Any, Dict, Optional, Tuple
+from typing import (
+ Any,
+ Dict,
+ Optional,
+ Tuple,
+)
import numpy as np
-from pandas._libs.tslibs import Timedelta, Timestamp
+from pandas._libs.tslibs import (
+ Timedelta,
+ Timestamp,
+)
from pandas.compat.chainmap import DeepChainMap
from pandas.core.dtypes.common import is_list_like
import pandas.core.common as com
-from pandas.core.computation import expr, ops, scope as _scope
+from pandas.core.computation import (
+ expr,
+ ops,
+ scope as _scope,
+)
from pandas.core.computation.common import ensure_decoded
from pandas.core.computation.expr import BaseExprVisitor
-from pandas.core.computation.ops import UndefinedVariableError, is_term
+from pandas.core.computation.ops import (
+ UndefinedVariableError,
+ is_term,
+)
from pandas.core.construction import extract_array
from pandas.core.indexes.base import Index
-from pandas.io.formats.printing import pprint_thing, pprint_thing_encoded
+from pandas.io.formats.printing import (
+ pprint_thing,
+ pprint_thing_encoded,
+)
class PyTablesScope(_scope.Scope):
diff --git a/pandas/core/construction.py b/pandas/core/construction.py
index 8aa3d7900e8e9..dd75473da6d78 100644
--- a/pandas/core/construction.py
+++ b/pandas/core/construction.py
@@ -7,16 +7,34 @@
from __future__ import annotations
from collections import abc
-from typing import TYPE_CHECKING, Any, Optional, Sequence, Union, cast
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Optional,
+ Sequence,
+ Union,
+ cast,
+)
import numpy as np
import numpy.ma as ma
from pandas._libs import lib
-from pandas._libs.tslibs import IncompatibleFrequency, OutOfBoundsDatetime
-from pandas._typing import AnyArrayLike, ArrayLike, Dtype, DtypeObj
+from pandas._libs.tslibs import (
+ IncompatibleFrequency,
+ OutOfBoundsDatetime,
+)
+from pandas._typing import (
+ AnyArrayLike,
+ ArrayLike,
+ Dtype,
+ DtypeObj,
+)
-from pandas.core.dtypes.base import ExtensionDtype, registry
+from pandas.core.dtypes.base import (
+ ExtensionDtype,
+ registry,
+)
from pandas.core.dtypes.cast import (
construct_1d_arraylike_from_scalar,
construct_1d_ndarray_preserving_na,
@@ -49,7 +67,11 @@
import pandas.core.common as com
if TYPE_CHECKING:
- from pandas import ExtensionArray, Index, Series
+ from pandas import (
+ ExtensionArray,
+ Index,
+ Series,
+ )
def array(
diff --git a/pandas/core/describe.py b/pandas/core/describe.py
index dcafb3c3a8be5..3a872c6202e04 100644
--- a/pandas/core/describe.py
+++ b/pandas/core/describe.py
@@ -5,14 +5,29 @@
"""
from __future__ import annotations
-from abc import ABC, abstractmethod
-from typing import TYPE_CHECKING, Callable, List, Optional, Sequence, Union, cast
+from abc import (
+ ABC,
+ abstractmethod,
+)
+from typing import (
+ TYPE_CHECKING,
+ Callable,
+ List,
+ Optional,
+ Sequence,
+ Union,
+ cast,
+)
import warnings
import numpy as np
from pandas._libs.tslibs import Timestamp
-from pandas._typing import FrameOrSeries, FrameOrSeriesUnion, Hashable
+from pandas._typing import (
+ FrameOrSeries,
+ FrameOrSeriesUnion,
+ Hashable,
+)
from pandas.util._validators import validate_percentile
from pandas.core.dtypes.common import (
@@ -27,7 +42,10 @@
from pandas.io.formats.format import format_percentiles
if TYPE_CHECKING:
- from pandas import DataFrame, Series
+ from pandas import (
+ DataFrame,
+ Series,
+ )
def describe_ndframe(
diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py
index 887bbc052b5c9..d83405803753a 100644
--- a/pandas/core/dtypes/base.py
+++ b/pandas/core/dtypes/base.py
@@ -4,14 +4,26 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Type, Union
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ List,
+ Optional,
+ Tuple,
+ Type,
+ Union,
+)
import numpy as np
from pandas._typing import DtypeObj
from pandas.errors import AbstractMethodError
-from pandas.core.dtypes.generic import ABCDataFrame, ABCIndex, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCIndex,
+ ABCSeries,
+)
if TYPE_CHECKING:
from pandas.core.arrays import ExtensionArray
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 74d750288bdeb..301056dd07a3b 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -5,7 +5,11 @@
from __future__ import annotations
from contextlib import suppress
-from datetime import date, datetime, timedelta
+from datetime import (
+ date,
+ datetime,
+ timedelta,
+)
from typing import (
TYPE_CHECKING,
Any,
@@ -24,7 +28,10 @@
import numpy as np
-from pandas._libs import lib, tslib
+from pandas._libs import (
+ lib,
+ tslib,
+)
from pandas._libs.tslibs import (
NaT,
OutOfBoundsDatetime,
@@ -36,7 +43,13 @@
iNaT,
ints_to_pydatetime,
)
-from pandas._typing import AnyArrayLike, ArrayLike, Dtype, DtypeObj, Scalar
+from pandas._typing import (
+ AnyArrayLike,
+ ArrayLike,
+ Dtype,
+ DtypeObj,
+ Scalar,
+)
from pandas.util._exceptions import find_stack_level
from pandas.util._validators import validate_bool_kwarg
@@ -95,7 +108,10 @@
if TYPE_CHECKING:
from pandas import Series
- from pandas.core.arrays import DatetimeArray, ExtensionArray
+ from pandas.core.arrays import (
+ DatetimeArray,
+ ExtensionArray,
+ )
_int8_max = np.iinfo(np.int8).max
_int16_max = np.iinfo(np.int16).max
@@ -387,7 +403,10 @@ def maybe_cast_result_dtype(dtype: DtypeObj, how: str) -> DtypeObj:
"""
from pandas.core.arrays.boolean import BooleanDtype
from pandas.core.arrays.floating import Float64Dtype
- from pandas.core.arrays.integer import Int64Dtype, _IntegerDtype
+ from pandas.core.arrays.integer import (
+ Int64Dtype,
+ _IntegerDtype,
+ )
if how in ["add", "cumsum", "sum", "prod"]:
if dtype == np.dtype(bool):
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index d24cff4ae81bb..0966d0b93cc25 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -2,14 +2,26 @@
Common type operations.
"""
-from typing import Any, Callable, Union
+from typing import (
+ Any,
+ Callable,
+ Union,
+)
import warnings
import numpy as np
-from pandas._libs import Interval, Period, algos
+from pandas._libs import (
+ Interval,
+ Period,
+ algos,
+)
from pandas._libs.tslibs import conversion
-from pandas._typing import ArrayLike, DtypeObj, Optional
+from pandas._typing import (
+ ArrayLike,
+ DtypeObj,
+ Optional,
+)
from pandas.core.dtypes.base import registry
from pandas.core.dtypes.dtypes import (
@@ -19,7 +31,10 @@
IntervalDtype,
PeriodDtype,
)
-from pandas.core.dtypes.generic import ABCCategorical, ABCIndex
+from pandas.core.dtypes.generic import (
+ ABCCategorical,
+ ABCIndex,
+)
from pandas.core.dtypes.inference import ( # noqa:F401
is_array_like,
is_bool,
diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py
index b766392e35601..42ac786ff315e 100644
--- a/pandas/core/dtypes/concat.py
+++ b/pandas/core/dtypes/concat.py
@@ -5,7 +5,10 @@
import numpy as np
-from pandas._typing import ArrayLike, DtypeObj
+from pandas._typing import (
+ ArrayLike,
+ DtypeObj,
+)
from pandas.core.dtypes.cast import find_common_type
from pandas.core.dtypes.common import (
@@ -14,11 +17,17 @@
is_extension_array_dtype,
is_sparse,
)
-from pandas.core.dtypes.generic import ABCCategoricalIndex, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCCategoricalIndex,
+ ABCSeries,
+)
from pandas.core.arrays import ExtensionArray
from pandas.core.arrays.sparse import SparseArray
-from pandas.core.construction import array, ensure_wrapped_if_datetimelike
+from pandas.core.construction import (
+ array,
+ ensure_wrapped_if_datetimelike,
+)
def _cast_to_common_type(arr: ArrayLike, dtype: DtypeObj) -> ArrayLike:
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index deafc17f76e10..da3a9269cf2c4 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -31,11 +31,25 @@
to_offset,
tz_compare,
)
-from pandas._typing import Dtype, DtypeObj, NpDtype, Ordered
+from pandas._typing import (
+ Dtype,
+ DtypeObj,
+ NpDtype,
+ Ordered,
+)
-from pandas.core.dtypes.base import ExtensionDtype, register_extension_dtype
-from pandas.core.dtypes.generic import ABCCategoricalIndex, ABCIndex
-from pandas.core.dtypes.inference import is_bool, is_list_like
+from pandas.core.dtypes.base import (
+ ExtensionDtype,
+ register_extension_dtype,
+)
+from pandas.core.dtypes.generic import (
+ ABCCategoricalIndex,
+ ABCIndex,
+)
+from pandas.core.dtypes.inference import (
+ is_bool,
+ is_list_like,
+)
if TYPE_CHECKING:
import pyarrow
@@ -1032,7 +1046,10 @@ class IntervalDtype(PandasExtensionDtype):
_cache: Dict[str_type, PandasExtensionDtype] = {}
def __new__(cls, subtype=None, closed: Optional[str_type] = None):
- from pandas.core.dtypes.common import is_string_dtype, pandas_dtype
+ from pandas.core.dtypes.common import (
+ is_string_dtype,
+ pandas_dtype,
+ )
if closed is not None and closed not in {"right", "left", "both", "neither"}:
raise ValueError("closed must be one of 'right', 'left', 'both', 'neither'")
diff --git a/pandas/core/dtypes/generic.py b/pandas/core/dtypes/generic.py
index 47a6009590d8b..2de7b262c3533 100644
--- a/pandas/core/dtypes/generic.py
+++ b/pandas/core/dtypes/generic.py
@@ -1,7 +1,11 @@
""" define generic base classes for pandas objects """
from __future__ import annotations
-from typing import TYPE_CHECKING, Type, cast
+from typing import (
+ TYPE_CHECKING,
+ Type,
+ cast,
+)
if TYPE_CHECKING:
from pandas import (
diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py
index 7ebbbdc9ce7f9..2eeb2ae793fe7 100644
--- a/pandas/core/dtypes/missing.py
+++ b/pandas/core/dtypes/missing.py
@@ -9,8 +9,15 @@
from pandas._libs import lib
import pandas._libs.missing as libmissing
-from pandas._libs.tslibs import NaT, Period, iNaT
-from pandas._typing import ArrayLike, DtypeObj
+from pandas._libs.tslibs import (
+ NaT,
+ Period,
+ iNaT,
+)
+from pandas._typing import (
+ ArrayLike,
+ DtypeObj,
+)
from pandas.core.dtypes.common import (
DT64NS_DTYPE,
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 4f3b1357b1000..060652c9f94ae 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -44,7 +44,11 @@
from pandas._config import get_option
-from pandas._libs import algos as libalgos, lib, properties
+from pandas._libs import (
+ algos as libalgos,
+ lib,
+ properties,
+)
from pandas._libs.lib import no_default
from pandas._typing import (
AggFuncType,
@@ -119,16 +123,35 @@
is_sequence,
pandas_dtype,
)
-from pandas.core.dtypes.missing import isna, notna
+from pandas.core.dtypes.missing import (
+ isna,
+ notna,
+)
-from pandas.core import algorithms, common as com, generic, nanops, ops
+from pandas.core import (
+ algorithms,
+ common as com,
+ generic,
+ nanops,
+ ops,
+)
from pandas.core.accessor import CachedAccessor
-from pandas.core.aggregation import reconstruct_func, relabel_result, transform
+from pandas.core.aggregation import (
+ reconstruct_func,
+ relabel_result,
+ transform,
+)
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays import ExtensionArray
from pandas.core.arrays.sparse import SparseFrameAccessor
-from pandas.core.construction import extract_array, sanitize_masked_array
-from pandas.core.generic import NDFrame, _shared_docs
+from pandas.core.construction import (
+ extract_array,
+ sanitize_masked_array,
+)
+from pandas.core.generic import (
+ NDFrame,
+ _shared_docs,
+)
from pandas.core.indexers import check_key_length
from pandas.core.indexes import base as ibase
from pandas.core.indexes.api import (
@@ -138,9 +161,18 @@
ensure_index,
ensure_index_from_sequences,
)
-from pandas.core.indexes.multi import MultiIndex, maybe_droplevels
-from pandas.core.indexing import check_bool_indexer, convert_to_index_sliceable
-from pandas.core.internals import ArrayManager, BlockManager
+from pandas.core.indexes.multi import (
+ MultiIndex,
+ maybe_droplevels,
+)
+from pandas.core.indexing import (
+ check_bool_indexer,
+ convert_to_index_sliceable,
+)
+from pandas.core.internals import (
+ ArrayManager,
+ BlockManager,
+)
from pandas.core.internals.construction import (
arrays_to_mgr,
dataclasses_to_dicts,
@@ -156,17 +188,30 @@
)
from pandas.core.reshape.melt import melt
from pandas.core.series import Series
-from pandas.core.sorting import get_group_index, lexsort_indexer, nargsort
+from pandas.core.sorting import (
+ get_group_index,
+ lexsort_indexer,
+ nargsort,
+)
from pandas.io.common import get_handle
-from pandas.io.formats import console, format as fmt
-from pandas.io.formats.info import BaseInfo, DataFrameInfo
+from pandas.io.formats import (
+ console,
+ format as fmt,
+)
+from pandas.io.formats.info import (
+ BaseInfo,
+ DataFrameInfo,
+)
import pandas.plotting
if TYPE_CHECKING:
from typing import Literal
- from pandas._typing import TimedeltaConvertibleTypes, TimestampConvertibleTypes
+ from pandas._typing import (
+ TimedeltaConvertibleTypes,
+ TimestampConvertibleTypes,
+ )
from pandas.core.groupby.generic import DataFrameGroupBy
from pandas.core.resample import Resampler
@@ -7313,7 +7358,10 @@ def stack(self, level: Level = -1, dropna: bool = True):
dog kg NaN 2.0
m 3.0 NaN
"""
- from pandas.core.reshape.reshape import stack, stack_multiple
+ from pandas.core.reshape.reshape import (
+ stack,
+ stack_multiple,
+ )
if isinstance(level, (tuple, list)):
result = stack_multiple(self, level, dropna=dropna)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 6413489a74ae6..a32ae7090ef8b 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -33,7 +33,12 @@
from pandas._config import config
from pandas._libs import lib
-from pandas._libs.tslibs import Period, Tick, Timestamp, to_offset
+from pandas._libs.tslibs import (
+ Period,
+ Tick,
+ Timestamp,
+ to_offset,
+)
from pandas._typing import (
Axis,
CompressionOptions,
@@ -57,9 +62,18 @@
)
from pandas.compat._optional import import_optional_dependency
from pandas.compat.numpy import function as nv
-from pandas.errors import AbstractMethodError, InvalidIndexError
-from pandas.util._decorators import doc, rewrite_axis_style_signature
-from pandas.util._validators import validate_bool_kwarg, validate_fillna_kwargs
+from pandas.errors import (
+ AbstractMethodError,
+ InvalidIndexError,
+)
+from pandas.util._decorators import (
+ doc,
+ rewrite_axis_style_signature,
+)
+from pandas.util._validators import (
+ validate_bool_kwarg,
+ validate_fillna_kwargs,
+)
from pandas.core.dtypes.common import (
ensure_int64,
@@ -82,16 +96,33 @@
is_timedelta64_dtype,
pandas_dtype,
)
-from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCSeries,
+)
from pandas.core.dtypes.inference import is_hashable
-from pandas.core.dtypes.missing import isna, notna
+from pandas.core.dtypes.missing import (
+ isna,
+ notna,
+)
-from pandas.core import arraylike, indexing, missing, nanops
+from pandas.core import (
+ arraylike,
+ indexing,
+ missing,
+ nanops,
+)
import pandas.core.algorithms as algos
from pandas.core.arrays import ExtensionArray
-from pandas.core.base import PandasObject, SelectionMixin
+from pandas.core.base import (
+ PandasObject,
+ SelectionMixin,
+)
import pandas.core.common as com
-from pandas.core.construction import create_series_with_explicit_dtype, extract_array
+from pandas.core.construction import (
+ create_series_with_explicit_dtype,
+ extract_array,
+)
from pandas.core.describe import describe_ndframe
from pandas.core.flags import Flags
from pandas.core.indexes import base as ibase
@@ -103,16 +134,27 @@
RangeIndex,
ensure_index,
)
-from pandas.core.internals import ArrayManager, BlockManager
+from pandas.core.internals import (
+ ArrayManager,
+ BlockManager,
+)
from pandas.core.missing import find_valid_index
from pandas.core.ops import align_method_FRAME
from pandas.core.reshape.concat import concat
from pandas.core.shared_docs import _shared_docs
from pandas.core.sorting import get_indexer_indexer
-from pandas.core.window import Expanding, ExponentialMovingWindow, Rolling, Window
+from pandas.core.window import (
+ Expanding,
+ ExponentialMovingWindow,
+ Rolling,
+ Window,
+)
from pandas.io.formats import format as fmt
-from pandas.io.formats.format import DataFrameFormatter, DataFrameRenderer
+from pandas.io.formats.format import (
+ DataFrameFormatter,
+ DataFrameRenderer,
+)
from pandas.io.formats.printing import pprint_thing
if TYPE_CHECKING:
diff --git a/pandas/core/groupby/__init__.py b/pandas/core/groupby/__init__.py
index 0c5d2658978b4..8248f378e2c1a 100644
--- a/pandas/core/groupby/__init__.py
+++ b/pandas/core/groupby/__init__.py
@@ -1,4 +1,8 @@
-from pandas.core.groupby.generic import DataFrameGroupBy, NamedAgg, SeriesGroupBy
+from pandas.core.groupby.generic import (
+ DataFrameGroupBy,
+ NamedAgg,
+ SeriesGroupBy,
+)
from pandas.core.groupby.groupby import GroupBy
from pandas.core.groupby.grouper import Grouper
diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py
index 9f1446b359f66..c169e29b74dbb 100644
--- a/pandas/core/groupby/base.py
+++ b/pandas/core/groupby/base.py
@@ -9,7 +9,10 @@
from pandas._typing import final
-from pandas.core.dtypes.common import is_list_like, is_scalar
+from pandas.core.dtypes.common import (
+ is_list_like,
+ is_scalar,
+)
from pandas.core.base import PandasObject
diff --git a/pandas/core/groupby/categorical.py b/pandas/core/groupby/categorical.py
index 64037f5757a38..c9dd420ec33df 100644
--- a/pandas/core/groupby/categorical.py
+++ b/pandas/core/groupby/categorical.py
@@ -1,4 +1,7 @@
-from typing import Optional, Tuple
+from typing import (
+ Optional,
+ Tuple,
+)
import numpy as np
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 9369dc61ca5f6..c1a277925de2a 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -7,7 +7,10 @@
"""
from __future__ import annotations
-from collections import abc, namedtuple
+from collections import (
+ abc,
+ namedtuple,
+)
import copy
from functools import partial
from textwrap import dedent
@@ -32,9 +35,20 @@
import numpy as np
-from pandas._libs import lib, reduction as libreduction
-from pandas._typing import ArrayLike, FrameOrSeries, FrameOrSeriesUnion
-from pandas.util._decorators import Appender, Substitution, doc
+from pandas._libs import (
+ lib,
+ reduction as libreduction,
+)
+from pandas._typing import (
+ ArrayLike,
+ FrameOrSeries,
+ FrameOrSeriesUnion,
+)
+from pandas.util._decorators import (
+ Appender,
+ Substitution,
+ doc,
+)
from pandas.core.dtypes.cast import (
find_common_type,
@@ -53,17 +67,29 @@
is_scalar,
needs_i8_conversion,
)
-from pandas.core.dtypes.missing import isna, notna
+from pandas.core.dtypes.missing import (
+ isna,
+ notna,
+)
-from pandas.core import algorithms, nanops
+from pandas.core import (
+ algorithms,
+ nanops,
+)
from pandas.core.aggregation import (
maybe_mangle_lambdas,
reconstruct_func,
validate_func_kwargs,
)
from pandas.core.apply import GroupByApply
-from pandas.core.arrays import Categorical, ExtensionArray
-from pandas.core.base import DataError, SpecificationError
+from pandas.core.arrays import (
+ Categorical,
+ ExtensionArray,
+)
+from pandas.core.base import (
+ DataError,
+ SpecificationError,
+)
import pandas.core.common as com
from pandas.core.construction import create_series_with_explicit_dtype
from pandas.core.frame import DataFrame
@@ -77,7 +103,11 @@
get_groupby,
group_selection_context,
)
-from pandas.core.indexes.api import Index, MultiIndex, all_indexes_same
+from pandas.core.indexes.api import (
+ Index,
+ MultiIndex,
+ all_indexes_same,
+)
import pandas.core.indexes.base as ibase
from pandas.core.internals import BlockManager
from pandas.core.series import Series
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 66e7bc78b2f81..bc277bf67614d 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -10,7 +10,10 @@ class providing the base-class of operations.
from contextlib import contextmanager
import datetime
-from functools import partial, wraps
+from functools import (
+ partial,
+ wraps,
+)
import inspect
from textwrap import dedent
import types
@@ -37,7 +40,10 @@ class providing the base-class of operations.
from pandas._config.config import option_context
-from pandas._libs import Timestamp, lib
+from pandas._libs import (
+ Timestamp,
+ lib,
+)
import pandas._libs.groupby as libgroupby
from pandas._typing import (
F,
@@ -50,7 +56,12 @@ class providing the base-class of operations.
)
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
-from pandas.util._decorators import Appender, Substitution, cache_readonly, doc
+from pandas.util._decorators import (
+ Appender,
+ Substitution,
+ cache_readonly,
+ doc,
+)
from pandas.core.dtypes.cast import maybe_downcast_numeric
from pandas.core.dtypes.common import (
@@ -64,17 +75,35 @@ class providing the base-class of operations.
is_scalar,
is_timedelta64_dtype,
)
-from pandas.core.dtypes.missing import isna, notna
+from pandas.core.dtypes.missing import (
+ isna,
+ notna,
+)
from pandas.core import nanops
import pandas.core.algorithms as algorithms
-from pandas.core.arrays import Categorical, DatetimeArray
-from pandas.core.base import DataError, PandasObject, SelectionMixin
+from pandas.core.arrays import (
+ Categorical,
+ DatetimeArray,
+)
+from pandas.core.base import (
+ DataError,
+ PandasObject,
+ SelectionMixin,
+)
import pandas.core.common as com
from pandas.core.frame import DataFrame
from pandas.core.generic import NDFrame
-from pandas.core.groupby import base, numba_, ops
-from pandas.core.indexes.api import CategoricalIndex, Index, MultiIndex
+from pandas.core.groupby import (
+ base,
+ numba_,
+ ops,
+)
+from pandas.core.indexes.api import (
+ CategoricalIndex,
+ Index,
+ MultiIndex,
+)
from pandas.core.series import Series
from pandas.core.sorting import get_group_index_sorter
from pandas.core.util.numba_ import NUMBA_FUNC_CACHE
diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py
index 6a789bc26cabc..89becb880c519 100644
--- a/pandas/core/groupby/grouper.py
+++ b/pandas/core/groupby/grouper.py
@@ -4,12 +4,22 @@
"""
from __future__ import annotations
-from typing import Dict, Hashable, List, Optional, Set, Tuple
+from typing import (
+ Dict,
+ Hashable,
+ List,
+ Optional,
+ Set,
+ Tuple,
+)
import warnings
import numpy as np
-from pandas._typing import FrameOrSeries, final
+from pandas._typing import (
+ FrameOrSeries,
+ final,
+)
from pandas.errors import InvalidIndexError
from pandas.util._decorators import cache_readonly
@@ -22,12 +32,22 @@
)
import pandas.core.algorithms as algorithms
-from pandas.core.arrays import Categorical, ExtensionArray
+from pandas.core.arrays import (
+ Categorical,
+ ExtensionArray,
+)
import pandas.core.common as com
from pandas.core.frame import DataFrame
from pandas.core.groupby import ops
-from pandas.core.groupby.categorical import recode_for_groupby, recode_from_groupby
-from pandas.core.indexes.api import CategoricalIndex, Index, MultiIndex
+from pandas.core.groupby.categorical import (
+ recode_for_groupby,
+ recode_from_groupby,
+)
+from pandas.core.indexes.api import (
+ CategoricalIndex,
+ Index,
+ MultiIndex,
+)
from pandas.core.series import Series
from pandas.io.formats.printing import pprint_thing
diff --git a/pandas/core/groupby/numba_.py b/pandas/core/groupby/numba_.py
index 5c983985628ad..3ba70baec1561 100644
--- a/pandas/core/groupby/numba_.py
+++ b/pandas/core/groupby/numba_.py
@@ -1,6 +1,12 @@
"""Common utilities for Numba operations with groupby ops"""
import inspect
-from typing import Any, Callable, Dict, Optional, Tuple
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ Optional,
+ Tuple,
+)
import numpy as np
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 1b1406fe9cd0f..00cb65fff3803 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -22,10 +22,20 @@
import numpy as np
-from pandas._libs import NaT, iNaT, lib
+from pandas._libs import (
+ NaT,
+ iNaT,
+ lib,
+)
import pandas._libs.groupby as libgroupby
import pandas._libs.reduction as libreduction
-from pandas._typing import ArrayLike, F, FrameOrSeries, Shape, final
+from pandas._typing import (
+ ArrayLike,
+ F,
+ FrameOrSeries,
+ Shape,
+ final,
+)
from pandas.errors import AbstractMethodError
from pandas.util._decorators import cache_readonly
@@ -55,15 +65,25 @@
needs_i8_conversion,
)
from pandas.core.dtypes.generic import ABCCategoricalIndex
-from pandas.core.dtypes.missing import isna, maybe_fill
+from pandas.core.dtypes.missing import (
+ isna,
+ maybe_fill,
+)
import pandas.core.algorithms as algorithms
from pandas.core.base import SelectionMixin
import pandas.core.common as com
from pandas.core.frame import DataFrame
from pandas.core.generic import NDFrame
-from pandas.core.groupby import base, grouper
-from pandas.core.indexes.api import Index, MultiIndex, ensure_index
+from pandas.core.groupby import (
+ base,
+ grouper,
+)
+from pandas.core.indexes.api import (
+ Index,
+ MultiIndex,
+ ensure_index,
+)
from pandas.core.series import Series
from pandas.core.sorting import (
compress_group_index,
diff --git a/pandas/core/indexers.py b/pandas/core/indexers.py
index c7011b4339fe7..0649cc3efc153 100644
--- a/pandas/core/indexers.py
+++ b/pandas/core/indexers.py
@@ -8,7 +8,11 @@
import numpy as np
-from pandas._typing import Any, AnyArrayLike, ArrayLike
+from pandas._typing import (
+ Any,
+ AnyArrayLike,
+ ArrayLike,
+)
from pandas.core.dtypes.common import (
is_array_like,
@@ -18,7 +22,10 @@
is_integer_dtype,
is_list_like,
)
-from pandas.core.dtypes.generic import ABCIndex, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCIndex,
+ ABCSeries,
+)
if TYPE_CHECKING:
from pandas.core.frame import DataFrame
diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py
index 430d3ea8f5e33..017f58bff03e9 100644
--- a/pandas/core/indexes/accessors.py
+++ b/pandas/core/indexes/accessors.py
@@ -19,9 +19,19 @@
)
from pandas.core.dtypes.generic import ABCSeries
-from pandas.core.accessor import PandasDelegate, delegate_names
-from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray
-from pandas.core.base import NoNewAttributesMixin, PandasObject
+from pandas.core.accessor import (
+ PandasDelegate,
+ delegate_names,
+)
+from pandas.core.arrays import (
+ DatetimeArray,
+ PeriodArray,
+ TimedeltaArray,
+)
+from pandas.core.base import (
+ NoNewAttributesMixin,
+ PandasObject,
+)
from pandas.core.indexes.datetimes import DatetimeIndex
from pandas.core.indexes.timedeltas import TimedeltaIndex
diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py
index d4f22e482af84..5656323b82fb7 100644
--- a/pandas/core/indexes/api.py
+++ b/pandas/core/indexes/api.py
@@ -1,7 +1,13 @@
import textwrap
-from typing import List, Set
+from typing import (
+ List,
+ Set,
+)
-from pandas._libs import NaT, lib
+from pandas._libs import (
+ NaT,
+ lib,
+)
from pandas.errors import InvalidIndexError
from pandas.core.indexes.base import (
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index f12a4fd382e7a..71095b8f4113a 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -25,19 +25,40 @@
import numpy as np
-from pandas._libs import algos as libalgos, index as libindex, lib
+from pandas._libs import (
+ algos as libalgos,
+ index as libindex,
+ lib,
+)
import pandas._libs.join as libjoin
-from pandas._libs.lib import is_datetime_array, no_default
+from pandas._libs.lib import (
+ is_datetime_array,
+ no_default,
+)
from pandas._libs.tslibs import (
IncompatibleFrequency,
OutOfBoundsDatetime,
Timestamp,
tz_compare,
)
-from pandas._typing import AnyArrayLike, ArrayLike, Dtype, DtypeObj, Shape, final
+from pandas._typing import (
+ AnyArrayLike,
+ ArrayLike,
+ Dtype,
+ DtypeObj,
+ Shape,
+ final,
+)
from pandas.compat.numpy import function as nv
-from pandas.errors import DuplicateLabelError, InvalidIndexError
-from pandas.util._decorators import Appender, cache_readonly, doc
+from pandas.errors import (
+ DuplicateLabelError,
+ InvalidIndexError,
+)
+from pandas.util._decorators import (
+ Appender,
+ cache_readonly,
+ doc,
+)
from pandas.core.dtypes.cast import (
can_hold_element,
@@ -88,26 +109,45 @@
ABCTimedeltaIndex,
)
from pandas.core.dtypes.inference import is_dict_like
-from pandas.core.dtypes.missing import array_equivalent, is_valid_na_for_dtype, isna
+from pandas.core.dtypes.missing import (
+ array_equivalent,
+ is_valid_na_for_dtype,
+ isna,
+)
-from pandas.core import missing, ops
+from pandas.core import (
+ missing,
+ ops,
+)
from pandas.core.accessor import CachedAccessor
import pandas.core.algorithms as algos
from pandas.core.array_algos.putmask import (
setitem_datetimelike_compat,
validate_putmask,
)
-from pandas.core.arrays import Categorical, ExtensionArray
-from pandas.core.arrays.datetimes import tz_to_dtype, validate_tz_from_dtype
+from pandas.core.arrays import (
+ Categorical,
+ ExtensionArray,
+)
+from pandas.core.arrays.datetimes import (
+ tz_to_dtype,
+ validate_tz_from_dtype,
+)
from pandas.core.arrays.sparse import SparseDtype
-from pandas.core.base import IndexOpsMixin, PandasObject
+from pandas.core.base import (
+ IndexOpsMixin,
+ PandasObject,
+)
import pandas.core.common as com
from pandas.core.construction import extract_array
from pandas.core.indexers import deprecate_ndim_indexing
from pandas.core.indexes.frozen import FrozenList
from pandas.core.ops import get_op_result_name
from pandas.core.ops.invalid import make_invalid_op
-from pandas.core.sorting import ensure_key_mapped, nargsort
+from pandas.core.sorting import (
+ ensure_key_mapped,
+ nargsort,
+)
from pandas.core.strings import StringMethods
from pandas.io.formats.printing import (
@@ -119,7 +159,13 @@
)
if TYPE_CHECKING:
- from pandas import CategoricalIndex, IntervalIndex, MultiIndex, RangeIndex, Series
+ from pandas import (
+ CategoricalIndex,
+ IntervalIndex,
+ MultiIndex,
+ RangeIndex,
+ Series,
+ )
from pandas.core.indexes.datetimelike import DatetimeIndexOpsMixin
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index 7e6d7d911b065..13c53dfafed4d 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -1,4 +1,9 @@
-from typing import Any, Hashable, List, Optional
+from typing import (
+ Any,
+ Hashable,
+ List,
+ Optional,
+)
import warnings
import numpy as np
@@ -7,22 +12,42 @@
from pandas._libs import index as libindex
from pandas._libs.lib import no_default
-from pandas._typing import ArrayLike, Dtype
-from pandas.util._decorators import Appender, doc
+from pandas._typing import (
+ ArrayLike,
+ Dtype,
+)
+from pandas.util._decorators import (
+ Appender,
+ doc,
+)
from pandas.core.dtypes.common import (
ensure_platform_int,
is_categorical_dtype,
is_scalar,
)
-from pandas.core.dtypes.missing import is_valid_na_for_dtype, isna, notna
+from pandas.core.dtypes.missing import (
+ is_valid_na_for_dtype,
+ isna,
+ notna,
+)
from pandas.core import accessor
-from pandas.core.arrays.categorical import Categorical, contains
+from pandas.core.arrays.categorical import (
+ Categorical,
+ contains,
+)
from pandas.core.construction import extract_array
import pandas.core.indexes.base as ibase
-from pandas.core.indexes.base import Index, _index_shared_docs, maybe_extract_name
-from pandas.core.indexes.extension import NDArrayBackedExtensionIndex, inherit_names
+from pandas.core.indexes.base import (
+ Index,
+ _index_shared_docs,
+ maybe_extract_name,
+)
+from pandas.core.indexes.extension import (
+ NDArrayBackedExtensionIndex,
+ inherit_names,
+)
_index_doc_kwargs = dict(ibase._index_doc_kwargs)
_index_doc_kwargs.update({"target_klass": "CategoricalIndex"})
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index 2e6519a3b73ad..b2c67ae2f0a00 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -17,11 +17,25 @@
import numpy as np
-from pandas._libs import NaT, Timedelta, iNaT, join as libjoin, lib
-from pandas._libs.tslibs import BaseOffset, Resolution, Tick
+from pandas._libs import (
+ NaT,
+ Timedelta,
+ iNaT,
+ join as libjoin,
+ lib,
+)
+from pandas._libs.tslibs import (
+ BaseOffset,
+ Resolution,
+ Tick,
+)
from pandas._typing import Callable
from pandas.compat.numpy import function as nv
-from pandas.util._decorators import Appender, cache_readonly, doc
+from pandas.util._decorators import (
+ Appender,
+ cache_readonly,
+ doc,
+)
from pandas.core.dtypes.common import (
is_bool_dtype,
@@ -35,11 +49,18 @@
from pandas.core.dtypes.concat import concat_compat
from pandas.core.dtypes.generic import ABCSeries
-from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray
+from pandas.core.arrays import (
+ DatetimeArray,
+ PeriodArray,
+ TimedeltaArray,
+)
from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin
import pandas.core.common as com
import pandas.core.indexes.base as ibase
-from pandas.core.indexes.base import Index, _index_shared_docs
+from pandas.core.indexes.base import (
+ Index,
+ _index_shared_docs,
+)
from pandas.core.indexes.extension import (
NDArrayBackedExtensionIndex,
inherit_names,
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index 2ef703de85dbe..9ea43d083f5b3 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -1,13 +1,29 @@
from __future__ import annotations
-from datetime import date, datetime, time, timedelta, tzinfo
+from datetime import (
+ date,
+ datetime,
+ time,
+ timedelta,
+ tzinfo,
+)
import operator
-from typing import TYPE_CHECKING, Optional, Tuple
+from typing import (
+ TYPE_CHECKING,
+ Optional,
+ Tuple,
+)
import warnings
import numpy as np
-from pandas._libs import NaT, Period, Timestamp, index as libindex, lib
+from pandas._libs import (
+ NaT,
+ Period,
+ Timestamp,
+ index as libindex,
+ lib,
+)
from pandas._libs.tslibs import (
Resolution,
ints_to_pydatetime,
@@ -16,9 +32,15 @@
to_offset,
)
from pandas._libs.tslibs.offsets import prefix_mapping
-from pandas._typing import Dtype, DtypeObj
+from pandas._typing import (
+ Dtype,
+ DtypeObj,
+)
from pandas.errors import InvalidIndexError
-from pandas.util._decorators import cache_readonly, doc
+from pandas.util._decorators import (
+ cache_readonly,
+ doc,
+)
from pandas.core.dtypes.common import (
DT64NS_DTYPE,
@@ -28,15 +50,27 @@
)
from pandas.core.dtypes.missing import is_valid_na_for_dtype
-from pandas.core.arrays.datetimes import DatetimeArray, tz_to_dtype
+from pandas.core.arrays.datetimes import (
+ DatetimeArray,
+ tz_to_dtype,
+)
import pandas.core.common as com
-from pandas.core.indexes.base import Index, get_unanimous_names, maybe_extract_name
+from pandas.core.indexes.base import (
+ Index,
+ get_unanimous_names,
+ maybe_extract_name,
+)
from pandas.core.indexes.datetimelike import DatetimeTimedeltaMixin
from pandas.core.indexes.extension import inherit_names
from pandas.core.tools.times import to_time
if TYPE_CHECKING:
- from pandas import DataFrame, Float64Index, PeriodIndex, TimedeltaIndex
+ from pandas import (
+ DataFrame,
+ Float64Index,
+ PeriodIndex,
+ TimedeltaIndex,
+ )
def _new_DatetimeIndex(cls, d):
diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py
index a0e783a74df3c..4150ec745bd2e 100644
--- a/pandas/core/indexes/extension.py
+++ b/pandas/core/indexes/extension.py
@@ -1,16 +1,29 @@
"""
Shared methods for Index subclasses backed by ExtensionArray.
"""
-from typing import List, TypeVar
+from typing import (
+ List,
+ TypeVar,
+)
import numpy as np
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
-from pandas.util._decorators import cache_readonly, doc
-
-from pandas.core.dtypes.common import is_dtype_equal, is_object_dtype, pandas_dtype
-from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
+from pandas.util._decorators import (
+ cache_readonly,
+ doc,
+)
+
+from pandas.core.dtypes.common import (
+ is_dtype_equal,
+ is_object_dtype,
+ pandas_dtype,
+)
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCSeries,
+)
from pandas.core.arrays import ExtensionArray
from pandas.core.arrays._mixins import NDArrayBackedExtensionArray
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index 70adcd841a57d..c2fabfc332b23 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -2,20 +2,47 @@
from __future__ import annotations
from functools import wraps
-from operator import le, lt
+from operator import (
+ le,
+ lt,
+)
import textwrap
-from typing import TYPE_CHECKING, Any, Hashable, List, Optional, Tuple, Union, cast
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Hashable,
+ List,
+ Optional,
+ Tuple,
+ Union,
+ cast,
+)
import numpy as np
from pandas._config import get_option
from pandas._libs import lib
-from pandas._libs.interval import Interval, IntervalMixin, IntervalTree
-from pandas._libs.tslibs import BaseOffset, Timedelta, Timestamp, to_offset
-from pandas._typing import Dtype, DtypeObj
+from pandas._libs.interval import (
+ Interval,
+ IntervalMixin,
+ IntervalTree,
+)
+from pandas._libs.tslibs import (
+ BaseOffset,
+ Timedelta,
+ Timestamp,
+ to_offset,
+)
+from pandas._typing import (
+ Dtype,
+ DtypeObj,
+)
from pandas.errors import InvalidIndexError
-from pandas.util._decorators import Appender, cache_readonly
+from pandas.util._decorators import (
+ Appender,
+ cache_readonly,
+)
from pandas.util._exceptions import rewrite_exception
from pandas.core.dtypes.cast import (
@@ -42,9 +69,15 @@
)
from pandas.core.dtypes.dtypes import IntervalDtype
-from pandas.core.algorithms import take_nd, unique
+from pandas.core.algorithms import (
+ take_nd,
+ unique,
+)
from pandas.core.array_algos.putmask import validate_putmask
-from pandas.core.arrays.interval import IntervalArray, _interval_shared_docs
+from pandas.core.arrays.interval import (
+ IntervalArray,
+ _interval_shared_docs,
+)
import pandas.core.common as com
from pandas.core.indexers import is_valid_positional_slice
import pandas.core.indexes.base as ibase
@@ -55,10 +88,19 @@
ensure_index,
maybe_extract_name,
)
-from pandas.core.indexes.datetimes import DatetimeIndex, date_range
-from pandas.core.indexes.extension import ExtensionIndex, inherit_names
+from pandas.core.indexes.datetimes import (
+ DatetimeIndex,
+ date_range,
+)
+from pandas.core.indexes.extension import (
+ ExtensionIndex,
+ inherit_names,
+)
from pandas.core.indexes.multi import MultiIndex
-from pandas.core.indexes.timedeltas import TimedeltaIndex, timedelta_range
+from pandas.core.indexes.timedeltas import (
+ TimedeltaIndex,
+ timedelta_range,
+)
from pandas.core.ops import get_op_result_name
if TYPE_CHECKING:
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 1fdffcf8e5980..7ef81b0947a22 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -21,12 +21,29 @@
from pandas._config import get_option
-from pandas._libs import algos as libalgos, index as libindex, lib
+from pandas._libs import (
+ algos as libalgos,
+ index as libindex,
+ lib,
+)
from pandas._libs.hashtable import duplicated_int64
-from pandas._typing import AnyArrayLike, DtypeObj, Scalar, Shape
+from pandas._typing import (
+ AnyArrayLike,
+ DtypeObj,
+ Scalar,
+ Shape,
+)
from pandas.compat.numpy import function as nv
-from pandas.errors import InvalidIndexError, PerformanceWarning, UnsortedIndexError
-from pandas.util._decorators import Appender, cache_readonly, doc
+from pandas.errors import (
+ InvalidIndexError,
+ PerformanceWarning,
+ UnsortedIndexError,
+)
+from pandas.util._decorators import (
+ Appender,
+ cache_readonly,
+ doc,
+)
from pandas.core.dtypes.cast import coerce_indexer_dtype
from pandas.core.dtypes.common import (
@@ -42,8 +59,15 @@
pandas_dtype,
)
from pandas.core.dtypes.dtypes import ExtensionDtype
-from pandas.core.dtypes.generic import ABCDataFrame, ABCDatetimeIndex, ABCTimedeltaIndex
-from pandas.core.dtypes.missing import array_equivalent, isna
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCDatetimeIndex,
+ ABCTimedeltaIndex,
+)
+from pandas.core.dtypes.missing import (
+ array_equivalent,
+ isna,
+)
import pandas.core.algorithms as algos
from pandas.core.arrays import Categorical
@@ -72,7 +96,10 @@
)
if TYPE_CHECKING:
- from pandas import CategoricalIndex, Series
+ from pandas import (
+ CategoricalIndex,
+ Series,
+ )
_index_doc_kwargs = dict(ibase._index_doc_kwargs)
_index_doc_kwargs.update(
diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py
index bb4a4f62e59cf..96c8c1ab9b69c 100644
--- a/pandas/core/indexes/numeric.py
+++ b/pandas/core/indexes/numeric.py
@@ -1,10 +1,19 @@
-from typing import Hashable, Optional
+from typing import (
+ Hashable,
+ Optional,
+)
import warnings
import numpy as np
-from pandas._libs import index as libindex, lib
-from pandas._typing import Dtype, DtypeObj
+from pandas._libs import (
+ index as libindex,
+ lib,
+)
+from pandas._typing import (
+ Dtype,
+ DtypeObj,
+)
from pandas.util._decorators import doc
from pandas.core.dtypes.cast import astype_nansafe
@@ -24,7 +33,10 @@
from pandas.core.dtypes.generic import ABCSeries
import pandas.core.common as com
-from pandas.core.indexes.base import Index, maybe_extract_name
+from pandas.core.indexes.base import (
+ Index,
+ maybe_extract_name,
+)
_num_index_shared_docs = {}
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py
index 9664f41362c8a..0c5dbec2094e5 100644
--- a/pandas/core/indexes/period.py
+++ b/pandas/core/indexes/period.py
@@ -1,15 +1,35 @@
from __future__ import annotations
-from datetime import datetime, timedelta
-from typing import Any, Optional
+from datetime import (
+ datetime,
+ timedelta,
+)
+from typing import (
+ Any,
+ Optional,
+)
import warnings
import numpy as np
-from pandas._libs import index as libindex, lib
-from pandas._libs.tslibs import BaseOffset, Period, Resolution, Tick
-from pandas._libs.tslibs.parsing import DateParseError, parse_time_string
-from pandas._typing import Dtype, DtypeObj
+from pandas._libs import (
+ index as libindex,
+ lib,
+)
+from pandas._libs.tslibs import (
+ BaseOffset,
+ Period,
+ Resolution,
+ Tick,
+)
+from pandas._libs.tslibs.parsing import (
+ DateParseError,
+ parse_time_string,
+)
+from pandas._typing import (
+ Dtype,
+ DtypeObj,
+)
from pandas.errors import InvalidIndexError
from pandas.util._decorators import doc
@@ -33,7 +53,10 @@
import pandas.core.indexes.base as ibase
from pandas.core.indexes.base import maybe_extract_name
from pandas.core.indexes.datetimelike import DatetimeIndexOpsMixin
-from pandas.core.indexes.datetimes import DatetimeIndex, Index
+from pandas.core.indexes.datetimes import (
+ DatetimeIndex,
+ Index,
+)
from pandas.core.indexes.extension import inherit_names
from pandas.core.indexes.numeric import Int64Index
diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py
index ee0b49aac3f79..bd9a92a657991 100644
--- a/pandas/core/indexes/range.py
+++ b/pandas/core/indexes/range.py
@@ -3,7 +3,14 @@
from datetime import timedelta
import operator
from sys import getsizeof
-from typing import TYPE_CHECKING, Any, Hashable, List, Optional, Tuple
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Hashable,
+ List,
+ Optional,
+ Tuple,
+)
import warnings
import numpy as np
@@ -12,7 +19,10 @@
from pandas._libs.lib import no_default
from pandas._typing import Dtype
from pandas.compat.numpy import function as nv
-from pandas.util._decorators import cache_readonly, doc
+from pandas.util._decorators import (
+ cache_readonly,
+ doc,
+)
from pandas.util._exceptions import rewrite_exception
from pandas.core.dtypes.common import (
@@ -31,7 +41,10 @@
from pandas.core.construction import extract_array
import pandas.core.indexes.base as ibase
from pandas.core.indexes.base import maybe_extract_name
-from pandas.core.indexes.numeric import Float64Index, Int64Index
+from pandas.core.indexes.numeric import (
+ Float64Index,
+ Int64Index,
+)
from pandas.core.ops.common import unpack_zerodim_and_defer
if TYPE_CHECKING:
diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py
index 79eb8de083958..a23dd10bc3c0e 100644
--- a/pandas/core/indexes/timedeltas.py
+++ b/pandas/core/indexes/timedeltas.py
@@ -1,16 +1,32 @@
""" implement the TimedeltaIndex """
-from pandas._libs import index as libindex, lib
-from pandas._libs.tslibs import Timedelta, to_offset
-from pandas._typing import DtypeObj, Optional
+from pandas._libs import (
+ index as libindex,
+ lib,
+)
+from pandas._libs.tslibs import (
+ Timedelta,
+ to_offset,
+)
+from pandas._typing import (
+ DtypeObj,
+ Optional,
+)
from pandas.errors import InvalidIndexError
-from pandas.core.dtypes.common import TD64NS_DTYPE, is_scalar, is_timedelta64_dtype
+from pandas.core.dtypes.common import (
+ TD64NS_DTYPE,
+ is_scalar,
+ is_timedelta64_dtype,
+)
from pandas.core.arrays import datetimelike as dtl
from pandas.core.arrays.timedeltas import TimedeltaArray
import pandas.core.common as com
-from pandas.core.indexes.base import Index, maybe_extract_name
+from pandas.core.indexes.base import (
+ Index,
+ maybe_extract_name,
+)
from pandas.core.indexes.datetimelike import DatetimeTimedeltaMixin
from pandas.core.indexes.extension import inherit_names
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index cc7c5f666feda..93f63c23ac2d1 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -1,7 +1,15 @@
from __future__ import annotations
from contextlib import suppress
-from typing import TYPE_CHECKING, Any, Hashable, List, Sequence, Tuple, Union
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Hashable,
+ List,
+ Sequence,
+ Tuple,
+ Union,
+)
import warnings
import numpy as np
@@ -10,7 +18,10 @@
from pandas._libs.indexing import NDFrameIndexerBase
from pandas._libs.lib import item_from_zerodim
-from pandas.errors import AbstractMethodError, InvalidIndexError
+from pandas.errors import (
+ AbstractMethodError,
+ InvalidIndexError,
+)
from pandas.util._decorators import doc
from pandas.core.dtypes.common import (
@@ -26,8 +37,15 @@
is_sequence,
)
from pandas.core.dtypes.concat import concat_compat
-from pandas.core.dtypes.generic import ABCDataFrame, ABCMultiIndex, ABCSeries
-from pandas.core.dtypes.missing import infer_fill_value, isna
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCMultiIndex,
+ ABCSeries,
+)
+from pandas.core.dtypes.missing import (
+ infer_fill_value,
+ isna,
+)
import pandas.core.common as com
from pandas.core.construction import array as pd_array
@@ -40,7 +58,10 @@
from pandas.core.indexes.api import Index
if TYPE_CHECKING:
- from pandas import DataFrame, Series
+ from pandas import (
+ DataFrame,
+ Series,
+ )
# "null slice"
_NS = slice(None, None)
diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py
index 2c2f32f7239d4..0e52ebf69137c 100644
--- a/pandas/core/internals/array_manager.py
+++ b/pandas/core/internals/array_manager.py
@@ -3,31 +3,59 @@
"""
from __future__ import annotations
-from typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple, TypeVar, Union
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ List,
+ Optional,
+ Tuple,
+ TypeVar,
+ Union,
+)
import numpy as np
from pandas._libs import lib
-from pandas._typing import ArrayLike, DtypeObj, Hashable
+from pandas._typing import (
+ ArrayLike,
+ DtypeObj,
+ Hashable,
+)
from pandas.util._validators import validate_bool_kwarg
-from pandas.core.dtypes.cast import find_common_type, infer_dtype_from_scalar
+from pandas.core.dtypes.cast import (
+ find_common_type,
+ infer_dtype_from_scalar,
+)
from pandas.core.dtypes.common import (
is_bool_dtype,
is_dtype_equal,
is_extension_array_dtype,
is_numeric_dtype,
)
-from pandas.core.dtypes.dtypes import ExtensionDtype, PandasDtype
-from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
-from pandas.core.dtypes.missing import array_equals, isna
+from pandas.core.dtypes.dtypes import (
+ ExtensionDtype,
+ PandasDtype,
+)
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCSeries,
+)
+from pandas.core.dtypes.missing import (
+ array_equals,
+ isna,
+)
import pandas.core.algorithms as algos
from pandas.core.arrays import ExtensionArray
from pandas.core.arrays.sparse import SparseDtype
from pandas.core.construction import extract_array
from pandas.core.indexers import maybe_convert_indices
-from pandas.core.indexes.api import Index, ensure_index
+from pandas.core.indexes.api import (
+ Index,
+ ensure_index,
+)
from pandas.core.internals.base import DataManager
from pandas.core.internals.blocks import make_block
diff --git a/pandas/core/internals/base.py b/pandas/core/internals/base.py
index 585a2dccf3acf..2ce91134f61d6 100644
--- a/pandas/core/internals/base.py
+++ b/pandas/core/internals/base.py
@@ -2,12 +2,18 @@
Base class for the internal managers. Both BlockManager and ArrayManager
inherit from this class.
"""
-from typing import List, TypeVar
+from typing import (
+ List,
+ TypeVar,
+)
from pandas.errors import AbstractMethodError
from pandas.core.base import PandasObject
-from pandas.core.indexes.api import Index, ensure_index
+from pandas.core.indexes.api import (
+ Index,
+ ensure_index,
+)
T = TypeVar("T", bound="DataManager")
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 06bf2e5d7b18e..90052347a1c85 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -2,7 +2,16 @@
import inspect
import re
-from typing import TYPE_CHECKING, Any, Callable, List, Optional, Type, Union, cast
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ List,
+ Optional,
+ Type,
+ Union,
+ cast,
+)
import numpy as np
@@ -18,7 +27,12 @@
)
from pandas._libs.internals import BlockPlacement
from pandas._libs.tslibs import conversion
-from pandas._typing import ArrayLike, Dtype, DtypeObj, Shape
+from pandas._typing import (
+ ArrayLike,
+ Dtype,
+ DtypeObj,
+ Shape,
+)
from pandas.util._validators import validate_bool_kwarg
from pandas.core.dtypes.cast import (
@@ -43,9 +57,21 @@
is_sparse,
pandas_dtype,
)
-from pandas.core.dtypes.dtypes import CategoricalDtype, ExtensionDtype, PandasDtype
-from pandas.core.dtypes.generic import ABCDataFrame, ABCIndex, ABCPandasArray, ABCSeries
-from pandas.core.dtypes.missing import is_valid_na_for_dtype, isna
+from pandas.core.dtypes.dtypes import (
+ CategoricalDtype,
+ ExtensionDtype,
+ PandasDtype,
+)
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCIndex,
+ ABCPandasArray,
+ ABCSeries,
+)
+from pandas.core.dtypes.missing import (
+ is_valid_na_for_dtype,
+ isna,
+)
import pandas.core.algorithms as algos
from pandas.core.array_algos.putmask import (
@@ -82,7 +108,10 @@
import pandas.core.missing as missing
if TYPE_CHECKING:
- from pandas import Float64Index, Index
+ from pandas import (
+ Float64Index,
+ Index,
+ )
from pandas.core.arrays._mixins import NDArrayBackedExtensionArray
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py
index 01d8cde3e9af2..d2ee54d46b4f0 100644
--- a/pandas/core/internals/concat.py
+++ b/pandas/core/internals/concat.py
@@ -2,15 +2,28 @@
import copy
import itertools
-from typing import TYPE_CHECKING, Dict, List, Sequence
+from typing import (
+ TYPE_CHECKING,
+ Dict,
+ List,
+ Sequence,
+)
import numpy as np
from pandas._libs import internals as libinternals
-from pandas._typing import ArrayLike, DtypeObj, Manager, Shape
+from pandas._typing import (
+ ArrayLike,
+ DtypeObj,
+ Manager,
+ Shape,
+)
from pandas.util._decorators import cache_readonly
-from pandas.core.dtypes.cast import ensure_dtype_can_hold_na, find_common_type
+from pandas.core.dtypes.cast import (
+ ensure_dtype_can_hold_na,
+ find_common_type,
+)
from pandas.core.dtypes.common import (
is_categorical_dtype,
is_datetime64tz_dtype,
@@ -19,10 +32,16 @@
is_sparse,
)
from pandas.core.dtypes.concat import concat_compat
-from pandas.core.dtypes.missing import is_valid_na_for_dtype, isna_all
+from pandas.core.dtypes.missing import (
+ is_valid_na_for_dtype,
+ isna_all,
+)
import pandas.core.algorithms as algos
-from pandas.core.arrays import DatetimeArray, ExtensionArray
+from pandas.core.arrays import (
+ DatetimeArray,
+ ExtensionArray,
+)
from pandas.core.internals.array_manager import ArrayManager
from pandas.core.internals.blocks import make_block
from pandas.core.internals.managers import BlockManager
diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py
index 878a5c9aafe5d..2cfe613b7072b 100644
--- a/pandas/core/internals/construction.py
+++ b/pandas/core/internals/construction.py
@@ -21,7 +21,12 @@
import numpy.ma as ma
from pandas._libs import lib
-from pandas._typing import Axis, DtypeObj, Manager, Scalar
+from pandas._typing import (
+ Axis,
+ DtypeObj,
+ Manager,
+ Scalar,
+)
from pandas.core.dtypes.cast import (
construct_1d_arraylike_from_scalar,
@@ -49,9 +54,15 @@
ABCTimedeltaIndex,
)
-from pandas.core import algorithms, common as com
+from pandas.core import (
+ algorithms,
+ common as com,
+)
from pandas.core.arrays import Categorical
-from pandas.core.construction import extract_array, sanitize_array
+from pandas.core.construction import (
+ extract_array,
+ sanitize_array,
+)
from pandas.core.indexes import base as ibase
from pandas.core.indexes.api import (
Index,
@@ -154,7 +165,10 @@ def mgr_to_mgr(mgr, typ: str):
Convert to specific type of Manager. Does not copy if the type is already
correct. Does not guarantee a copy otherwise.
"""
- from pandas.core.internals import ArrayManager, BlockManager
+ from pandas.core.internals import (
+ ArrayManager,
+ BlockManager,
+ )
new_mgr: Manager
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index ccac2696b34c5..b3f0466f236b6 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -19,12 +19,23 @@
import numpy as np
-from pandas._libs import internals as libinternals, lib
-from pandas._typing import ArrayLike, Dtype, DtypeObj, Shape
+from pandas._libs import (
+ internals as libinternals,
+ lib,
+)
+from pandas._typing import (
+ ArrayLike,
+ Dtype,
+ DtypeObj,
+ Shape,
+)
from pandas.errors import PerformanceWarning
from pandas.util._validators import validate_bool_kwarg
-from pandas.core.dtypes.cast import find_common_type, infer_dtype_from_scalar
+from pandas.core.dtypes.cast import (
+ find_common_type,
+ infer_dtype_from_scalar,
+)
from pandas.core.dtypes.common import (
DT64NS_DTYPE,
is_dtype_equal,
@@ -32,14 +43,25 @@
is_list_like,
)
from pandas.core.dtypes.dtypes import ExtensionDtype
-from pandas.core.dtypes.generic import ABCDataFrame, ABCPandasArray, ABCSeries
-from pandas.core.dtypes.missing import array_equals, isna
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCPandasArray,
+ ABCSeries,
+)
+from pandas.core.dtypes.missing import (
+ array_equals,
+ isna,
+)
import pandas.core.algorithms as algos
from pandas.core.arrays.sparse import SparseDtype
from pandas.core.construction import extract_array
from pandas.core.indexers import maybe_convert_indices
-from pandas.core.indexes.api import Float64Index, Index, ensure_index
+from pandas.core.indexes.api import (
+ Float64Index,
+ Index,
+ ensure_index,
+)
from pandas.core.internals.base import DataManager
from pandas.core.internals.blocks import (
Block,
@@ -52,7 +74,10 @@
make_block,
safe_reshape,
)
-from pandas.core.internals.ops import blockwise_all, operate_blockwise
+from pandas.core.internals.ops import (
+ blockwise_all,
+ operate_blockwise,
+)
# TODO: flexible with index=None and/or items=None
diff --git a/pandas/core/internals/ops.py b/pandas/core/internals/ops.py
index 8250db3f5d888..70d4f3b91c245 100644
--- a/pandas/core/internals/ops.py
+++ b/pandas/core/internals/ops.py
@@ -1,7 +1,12 @@
from __future__ import annotations
from collections import namedtuple
-from typing import TYPE_CHECKING, Iterator, List, Tuple
+from typing import (
+ TYPE_CHECKING,
+ Iterator,
+ List,
+ Tuple,
+)
import numpy as np
diff --git a/pandas/core/missing.py b/pandas/core/missing.py
index d0ad38235d7e5..9ae5f7d1b7497 100644
--- a/pandas/core/missing.py
+++ b/pandas/core/missing.py
@@ -4,12 +4,26 @@
from __future__ import annotations
from functools import partial
-from typing import TYPE_CHECKING, Any, List, Optional, Set, Union
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ List,
+ Optional,
+ Set,
+ Union,
+)
import numpy as np
-from pandas._libs import algos, lib
-from pandas._typing import ArrayLike, Axis, DtypeObj
+from pandas._libs import (
+ algos,
+ lib,
+)
+from pandas._typing import (
+ ArrayLike,
+ Axis,
+ DtypeObj,
+)
from pandas.compat._optional import import_optional_dependency
from pandas.core.dtypes.cast import infer_dtype_from
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index 4af1084033ce2..24e75a2bbeff2 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -1,15 +1,32 @@
import functools
import itertools
import operator
-from typing import Any, Optional, Tuple, Union, cast
+from typing import (
+ Any,
+ Optional,
+ Tuple,
+ Union,
+ cast,
+)
import warnings
import numpy as np
from pandas._config import get_option
-from pandas._libs import NaT, Timedelta, iNaT, lib
-from pandas._typing import ArrayLike, Dtype, DtypeObj, F, Scalar
+from pandas._libs import (
+ NaT,
+ Timedelta,
+ iNaT,
+ lib,
+)
+from pandas._typing import (
+ ArrayLike,
+ Dtype,
+ DtypeObj,
+ F,
+ Scalar,
+)
from pandas.compat._optional import import_optional_dependency
from pandas.core.dtypes.common import (
@@ -30,7 +47,11 @@
pandas_dtype,
)
from pandas.core.dtypes.dtypes import PeriodDtype
-from pandas.core.dtypes.missing import isna, na_value_for_dtype, notna
+from pandas.core.dtypes.missing import (
+ isna,
+ na_value_for_dtype,
+ notna,
+)
from pandas.core.construction import extract_array
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py
index 11ce2a1a3b8a3..8ace64fedacb9 100644
--- a/pandas/core/ops/__init__.py
+++ b/pandas/core/ops/__init__.py
@@ -6,7 +6,11 @@
from __future__ import annotations
import operator
-from typing import TYPE_CHECKING, Optional, Set
+from typing import (
+ TYPE_CHECKING,
+ Optional,
+ Set,
+)
import warnings
import numpy as np
@@ -15,8 +19,14 @@
from pandas._typing import Level
from pandas.util._decorators import Appender
-from pandas.core.dtypes.common import is_array_like, is_list_like
-from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
+from pandas.core.dtypes.common import (
+ is_array_like,
+ is_list_like,
+)
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCSeries,
+)
from pandas.core.dtypes.missing import isna
from pandas.core import algorithms
@@ -37,7 +47,11 @@
make_flex_doc,
)
from pandas.core.ops.invalid import invalid_comparison # noqa:F401
-from pandas.core.ops.mask_ops import kleene_and, kleene_or, kleene_xor # noqa: F401
+from pandas.core.ops.mask_ops import ( # noqa: F401
+ kleene_and,
+ kleene_or,
+ kleene_xor,
+)
from pandas.core.ops.methods import add_flex_arithmetic_methods # noqa:F401
from pandas.core.ops.roperator import ( # noqa:F401
radd,
@@ -55,7 +69,10 @@
)
if TYPE_CHECKING:
- from pandas import DataFrame, Series
+ from pandas import (
+ DataFrame,
+ Series,
+ )
# -----------------------------------------------------------------------------
# constants
diff --git a/pandas/core/ops/array_ops.py b/pandas/core/ops/array_ops.py
index 857840cf9d8b9..10807dffb026b 100644
--- a/pandas/core/ops/array_ops.py
+++ b/pandas/core/ops/array_ops.py
@@ -10,8 +10,16 @@
import numpy as np
-from pandas._libs import Timedelta, Timestamp, lib, ops as libops
-from pandas._typing import ArrayLike, Shape
+from pandas._libs import (
+ Timedelta,
+ Timestamp,
+ lib,
+ ops as libops,
+)
+from pandas._typing import (
+ ArrayLike,
+ Shape,
+)
from pandas.core.dtypes.cast import (
construct_1d_object_array_from_listlike,
@@ -27,8 +35,15 @@
is_object_dtype,
is_scalar,
)
-from pandas.core.dtypes.generic import ABCExtensionArray, ABCIndex, ABCSeries
-from pandas.core.dtypes.missing import isna, notna
+from pandas.core.dtypes.generic import (
+ ABCExtensionArray,
+ ABCIndex,
+ ABCSeries,
+)
+from pandas.core.dtypes.missing import (
+ isna,
+ notna,
+)
from pandas.core.construction import ensure_wrapped_if_datetimelike
from pandas.core.ops import missing
@@ -420,7 +435,10 @@ def _maybe_upcast_for_op(obj, shape: Shape):
Be careful to call this *after* determining the `name` attribute to be
attached to the result of the arithmetic operation.
"""
- from pandas.core.arrays import DatetimeArray, TimedeltaArray
+ from pandas.core.arrays import (
+ DatetimeArray,
+ TimedeltaArray,
+ )
if type(obj) is timedelta:
# GH#22390 cast up to Timedelta to rely on Timedelta
diff --git a/pandas/core/ops/common.py b/pandas/core/ops/common.py
index 25a38b3a373ae..2a76eb92120e7 100644
--- a/pandas/core/ops/common.py
+++ b/pandas/core/ops/common.py
@@ -7,7 +7,11 @@
from pandas._libs.lib import item_from_zerodim
from pandas._typing import F
-from pandas.core.dtypes.generic import ABCDataFrame, ABCIndex, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCIndex,
+ ABCSeries,
+)
def unpack_zerodim_and_defer(name: str) -> Callable[[F], F]:
diff --git a/pandas/core/ops/docstrings.py b/pandas/core/ops/docstrings.py
index 06ed321327e06..06ca6ed806f25 100644
--- a/pandas/core/ops/docstrings.py
+++ b/pandas/core/ops/docstrings.py
@@ -1,7 +1,10 @@
"""
Templating for ops docstrings
"""
-from typing import Dict, Optional
+from typing import (
+ Dict,
+ Optional,
+)
def make_flex_doc(op_name: str, typ: str) -> str:
diff --git a/pandas/core/ops/mask_ops.py b/pandas/core/ops/mask_ops.py
index 8fb81faf313d7..a9edb2d138246 100644
--- a/pandas/core/ops/mask_ops.py
+++ b/pandas/core/ops/mask_ops.py
@@ -1,11 +1,17 @@
"""
Ops for masked arrays.
"""
-from typing import Optional, Union
+from typing import (
+ Optional,
+ Union,
+)
import numpy as np
-from pandas._libs import lib, missing as libmissing
+from pandas._libs import (
+ lib,
+ missing as libmissing,
+)
def kleene_or(
diff --git a/pandas/core/ops/methods.py b/pandas/core/ops/methods.py
index 4866905d32b83..700c4a946e2b2 100644
--- a/pandas/core/ops/methods.py
+++ b/pandas/core/ops/methods.py
@@ -3,7 +3,10 @@
"""
import operator
-from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCSeries,
+)
from pandas.core.ops.roperator import (
radd,
diff --git a/pandas/core/ops/missing.py b/pandas/core/ops/missing.py
index c33cb32dcec19..20b7510c33160 100644
--- a/pandas/core/ops/missing.py
+++ b/pandas/core/ops/missing.py
@@ -25,9 +25,17 @@
import numpy as np
-from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype, is_scalar
-
-from pandas.core.ops.roperator import rdivmod, rfloordiv, rmod
+from pandas.core.dtypes.common import (
+ is_float_dtype,
+ is_integer_dtype,
+ is_scalar,
+)
+
+from pandas.core.ops.roperator import (
+ rdivmod,
+ rfloordiv,
+ rmod,
+)
def fill_zeros(result, x, y):
diff --git a/pandas/core/resample.py b/pandas/core/resample.py
index 670c2f9f6da6c..2308f9edb4328 100644
--- a/pandas/core/resample.py
+++ b/pandas/core/resample.py
@@ -3,7 +3,14 @@
import copy
from datetime import timedelta
from textwrap import dedent
-from typing import Callable, Dict, Optional, Tuple, Union, no_type_check
+from typing import (
+ Callable,
+ Dict,
+ Optional,
+ Tuple,
+ Union,
+ no_type_check,
+)
import numpy as np
@@ -16,18 +23,35 @@
Timestamp,
to_offset,
)
-from pandas._typing import T, TimedeltaConvertibleTypes, TimestampConvertibleTypes
+from pandas._typing import (
+ T,
+ TimedeltaConvertibleTypes,
+ TimestampConvertibleTypes,
+)
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
-from pandas.util._decorators import Appender, Substitution, doc
+from pandas.util._decorators import (
+ Appender,
+ Substitution,
+ doc,
+)
-from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCSeries,
+)
import pandas.core.algorithms as algos
from pandas.core.apply import ResamplerWindowApply
from pandas.core.base import DataError
-from pandas.core.generic import NDFrame, _shared_docs
-from pandas.core.groupby.base import GotItemMixin, ShallowMixin
+from pandas.core.generic import (
+ NDFrame,
+ _shared_docs,
+)
+from pandas.core.groupby.base import (
+ GotItemMixin,
+ ShallowMixin,
+)
from pandas.core.groupby.generic import SeriesGroupBy
from pandas.core.groupby.groupby import (
BaseGroupBy,
@@ -38,12 +62,29 @@
from pandas.core.groupby.grouper import Grouper
from pandas.core.groupby.ops import BinGrouper
from pandas.core.indexes.api import Index
-from pandas.core.indexes.datetimes import DatetimeIndex, date_range
-from pandas.core.indexes.period import PeriodIndex, period_range
-from pandas.core.indexes.timedeltas import TimedeltaIndex, timedelta_range
+from pandas.core.indexes.datetimes import (
+ DatetimeIndex,
+ date_range,
+)
+from pandas.core.indexes.period import (
+ PeriodIndex,
+ period_range,
+)
+from pandas.core.indexes.timedeltas import (
+ TimedeltaIndex,
+ timedelta_range,
+)
-from pandas.tseries.frequencies import is_subperiod, is_superperiod
-from pandas.tseries.offsets import DateOffset, Day, Nano, Tick
+from pandas.tseries.frequencies import (
+ is_subperiod,
+ is_superperiod,
+)
+from pandas.tseries.offsets import (
+ DateOffset,
+ Day,
+ Nano,
+ Tick,
+)
_shared_docs_kwargs: Dict[str, str] = {}
diff --git a/pandas/core/reshape/api.py b/pandas/core/reshape/api.py
index 3c76eef809c7a..58d741c2c6988 100644
--- a/pandas/core/reshape/api.py
+++ b/pandas/core/reshape/api.py
@@ -1,8 +1,23 @@
# flake8: noqa
from pandas.core.reshape.concat import concat
-from pandas.core.reshape.melt import lreshape, melt, wide_to_long
-from pandas.core.reshape.merge import merge, merge_asof, merge_ordered
-from pandas.core.reshape.pivot import crosstab, pivot, pivot_table
+from pandas.core.reshape.melt import (
+ lreshape,
+ melt,
+ wide_to_long,
+)
+from pandas.core.reshape.merge import (
+ merge,
+ merge_asof,
+ merge_ordered,
+)
+from pandas.core.reshape.pivot import (
+ crosstab,
+ pivot,
+ pivot_table,
+)
from pandas.core.reshape.reshape import get_dummies
-from pandas.core.reshape.tile import cut, qcut
+from pandas.core.reshape.tile import (
+ cut,
+ qcut,
+)
diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py
index f9bff603cec38..92fc4a2e85163 100644
--- a/pandas/core/reshape/concat.py
+++ b/pandas/core/reshape/concat.py
@@ -23,7 +23,10 @@
from pandas.util._decorators import cache_readonly
from pandas.core.dtypes.concat import concat_compat
-from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCSeries,
+)
from pandas.core.dtypes.missing import isna
from pandas.core.arrays.categorical import (
@@ -43,7 +46,10 @@
from pandas.core.internals import concatenate_block_managers
if TYPE_CHECKING:
- from pandas import DataFrame, Series
+ from pandas import (
+ DataFrame,
+ Series,
+ )
from pandas.core.generic import NDFrame
# ---------------------------------------------------------------------
diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py
index b5f8b2d02207b..80a44e8fda39b 100644
--- a/pandas/core/reshape/melt.py
+++ b/pandas/core/reshape/melt.py
@@ -1,27 +1,43 @@
from __future__ import annotations
import re
-from typing import TYPE_CHECKING, List, cast
+from typing import (
+ TYPE_CHECKING,
+ List,
+ cast,
+)
import warnings
import numpy as np
-from pandas.util._decorators import Appender, deprecate_kwarg
+from pandas.util._decorators import (
+ Appender,
+ deprecate_kwarg,
+)
-from pandas.core.dtypes.common import is_extension_array_dtype, is_list_like
+from pandas.core.dtypes.common import (
+ is_extension_array_dtype,
+ is_list_like,
+)
from pandas.core.dtypes.concat import concat_compat
from pandas.core.dtypes.missing import notna
from pandas.core.arrays import Categorical
import pandas.core.common as com
-from pandas.core.indexes.api import Index, MultiIndex
+from pandas.core.indexes.api import (
+ Index,
+ MultiIndex,
+)
from pandas.core.reshape.concat import concat
from pandas.core.reshape.util import tile_compat
from pandas.core.shared_docs import _shared_docs
from pandas.core.tools.numeric import to_numeric
if TYPE_CHECKING:
- from pandas import DataFrame, Series
+ from pandas import (
+ DataFrame,
+ Series,
+ )
@Appender(_shared_docs["melt"] % {"caller": "pd.melt(df, ", "other": "DataFrame.melt"})
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 963d071dc2768..79d018427aa33 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -8,12 +8,22 @@
from functools import partial
import hashlib
import string
-from typing import TYPE_CHECKING, Optional, Tuple, cast
+from typing import (
+ TYPE_CHECKING,
+ Optional,
+ Tuple,
+ cast,
+)
import warnings
import numpy as np
-from pandas._libs import Timedelta, hashtable as libhashtable, join as libjoin, lib
+from pandas._libs import (
+ Timedelta,
+ hashtable as libhashtable,
+ join as libjoin,
+ lib,
+)
from pandas._typing import (
ArrayLike,
FrameOrSeries,
@@ -22,7 +32,10 @@
Suffixes,
)
from pandas.errors import MergeError
-from pandas.util._decorators import Appender, Substitution
+from pandas.util._decorators import (
+ Appender,
+ Substitution,
+)
from pandas.core.dtypes.common import (
ensure_float64,
@@ -44,10 +57,20 @@
is_object_dtype,
needs_i8_conversion,
)
-from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
-from pandas.core.dtypes.missing import isna, na_value_for_dtype
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCSeries,
+)
+from pandas.core.dtypes.missing import (
+ isna,
+ na_value_for_dtype,
+)
-from pandas import Categorical, Index, MultiIndex
+from pandas import (
+ Categorical,
+ Index,
+ MultiIndex,
+)
from pandas.core import groupby
import pandas.core.algorithms as algos
import pandas.core.common as com
diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py
index 7ac98d7fcbd33..778e37bc07eb5 100644
--- a/pandas/core/reshape/pivot.py
+++ b/pandas/core/reshape/pivot.py
@@ -16,17 +16,34 @@
import numpy as np
-from pandas._typing import FrameOrSeriesUnion, IndexLabel
-from pandas.util._decorators import Appender, Substitution
+from pandas._typing import (
+ FrameOrSeriesUnion,
+ IndexLabel,
+)
+from pandas.util._decorators import (
+ Appender,
+ Substitution,
+)
from pandas.core.dtypes.cast import maybe_downcast_to_dtype
-from pandas.core.dtypes.common import is_integer_dtype, is_list_like, is_scalar
-from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
+from pandas.core.dtypes.common import (
+ is_integer_dtype,
+ is_list_like,
+ is_scalar,
+)
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCSeries,
+)
import pandas.core.common as com
from pandas.core.frame import _shared_docs
from pandas.core.groupby import Grouper
-from pandas.core.indexes.api import Index, MultiIndex, get_objs_combined_axis
+from pandas.core.indexes.api import (
+ Index,
+ MultiIndex,
+ get_objs_combined_axis,
+)
from pandas.core.reshape.concat import concat
from pandas.core.reshape.util import cartesian_product
from pandas.core.series import Series
diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py
index c335768748b26..4ccdbc089a058 100644
--- a/pandas/core/reshape/reshape.py
+++ b/pandas/core/reshape/reshape.py
@@ -1,7 +1,11 @@
from __future__ import annotations
import itertools
-from typing import List, Optional, Union
+from typing import (
+ List,
+ Optional,
+ Union,
+)
import numpy as np
@@ -28,7 +32,10 @@
from pandas.core.arrays import SparseArray
from pandas.core.arrays.categorical import factorize_from_iterable
from pandas.core.frame import DataFrame
-from pandas.core.indexes.api import Index, MultiIndex
+from pandas.core.indexes.api import (
+ Index,
+ MultiIndex,
+)
from pandas.core.series import Series
from pandas.core.sorting import (
compress_group_index,
diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py
index 969b416669023..89eba5bf41c78 100644
--- a/pandas/core/reshape/tile.py
+++ b/pandas/core/reshape/tile.py
@@ -3,7 +3,10 @@
"""
import numpy as np
-from pandas._libs import Timedelta, Timestamp
+from pandas._libs import (
+ Timedelta,
+ Timestamp,
+)
from pandas._libs.lib import infer_dtype
from pandas.core.dtypes.common import (
@@ -24,7 +27,13 @@
from pandas.core.dtypes.generic import ABCSeries
from pandas.core.dtypes.missing import isna
-from pandas import Categorical, Index, IntervalIndex, to_datetime, to_timedelta
+from pandas import (
+ Categorical,
+ Index,
+ IntervalIndex,
+ to_datetime,
+ to_timedelta,
+)
import pandas.core.algorithms as algos
import pandas.core.nanops as nanops
diff --git a/pandas/core/series.py b/pandas/core/series.py
index c98fc98db5116..0e1d2f5dafb3f 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -25,7 +25,12 @@
from pandas._config import get_option
-from pandas._libs import lib, properties, reshape, tslibs
+from pandas._libs import (
+ lib,
+ properties,
+ reshape,
+ tslibs,
+)
from pandas._libs.lib import no_default
from pandas._typing import (
AggFuncType,
@@ -41,8 +46,15 @@
)
from pandas.compat.numpy import function as nv
from pandas.errors import InvalidIndexError
-from pandas.util._decorators import Appender, Substitution, doc
-from pandas.util._validators import validate_bool_kwarg, validate_percentile
+from pandas.util._decorators import (
+ Appender,
+ Substitution,
+ doc,
+)
+from pandas.util._validators import (
+ validate_bool_kwarg,
+ validate_percentile,
+)
from pandas.core.dtypes.cast import (
convert_dtypes,
@@ -72,7 +84,14 @@
remove_na_arraylike,
)
-from pandas.core import algorithms, base, generic, missing, nanops, ops
+from pandas.core import (
+ algorithms,
+ base,
+ generic,
+ missing,
+ nanops,
+ ops,
+)
from pandas.core.accessor import CachedAccessor
from pandas.core.aggregation import transform
from pandas.core.apply import series_apply
@@ -87,7 +106,10 @@
sanitize_array,
)
from pandas.core.generic import NDFrame
-from pandas.core.indexers import deprecate_ndim_indexing, unpack_1tuple
+from pandas.core.indexers import (
+ deprecate_ndim_indexing,
+ unpack_1tuple,
+)
from pandas.core.indexes.accessors import CombinedDatetimelikeProperties
from pandas.core.indexes.api import (
CategoricalIndex,
@@ -104,7 +126,10 @@
from pandas.core.internals import SingleBlockManager
from pandas.core.internals.construction import sanitize_index
from pandas.core.shared_docs import _shared_docs
-from pandas.core.sorting import ensure_key_mapped, nargsort
+from pandas.core.sorting import (
+ ensure_key_mapped,
+ nargsort,
+)
from pandas.core.strings import StringMethods
from pandas.core.tools.datetimes import to_datetime
@@ -112,7 +137,10 @@
import pandas.plotting
if TYPE_CHECKING:
- from pandas._typing import TimedeltaConvertibleTypes, TimestampConvertibleTypes
+ from pandas._typing import (
+ TimedeltaConvertibleTypes,
+ TimestampConvertibleTypes,
+ )
from pandas.core.frame import DataFrame
from pandas.core.groupby.generic import SeriesGroupBy
diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py
index cfbabab491ae4..67863036929b3 100644
--- a/pandas/core/sorting.py
+++ b/pandas/core/sorting.py
@@ -16,7 +16,11 @@
import numpy as np
-from pandas._libs import algos, hashtable, lib
+from pandas._libs import (
+ algos,
+ hashtable,
+ lib,
+)
from pandas._libs.hashtable import unique_label_indices
from pandas._typing import IndexKeyFunc
diff --git a/pandas/core/sparse/api.py b/pandas/core/sparse/api.py
index e7bf94cdc08ea..2a324ebf77d9d 100644
--- a/pandas/core/sparse/api.py
+++ b/pandas/core/sparse/api.py
@@ -1,3 +1,6 @@
-from pandas.core.arrays.sparse import SparseArray, SparseDtype
+from pandas.core.arrays.sparse import (
+ SparseArray,
+ SparseDtype,
+)
__all__ = ["SparseArray", "SparseDtype"]
diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py
index 0e6ffa637f1ae..32a99c0a020b2 100644
--- a/pandas/core/strings/accessor.py
+++ b/pandas/core/strings/accessor.py
@@ -1,7 +1,11 @@
import codecs
from functools import wraps
import re
-from typing import Dict, List, Optional
+from typing import (
+ Dict,
+ List,
+ Optional,
+)
import warnings
import numpy as np
@@ -16,7 +20,12 @@
is_integer,
is_list_like,
)
-from pandas.core.dtypes.generic import ABCDataFrame, ABCIndex, ABCMultiIndex, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCIndex,
+ ABCMultiIndex,
+ ABCSeries,
+)
from pandas.core.dtypes.missing import isna
from pandas.core.base import NoNewAttributesMixin
@@ -233,7 +242,10 @@ def _wrap_result(
fill_value=np.nan,
returns_string=True,
):
- from pandas import Index, MultiIndex
+ from pandas import (
+ Index,
+ MultiIndex,
+ )
if not hasattr(result, "ndim") or not hasattr(result, "dtype"):
if isinstance(result, ABCDataFrame):
@@ -338,7 +350,10 @@ def _get_series_list(self, others):
list of Series
Others transformed into list of Series.
"""
- from pandas import DataFrame, Series
+ from pandas import (
+ DataFrame,
+ Series,
+ )
# self._orig is either Series or Index
idx = self._orig if isinstance(self._orig, ABCIndex) else self._orig.index
@@ -515,7 +530,11 @@ def cat(self, others=None, sep=None, na_rep=None, join="left"):
For more examples, see :ref:`here <text.concatenate>`.
"""
# TODO: dispatch
- from pandas import Index, Series, concat
+ from pandas import (
+ Index,
+ Series,
+ concat,
+ )
if isinstance(others, str):
raise ValueError("Did you mean to supply a `sep` keyword?")
@@ -2990,7 +3009,10 @@ def _str_extract_noexpand(arr, pat, flags=0):
Index.
"""
- from pandas import DataFrame, array
+ from pandas import (
+ DataFrame,
+ array,
+ )
regex = re.compile(pat, flags=flags)
groups_or_na = _groups_or_na_fun(regex)
diff --git a/pandas/core/strings/base.py b/pandas/core/strings/base.py
index 08064244a2ff9..b8033668aa18f 100644
--- a/pandas/core/strings/base.py
+++ b/pandas/core/strings/base.py
@@ -1,5 +1,8 @@
import abc
-from typing import Pattern, Union
+from typing import (
+ Pattern,
+ Union,
+)
import numpy as np
diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py
index 471f1e521b991..0a4543057c386 100644
--- a/pandas/core/strings/object_array.py
+++ b/pandas/core/strings/object_array.py
@@ -1,6 +1,12 @@
import re
import textwrap
-from typing import Optional, Pattern, Set, Union, cast
+from typing import (
+ Optional,
+ Pattern,
+ Set,
+ Union,
+ cast,
+)
import unicodedata
import warnings
@@ -9,9 +15,15 @@
import pandas._libs.lib as lib
import pandas._libs.missing as libmissing
import pandas._libs.ops as libops
-from pandas._typing import Dtype, Scalar
-
-from pandas.core.dtypes.common import is_re, is_scalar
+from pandas._typing import (
+ Dtype,
+ Scalar,
+)
+
+from pandas.core.dtypes.common import (
+ is_re,
+ is_scalar,
+)
from pandas.core.dtypes.missing import isna
from pandas.core.strings.base import BaseStringArrayMethods
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py
index b0df626da973a..18f9ece3e3812 100644
--- a/pandas/core/tools/datetimes.py
+++ b/pandas/core/tools/datetimes.py
@@ -35,7 +35,11 @@
guess_datetime_format,
)
from pandas._libs.tslibs.strptime import array_strptime
-from pandas._typing import AnyArrayLike, ArrayLike, Timezone
+from pandas._typing import (
+ AnyArrayLike,
+ ArrayLike,
+ Timezone,
+)
from pandas.core.dtypes.common import (
ensure_object,
@@ -49,10 +53,16 @@
is_numeric_dtype,
is_scalar,
)
-from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCSeries,
+)
from pandas.core.dtypes.missing import notna
-from pandas.arrays import DatetimeArray, IntegerArray
+from pandas.arrays import (
+ DatetimeArray,
+ IntegerArray,
+)
from pandas.core import algorithms
from pandas.core.algorithms import unique
from pandas.core.arrays.datetimes import (
@@ -882,7 +892,11 @@ def _assemble_from_unit_mappings(arg, errors, tz):
-------
Series
"""
- from pandas import DataFrame, to_numeric, to_timedelta
+ from pandas import (
+ DataFrame,
+ to_numeric,
+ to_timedelta,
+ )
arg = DataFrame(arg)
if not arg.columns.is_unique:
diff --git a/pandas/core/tools/numeric.py b/pandas/core/tools/numeric.py
index 3807fdd47b54f..1032edcb22b46 100644
--- a/pandas/core/tools/numeric.py
+++ b/pandas/core/tools/numeric.py
@@ -13,7 +13,10 @@
is_scalar,
needs_i8_conversion,
)
-from pandas.core.dtypes.generic import ABCIndex, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCIndex,
+ ABCSeries,
+)
import pandas as pd
from pandas.core.arrays.numeric import NumericArray
@@ -218,7 +221,10 @@ def to_numeric(arg, errors="raise", downcast=None):
data = np.zeros(mask.shape, dtype=values.dtype)
data[~mask] = values
- from pandas.core.arrays import FloatingArray, IntegerArray
+ from pandas.core.arrays import (
+ FloatingArray,
+ IntegerArray,
+ )
klass = IntegerArray if is_integer_dtype(data.dtype) else FloatingArray
values = klass(data, mask.copy())
diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py
index 0a274dcfd1d73..a335146265523 100644
--- a/pandas/core/tools/timedeltas.py
+++ b/pandas/core/tools/timedeltas.py
@@ -6,10 +6,16 @@
from pandas._libs import lib
from pandas._libs.tslibs import NaT
-from pandas._libs.tslibs.timedeltas import Timedelta, parse_timedelta_unit
+from pandas._libs.tslibs.timedeltas import (
+ Timedelta,
+ parse_timedelta_unit,
+)
from pandas.core.dtypes.common import is_list_like
-from pandas.core.dtypes.generic import ABCIndex, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCIndex,
+ ABCSeries,
+)
from pandas.core.arrays.timedeltas import sequence_to_td64ns
diff --git a/pandas/core/tools/times.py b/pandas/core/tools/times.py
index 9b86a7325fa6d..d5ccae9abc385 100644
--- a/pandas/core/tools/times.py
+++ b/pandas/core/tools/times.py
@@ -1,11 +1,20 @@
-from datetime import datetime, time
-from typing import List, Optional
+from datetime import (
+ datetime,
+ time,
+)
+from typing import (
+ List,
+ Optional,
+)
import numpy as np
from pandas._libs.lib import is_list_like
-from pandas.core.dtypes.generic import ABCIndex, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCIndex,
+ ABCSeries,
+)
from pandas.core.dtypes.missing import notna
diff --git a/pandas/core/util/hashing.py b/pandas/core/util/hashing.py
index 5af3f8f4e0a7f..6d375a92ea50a 100644
--- a/pandas/core/util/hashing.py
+++ b/pandas/core/util/hashing.py
@@ -13,7 +13,12 @@
is_extension_array_dtype,
is_list_like,
)
-from pandas.core.dtypes.generic import ABCDataFrame, ABCIndex, ABCMultiIndex, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCIndex,
+ ABCMultiIndex,
+ ABCSeries,
+)
# 16 byte long hashing key
_default_hash_key = "0123456789123456"
@@ -155,7 +160,10 @@ def hash_tuples(vals, encoding="utf8", hash_key: str = _default_hash_key):
elif not is_list_like(vals):
raise TypeError("must be convertible to a list-of-tuples")
- from pandas import Categorical, MultiIndex
+ from pandas import (
+ Categorical,
+ MultiIndex,
+ )
if not isinstance(vals, ABCMultiIndex):
vals = MultiIndex.from_tuples(vals)
@@ -270,7 +278,11 @@ def hash_array(
# then hash and rename categories. We allow skipping the categorization
# when the values are known/likely to be unique.
if categorize:
- from pandas import Categorical, Index, factorize
+ from pandas import (
+ Categorical,
+ Index,
+ factorize,
+ )
codes, categories = factorize(vals, sort=False)
cat = Categorical(codes, Index(categories), ordered=False, fastpath=True)
diff --git a/pandas/core/util/numba_.py b/pandas/core/util/numba_.py
index ed920c174ea69..3da6a5cbf7326 100644
--- a/pandas/core/util/numba_.py
+++ b/pandas/core/util/numba_.py
@@ -1,7 +1,12 @@
"""Common utilities for Numba operations"""
from distutils.version import LooseVersion
import types
-from typing import Callable, Dict, Optional, Tuple
+from typing import (
+ Callable,
+ Dict,
+ Optional,
+ Tuple,
+)
import numpy as np
diff --git a/pandas/core/window/__init__.py b/pandas/core/window/__init__.py
index b3d0820fee4da..8f42cd782c67f 100644
--- a/pandas/core/window/__init__.py
+++ b/pandas/core/window/__init__.py
@@ -2,5 +2,12 @@
ExponentialMovingWindow,
ExponentialMovingWindowGroupby,
)
-from pandas.core.window.expanding import Expanding, ExpandingGroupby # noqa:F401
-from pandas.core.window.rolling import Rolling, RollingGroupby, Window # noqa:F401
+from pandas.core.window.expanding import ( # noqa:F401
+ Expanding,
+ ExpandingGroupby,
+)
+from pandas.core.window.rolling import ( # noqa:F401
+ Rolling,
+ RollingGroupby,
+ Window,
+)
diff --git a/pandas/core/window/common.py b/pandas/core/window/common.py
index 8e935b7c05300..d85aa20de5ab4 100644
--- a/pandas/core/window/common.py
+++ b/pandas/core/window/common.py
@@ -5,7 +5,10 @@
import numpy as np
-from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCSeries,
+)
from pandas.core.indexes.api import MultiIndex
diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py
index 633427369902d..518119b63209e 100644
--- a/pandas/core/window/ewm.py
+++ b/pandas/core/window/ewm.py
@@ -3,14 +3,21 @@
import datetime
from functools import partial
from textwrap import dedent
-from typing import Optional, Union
+from typing import (
+ Optional,
+ Union,
+)
import warnings
import numpy as np
from pandas._libs.tslibs import Timedelta
import pandas._libs.window.aggregations as window_aggregations
-from pandas._typing import FrameOrSeries, FrameOrSeriesUnion, TimedeltaConvertibleTypes
+from pandas._typing import (
+ FrameOrSeries,
+ FrameOrSeriesUnion,
+ TimedeltaConvertibleTypes,
+)
from pandas.compat.numpy import function as nv
from pandas.util._decorators import doc
@@ -35,7 +42,10 @@
GroupbyIndexer,
)
from pandas.core.window.numba_ import generate_numba_groupby_ewma_func
-from pandas.core.window.rolling import BaseWindow, BaseWindowGroupby
+from pandas.core.window.rolling import (
+ BaseWindow,
+ BaseWindowGroupby,
+)
def get_center_of_mass(
diff --git a/pandas/core/window/expanding.py b/pandas/core/window/expanding.py
index f91441de41448..64e092d853456 100644
--- a/pandas/core/window/expanding.py
+++ b/pandas/core/window/expanding.py
@@ -1,5 +1,12 @@
from textwrap import dedent
-from typing import Any, Callable, Dict, Optional, Tuple, Union
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ Optional,
+ Tuple,
+ Union,
+)
import numpy as np
@@ -19,8 +26,15 @@
window_agg_numba_parameters,
window_apply_parameters,
)
-from pandas.core.window.indexers import BaseIndexer, ExpandingIndexer, GroupbyIndexer
-from pandas.core.window.rolling import BaseWindowGroupby, RollingAndExpandingMixin
+from pandas.core.window.indexers import (
+ BaseIndexer,
+ ExpandingIndexer,
+ GroupbyIndexer,
+)
+from pandas.core.window.rolling import (
+ BaseWindowGroupby,
+ RollingAndExpandingMixin,
+)
class Expanding(RollingAndExpandingMixin):
diff --git a/pandas/core/window/indexers.py b/pandas/core/window/indexers.py
index a3b9695d777d9..f8e2734b99e20 100644
--- a/pandas/core/window/indexers.py
+++ b/pandas/core/window/indexers.py
@@ -1,6 +1,11 @@
"""Indexer objects for computing start/end window bounds for rolling operations"""
from datetime import timedelta
-from typing import Dict, Optional, Tuple, Type
+from typing import (
+ Dict,
+ Optional,
+ Tuple,
+ Type,
+)
import numpy as np
diff --git a/pandas/core/window/numba_.py b/pandas/core/window/numba_.py
index aa69d4fa675cd..c9107c8ed0aa7 100644
--- a/pandas/core/window/numba_.py
+++ b/pandas/core/window/numba_.py
@@ -1,5 +1,11 @@
import functools
-from typing import Any, Callable, Dict, Optional, Tuple
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ Optional,
+ Tuple,
+)
import numpy as np
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index 1538975b260c0..20bf0142b0855 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -24,9 +24,17 @@
import numpy as np
-from pandas._libs.tslibs import BaseOffset, to_offset
+from pandas._libs.tslibs import (
+ BaseOffset,
+ to_offset,
+)
import pandas._libs.window.aggregations as window_aggregations
-from pandas._typing import ArrayLike, Axis, FrameOrSeries, FrameOrSeriesUnion
+from pandas._typing import (
+ ArrayLike,
+ Axis,
+ FrameOrSeries,
+ FrameOrSeriesUnion,
+)
from pandas.compat._optional import import_optional_dependency
from pandas.compat.numpy import function as nv
from pandas.util._decorators import doc
@@ -50,14 +58,29 @@
from pandas.core.algorithms import factorize
from pandas.core.apply import ResamplerWindowApply
-from pandas.core.base import DataError, SelectionMixin
+from pandas.core.base import (
+ DataError,
+ SelectionMixin,
+)
import pandas.core.common as common
from pandas.core.construction import extract_array
-from pandas.core.groupby.base import GotItemMixin, ShallowMixin
-from pandas.core.indexes.api import Index, MultiIndex
+from pandas.core.groupby.base import (
+ GotItemMixin,
+ ShallowMixin,
+)
+from pandas.core.indexes.api import (
+ Index,
+ MultiIndex,
+)
from pandas.core.reshape.concat import concat
-from pandas.core.util.numba_ import NUMBA_FUNC_CACHE, maybe_use_numba
-from pandas.core.window.common import flex_binary_moment, zsqrt
+from pandas.core.util.numba_ import (
+ NUMBA_FUNC_CACHE,
+ maybe_use_numba,
+)
+from pandas.core.window.common import (
+ flex_binary_moment,
+ zsqrt,
+)
from pandas.core.window.doc import (
_shared_docs,
args_compat,
@@ -84,7 +107,10 @@
)
if TYPE_CHECKING:
- from pandas import DataFrame, Series
+ from pandas import (
+ DataFrame,
+ Series,
+ )
from pandas.core.internals import Block # noqa:F401
diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py
index ea60ae5c1d227..a0f6ddfd84d7b 100644
--- a/pandas/errors/__init__.py
+++ b/pandas/errors/__init__.py
@@ -6,7 +6,10 @@
from pandas._config.config import OptionError
-from pandas._libs.tslibs import OutOfBoundsDatetime, OutOfBoundsTimedelta
+from pandas._libs.tslibs import (
+ OutOfBoundsDatetime,
+ OutOfBoundsTimedelta,
+)
class NullFrequencyError(ValueError):
diff --git a/pandas/io/api.py b/pandas/io/api.py
index 2d25ffe5f8a6b..2241f491b5d48 100644
--- a/pandas/io/api.py
+++ b/pandas/io/api.py
@@ -5,17 +5,35 @@
# flake8: noqa
from pandas.io.clipboards import read_clipboard
-from pandas.io.excel import ExcelFile, ExcelWriter, read_excel
+from pandas.io.excel import (
+ ExcelFile,
+ ExcelWriter,
+ read_excel,
+)
from pandas.io.feather_format import read_feather
from pandas.io.gbq import read_gbq
from pandas.io.html import read_html
from pandas.io.json import read_json
from pandas.io.orc import read_orc
from pandas.io.parquet import read_parquet
-from pandas.io.parsers import read_csv, read_fwf, read_table
-from pandas.io.pickle import read_pickle, to_pickle
-from pandas.io.pytables import HDFStore, read_hdf
+from pandas.io.parsers import (
+ read_csv,
+ read_fwf,
+ read_table,
+)
+from pandas.io.pickle import (
+ read_pickle,
+ to_pickle,
+)
+from pandas.io.pytables import (
+ HDFStore,
+ read_hdf,
+)
from pandas.io.sas import read_sas
from pandas.io.spss import read_spss
-from pandas.io.sql import read_sql, read_sql_query, read_sql_table
+from pandas.io.sql import (
+ read_sql,
+ read_sql_query,
+ read_sql_table,
+)
from pandas.io.stata import read_stata
diff --git a/pandas/io/clipboard/__init__.py b/pandas/io/clipboard/__init__.py
index 233e58d14adf1..788fc62165c0c 100644
--- a/pandas/io/clipboard/__init__.py
+++ b/pandas/io/clipboard/__init__.py
@@ -44,7 +44,13 @@
import contextlib
import ctypes
-from ctypes import c_size_t, c_wchar, c_wchar_p, get_errno, sizeof
+from ctypes import (
+ c_size_t,
+ c_wchar,
+ c_wchar_p,
+ get_errno,
+ sizeof,
+)
import distutils.spawn
import os
import platform
diff --git a/pandas/io/clipboards.py b/pandas/io/clipboards.py
index 97178261bdf72..54cb6b9f91137 100644
--- a/pandas/io/clipboards.py
+++ b/pandas/io/clipboards.py
@@ -4,7 +4,10 @@
from pandas.core.dtypes.generic import ABCDataFrame
-from pandas import get_option, option_context
+from pandas import (
+ get_option,
+ option_context,
+)
def read_clipboard(sep=r"\s+", **kwargs): # pragma: no cover
diff --git a/pandas/io/common.py b/pandas/io/common.py
index e5a1f58ec6cd2..e5da12d7b1753 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -6,10 +6,27 @@
from collections import abc
import dataclasses
import gzip
-from io import BufferedIOBase, BytesIO, RawIOBase, StringIO, TextIOWrapper
+from io import (
+ BufferedIOBase,
+ BytesIO,
+ RawIOBase,
+ StringIO,
+ TextIOWrapper,
+)
import mmap
import os
-from typing import IO, Any, AnyStr, Dict, List, Mapping, Optional, Tuple, Union, cast
+from typing import (
+ IO,
+ Any,
+ AnyStr,
+ Dict,
+ List,
+ Mapping,
+ Optional,
+ Tuple,
+ Union,
+ cast,
+)
from urllib.parse import (
urljoin,
urlparse as parse_url,
@@ -28,7 +45,10 @@
FilePathOrBuffer,
StorageOptions,
)
-from pandas.compat import get_lzma_file, import_lzma
+from pandas.compat import (
+ get_lzma_file,
+ import_lzma,
+)
from pandas.compat._optional import import_optional_dependency
from pandas.core.dtypes.common import is_file_like
@@ -325,7 +345,10 @@ def _get_filepath_or_buffer(
err_types_to_retry_with_anon: List[Any] = []
try:
import_optional_dependency("botocore")
- from botocore.exceptions import ClientError, NoCredentialsError
+ from botocore.exceptions import (
+ ClientError,
+ NoCredentialsError,
+ )
err_types_to_retry_with_anon = [
ClientError,
diff --git a/pandas/io/excel/__init__.py b/pandas/io/excel/__init__.py
index 3bad493dee388..854e2a1ec3a73 100644
--- a/pandas/io/excel/__init__.py
+++ b/pandas/io/excel/__init__.py
@@ -1,4 +1,8 @@
-from pandas.io.excel._base import ExcelFile, ExcelWriter, read_excel
+from pandas.io.excel._base import (
+ ExcelFile,
+ ExcelWriter,
+ read_excel,
+)
from pandas.io.excel._odswriter import ODSWriter as _ODSWriter
from pandas.io.excel._openpyxl import OpenpyxlWriter as _OpenpyxlWriter
from pandas.io.excel._util import register_writer
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index 8902d45144c56..7088f93fa6474 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -7,24 +7,53 @@
from io import BytesIO
import os
from textwrap import fill
-from typing import Any, Dict, Mapping, Optional, Union, cast
+from typing import (
+ Any,
+ Dict,
+ Mapping,
+ Optional,
+ Union,
+ cast,
+)
import warnings
import zipfile
from pandas._config import config
from pandas._libs.parsers import STR_NA_VALUES
-from pandas._typing import Buffer, DtypeArg, FilePathOrBuffer, StorageOptions
-from pandas.compat._optional import get_version, import_optional_dependency
+from pandas._typing import (
+ Buffer,
+ DtypeArg,
+ FilePathOrBuffer,
+ StorageOptions,
+)
+from pandas.compat._optional import (
+ get_version,
+ import_optional_dependency,
+)
from pandas.errors import EmptyDataError
-from pandas.util._decorators import Appender, deprecate_nonkeyword_arguments, doc
+from pandas.util._decorators import (
+ Appender,
+ deprecate_nonkeyword_arguments,
+ doc,
+)
-from pandas.core.dtypes.common import is_bool, is_float, is_integer, is_list_like
+from pandas.core.dtypes.common import (
+ is_bool,
+ is_float,
+ is_integer,
+ is_list_like,
+)
from pandas.core.frame import DataFrame
from pandas.core.shared_docs import _shared_docs
-from pandas.io.common import IOHandles, get_handle, stringify_path, validate_header_arg
+from pandas.io.common import (
+ IOHandles,
+ get_handle,
+ stringify_path,
+ validate_header_arg,
+)
from pandas.io.excel._util import (
fill_mi_header,
get_default_engine,
diff --git a/pandas/io/excel/_odfreader.py b/pandas/io/excel/_odfreader.py
index 8987d5bb42057..c5aa4a061a05b 100644
--- a/pandas/io/excel/_odfreader.py
+++ b/pandas/io/excel/_odfreader.py
@@ -1,8 +1,15 @@
-from typing import List, cast
+from typing import (
+ List,
+ cast,
+)
import numpy as np
-from pandas._typing import FilePathOrBuffer, Scalar, StorageOptions
+from pandas._typing import (
+ FilePathOrBuffer,
+ Scalar,
+ StorageOptions,
+)
from pandas.compat._optional import import_optional_dependency
import pandas as pd
@@ -78,7 +85,11 @@ def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]:
"""
Parse an ODF Table into a list of lists
"""
- from odf.table import CoveredTableCell, TableCell, TableRow
+ from odf.table import (
+ CoveredTableCell,
+ TableCell,
+ TableRow,
+ )
covered_cell_name = CoveredTableCell().qname
table_cell_name = TableCell().qname
diff --git a/pandas/io/excel/_odswriter.py b/pandas/io/excel/_odswriter.py
index 0bea19bec2cdd..d00e600b4e5d4 100644
--- a/pandas/io/excel/_odswriter.py
+++ b/pandas/io/excel/_odswriter.py
@@ -1,6 +1,14 @@
from collections import defaultdict
import datetime
-from typing import Any, DefaultDict, Dict, List, Optional, Tuple, Union
+from typing import (
+ Any,
+ DefaultDict,
+ Dict,
+ List,
+ Optional,
+ Tuple,
+ Union,
+)
import pandas._libs.json as json
from pandas._typing import StorageOptions
@@ -55,7 +63,11 @@ def write_cells(
"""
Write the frame cells using odf
"""
- from odf.table import Table, TableCell, TableRow
+ from odf.table import (
+ Table,
+ TableCell,
+ TableRow,
+ )
from odf.text import P
sheet_name = self._get_sheet_name(sheet_name)
diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py
index 15f49660dc6dc..be2c9b919a5c3 100644
--- a/pandas/io/excel/_openpyxl.py
+++ b/pandas/io/excel/_openpyxl.py
@@ -1,14 +1,26 @@
from __future__ import annotations
import mmap
-from typing import TYPE_CHECKING, Dict, List, Optional
+from typing import (
+ TYPE_CHECKING,
+ Dict,
+ List,
+ Optional,
+)
import numpy as np
-from pandas._typing import FilePathOrBuffer, Scalar, StorageOptions
+from pandas._typing import (
+ FilePathOrBuffer,
+ Scalar,
+ StorageOptions,
+)
from pandas.compat._optional import import_optional_dependency
-from pandas.io.excel._base import BaseExcelReader, ExcelWriter
+from pandas.io.excel._base import (
+ BaseExcelReader,
+ ExcelWriter,
+)
from pandas.io.excel._util import validate_freeze_panes
if TYPE_CHECKING:
@@ -215,7 +227,10 @@ def _convert_to_fill(cls, fill_dict):
-------
fill : openpyxl.styles.Fill
"""
- from openpyxl.styles import GradientFill, PatternFill
+ from openpyxl.styles import (
+ GradientFill,
+ PatternFill,
+ )
_pattern_fill_key_map = {
"patternType": "fill_type",
@@ -508,7 +523,10 @@ def get_sheet_by_index(self, index: int):
def _convert_cell(self, cell, convert_float: bool) -> Scalar:
- from openpyxl.cell.cell import TYPE_ERROR, TYPE_NUMERIC
+ from openpyxl.cell.cell import (
+ TYPE_ERROR,
+ TYPE_NUMERIC,
+ )
if cell.value is None:
return "" # compat with xlrd
diff --git a/pandas/io/excel/_pyxlsb.py b/pandas/io/excel/_pyxlsb.py
index f77a6bd5b1ad5..71ec189854f6d 100644
--- a/pandas/io/excel/_pyxlsb.py
+++ b/pandas/io/excel/_pyxlsb.py
@@ -1,6 +1,10 @@
from typing import List
-from pandas._typing import FilePathOrBuffer, Scalar, StorageOptions
+from pandas._typing import (
+ FilePathOrBuffer,
+ Scalar,
+ StorageOptions,
+)
from pandas.compat._optional import import_optional_dependency
from pandas.io.excel._base import BaseExcelReader
diff --git a/pandas/io/excel/_util.py b/pandas/io/excel/_util.py
index 01ccc9d15a6a3..bc848455c47d1 100644
--- a/pandas/io/excel/_util.py
+++ b/pandas/io/excel/_util.py
@@ -1,8 +1,14 @@
-from typing import List, MutableMapping
+from typing import (
+ List,
+ MutableMapping,
+)
from pandas.compat._optional import import_optional_dependency
-from pandas.core.dtypes.common import is_integer, is_list_like
+from pandas.core.dtypes.common import (
+ is_integer,
+ is_list_like,
+)
_writers: MutableMapping[str, str] = {}
diff --git a/pandas/io/excel/_xlsxwriter.py b/pandas/io/excel/_xlsxwriter.py
index d7bbec578d89d..849572cff813a 100644
--- a/pandas/io/excel/_xlsxwriter.py
+++ b/pandas/io/excel/_xlsxwriter.py
@@ -1,4 +1,8 @@
-from typing import Dict, List, Tuple
+from typing import (
+ Dict,
+ List,
+ Tuple,
+)
import pandas._libs.json as json
from pandas._typing import StorageOptions
diff --git a/pandas/io/excel/_xlwt.py b/pandas/io/excel/_xlwt.py
index 9a725c15de61e..a8386242faf72 100644
--- a/pandas/io/excel/_xlwt.py
+++ b/pandas/io/excel/_xlwt.py
@@ -1,4 +1,7 @@
-from typing import TYPE_CHECKING, Dict
+from typing import (
+ TYPE_CHECKING,
+ Dict,
+)
import pandas._libs.json as json
from pandas._typing import StorageOptions
diff --git a/pandas/io/feather_format.py b/pandas/io/feather_format.py
index 422677771b4d0..3999f91a7b141 100644
--- a/pandas/io/feather_format.py
+++ b/pandas/io/feather_format.py
@@ -2,11 +2,18 @@
from typing import AnyStr
-from pandas._typing import FilePathOrBuffer, StorageOptions
+from pandas._typing import (
+ FilePathOrBuffer,
+ StorageOptions,
+)
from pandas.compat._optional import import_optional_dependency
from pandas.util._decorators import doc
-from pandas import DataFrame, Int64Index, RangeIndex
+from pandas import (
+ DataFrame,
+ Int64Index,
+ RangeIndex,
+)
from pandas.core import generic
from pandas.io.common import get_handle
diff --git a/pandas/io/formats/css.py b/pandas/io/formats/css.py
index 8abe13db370ca..f27bae2c161f3 100644
--- a/pandas/io/formats/css.py
+++ b/pandas/io/formats/css.py
@@ -3,7 +3,10 @@
"""
import re
-from typing import Dict, Optional
+from typing import (
+ Dict,
+ Optional,
+)
import warnings
diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py
index 099688b2449db..adfe1f285f2ee 100644
--- a/pandas/io/formats/excel.py
+++ b/pandas/io/formats/excel.py
@@ -21,18 +21,32 @@
import numpy as np
from pandas._libs.lib import is_list_like
-from pandas._typing import IndexLabel, StorageOptions
+from pandas._typing import (
+ IndexLabel,
+ StorageOptions,
+)
from pandas.util._decorators import doc
from pandas.core.dtypes import missing
-from pandas.core.dtypes.common import is_float, is_scalar
+from pandas.core.dtypes.common import (
+ is_float,
+ is_scalar,
+)
-from pandas import DataFrame, Index, MultiIndex, PeriodIndex
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ PeriodIndex,
+)
from pandas.core import generic
import pandas.core.common as com
from pandas.io.formats._color_data import CSS4_COLORS
-from pandas.io.formats.css import CSSResolver, CSSWarning
+from pandas.io.formats.css import (
+ CSSResolver,
+ CSSWarning,
+)
from pandas.io.formats.format import get_level_lengths
from pandas.io.formats.printing import pprint_thing
diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py
index 48b2fae8c6de5..a1b6986079723 100644
--- a/pandas/io/formats/format.py
+++ b/pandas/io/formats/format.py
@@ -5,7 +5,10 @@
from __future__ import annotations
from contextlib import contextmanager
-from csv import QUOTE_NONE, QUOTE_NONNUMERIC
+from csv import (
+ QUOTE_NONE,
+ QUOTE_NONNUMERIC,
+)
import decimal
from functools import partial
from io import StringIO
@@ -33,11 +36,19 @@
import numpy as np
-from pandas._config.config import get_option, set_option
+from pandas._config.config import (
+ get_option,
+ set_option,
+)
from pandas._libs import lib
from pandas._libs.missing import NA
-from pandas._libs.tslibs import NaT, Timedelta, Timestamp, iNaT
+from pandas._libs.tslibs import (
+ NaT,
+ Timedelta,
+ Timestamp,
+ iNaT,
+)
from pandas._libs.tslibs.nattype import NaTType
from pandas._typing import (
ArrayLike,
@@ -66,23 +77,39 @@
is_scalar,
is_timedelta64_dtype,
)
-from pandas.core.dtypes.missing import isna, notna
+from pandas.core.dtypes.missing import (
+ isna,
+ notna,
+)
from pandas.core.arrays.datetimes import DatetimeArray
from pandas.core.arrays.timedeltas import TimedeltaArray
from pandas.core.base import PandasObject
import pandas.core.common as com
from pandas.core.construction import extract_array
-from pandas.core.indexes.api import Index, MultiIndex, PeriodIndex, ensure_index
+from pandas.core.indexes.api import (
+ Index,
+ MultiIndex,
+ PeriodIndex,
+ ensure_index,
+)
from pandas.core.indexes.datetimes import DatetimeIndex
from pandas.core.indexes.timedeltas import TimedeltaIndex
from pandas.core.reshape.concat import concat
from pandas.io.common import stringify_path
-from pandas.io.formats.printing import adjoin, justify, pprint_thing
+from pandas.io.formats.printing import (
+ adjoin,
+ justify,
+ pprint_thing,
+)
if TYPE_CHECKING:
- from pandas import Categorical, DataFrame, Series
+ from pandas import (
+ Categorical,
+ DataFrame,
+ Series,
+ )
common_docstring = """
@@ -989,7 +1016,10 @@ def to_html(
render_links : bool, default False
Convert URLs to HTML links.
"""
- from pandas.io.formats.html import HTMLFormatter, NotebookFormatter
+ from pandas.io.formats.html import (
+ HTMLFormatter,
+ NotebookFormatter,
+ )
Klass = NotebookFormatter if notebook else HTMLFormatter
diff --git a/pandas/io/formats/html.py b/pandas/io/formats/html.py
index b4f7e3922f02f..6f4a6d87c7959 100644
--- a/pandas/io/formats/html.py
+++ b/pandas/io/formats/html.py
@@ -3,16 +3,32 @@
"""
from textwrap import dedent
-from typing import Any, Dict, Iterable, List, Mapping, Optional, Tuple, Union, cast
+from typing import (
+ Any,
+ Dict,
+ Iterable,
+ List,
+ Mapping,
+ Optional,
+ Tuple,
+ Union,
+ cast,
+)
from pandas._config import get_option
from pandas._libs import lib
-from pandas import MultiIndex, option_context
+from pandas import (
+ MultiIndex,
+ option_context,
+)
from pandas.io.common import is_url
-from pandas.io.formats.format import DataFrameFormatter, get_level_lengths
+from pandas.io.formats.format import (
+ DataFrameFormatter,
+ get_level_lengths,
+)
from pandas.io.formats.printing import pprint_thing
diff --git a/pandas/io/formats/info.py b/pandas/io/formats/info.py
index b1675fa5c5375..2c1739998da08 100644
--- a/pandas/io/formats/info.py
+++ b/pandas/io/formats/info.py
@@ -1,6 +1,9 @@
from __future__ import annotations
-from abc import ABC, abstractmethod
+from abc import (
+ ABC,
+ abstractmethod,
+)
import sys
from typing import (
IO,
@@ -16,7 +19,10 @@
from pandas._config import get_option
-from pandas._typing import Dtype, FrameOrSeriesUnion
+from pandas._typing import (
+ Dtype,
+ FrameOrSeriesUnion,
+)
from pandas.core.indexes.api import Index
diff --git a/pandas/io/formats/latex.py b/pandas/io/formats/latex.py
index f6f3571955e6e..fce0814e979a4 100644
--- a/pandas/io/formats/latex.py
+++ b/pandas/io/formats/latex.py
@@ -1,8 +1,19 @@
"""
Module for formatting output data in Latex.
"""
-from abc import ABC, abstractmethod
-from typing import Iterator, List, Optional, Sequence, Tuple, Type, Union
+from abc import (
+ ABC,
+ abstractmethod,
+)
+from typing import (
+ Iterator,
+ List,
+ Optional,
+ Sequence,
+ Tuple,
+ Type,
+ Union,
+)
import numpy as np
diff --git a/pandas/io/formats/string.py b/pandas/io/formats/string.py
index 1fe2ed9806535..622001f280885 100644
--- a/pandas/io/formats/string.py
+++ b/pandas/io/formats/string.py
@@ -2,7 +2,11 @@
Module for formatting output data in console (to string).
"""
from shutil import get_terminal_size
-from typing import Iterable, List, Optional
+from typing import (
+ Iterable,
+ List,
+ Optional,
+)
import numpy as np
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index 8322587a096d4..e81440dc36360 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -27,19 +27,30 @@
from pandas._config import get_option
from pandas._libs import lib
-from pandas._typing import Axis, FrameOrSeries, FrameOrSeriesUnion, IndexLabel
+from pandas._typing import (
+ Axis,
+ FrameOrSeries,
+ FrameOrSeriesUnion,
+ IndexLabel,
+)
from pandas.compat._optional import import_optional_dependency
from pandas.util._decorators import doc
from pandas.core.dtypes.common import is_float
import pandas as pd
-from pandas.api.types import is_dict_like, is_list_like
+from pandas.api.types import (
+ is_dict_like,
+ is_list_like,
+)
from pandas.core import generic
import pandas.core.common as com
from pandas.core.frame import DataFrame
from pandas.core.generic import NDFrame
-from pandas.core.indexing import maybe_numeric_slice, non_reducing_slice
+from pandas.core.indexing import (
+ maybe_numeric_slice,
+ non_reducing_slice,
+)
jinja2 = import_optional_dependency("jinja2", extra="DataFrame.style requires jinja2.")
CSSSequence = Sequence[Tuple[str, Union[str, int, float]]]
diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py
index 260d688ccb0cc..215d966609ab4 100644
--- a/pandas/io/gbq.py
+++ b/pandas/io/gbq.py
@@ -1,7 +1,14 @@
""" Google BigQuery support """
from __future__ import annotations
-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Dict,
+ List,
+ Optional,
+ Union,
+)
from pandas.compat._optional import import_optional_dependency
diff --git a/pandas/io/html.py b/pandas/io/html.py
index c445ee81ec8ed..7541e5d62fd1e 100644
--- a/pandas/io/html.py
+++ b/pandas/io/html.py
@@ -8,11 +8,22 @@
import numbers
import os
import re
-from typing import Dict, List, Optional, Pattern, Sequence, Tuple, Union
+from typing import (
+ Dict,
+ List,
+ Optional,
+ Pattern,
+ Sequence,
+ Tuple,
+ Union,
+)
from pandas._typing import FilePathOrBuffer
from pandas.compat._optional import import_optional_dependency
-from pandas.errors import AbstractMethodError, EmptyDataError
+from pandas.errors import (
+ AbstractMethodError,
+ EmptyDataError,
+)
from pandas.util._decorators import deprecate_nonkeyword_arguments
from pandas.core.dtypes.common import is_list_like
@@ -20,7 +31,12 @@
from pandas.core.construction import create_series_with_explicit_dtype
from pandas.core.frame import DataFrame
-from pandas.io.common import is_url, stringify_path, urlopen, validate_header_arg
+from pandas.io.common import (
+ is_url,
+ stringify_path,
+ urlopen,
+ validate_header_arg,
+)
from pandas.io.formats.printing import pprint_thing
from pandas.io.parsers import TextParser
@@ -700,7 +716,11 @@ def _build_doc(self):
pandas.io.html._HtmlFrameParser._build_doc
"""
from lxml.etree import XMLSyntaxError
- from lxml.html import HTMLParser, fromstring, parse
+ from lxml.html import (
+ HTMLParser,
+ fromstring,
+ parse,
+ )
parser = HTMLParser(recover=True, encoding=self.encoding)
diff --git a/pandas/io/json/__init__.py b/pandas/io/json/__init__.py
index 48febb086c302..1de1abcdb9920 100644
--- a/pandas/io/json/__init__.py
+++ b/pandas/io/json/__init__.py
@@ -1,5 +1,13 @@
-from pandas.io.json._json import dumps, loads, read_json, to_json
-from pandas.io.json._normalize import _json_normalize, json_normalize
+from pandas.io.json._json import (
+ dumps,
+ loads,
+ read_json,
+ to_json,
+)
+from pandas.io.json._normalize import (
+ _json_normalize,
+ json_normalize,
+)
from pandas.io.json._table_schema import build_table_schema
__all__ = [
diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py
index 497cf261fcece..635a493d03d61 100644
--- a/pandas/io/json/_json.py
+++ b/pandas/io/json/_json.py
@@ -1,9 +1,20 @@
-from abc import ABC, abstractmethod
+from abc import (
+ ABC,
+ abstractmethod,
+)
from collections import abc
import functools
from io import StringIO
from itertools import islice
-from typing import Any, Callable, Mapping, Optional, Tuple, Type, Union
+from typing import (
+ Any,
+ Callable,
+ Mapping,
+ Optional,
+ Tuple,
+ Type,
+ Union,
+)
import numpy as np
@@ -18,11 +29,25 @@
StorageOptions,
)
from pandas.errors import AbstractMethodError
-from pandas.util._decorators import deprecate_kwarg, deprecate_nonkeyword_arguments, doc
+from pandas.util._decorators import (
+ deprecate_kwarg,
+ deprecate_nonkeyword_arguments,
+ doc,
+)
-from pandas.core.dtypes.common import ensure_str, is_period_dtype
+from pandas.core.dtypes.common import (
+ ensure_str,
+ is_period_dtype,
+)
-from pandas import DataFrame, MultiIndex, Series, isna, notna, to_datetime
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+ isna,
+ notna,
+ to_datetime,
+)
from pandas.core import generic
from pandas.core.construction import create_series_with_explicit_dtype
from pandas.core.generic import NDFrame
@@ -37,7 +62,10 @@
stringify_path,
)
from pandas.io.json._normalize import convert_to_line_delimits
-from pandas.io.json._table_schema import build_table_schema, parse_table_schema
+from pandas.io.json._table_schema import (
+ build_table_schema,
+ parse_table_schema,
+)
from pandas.io.parsers.readers import validate_integer
loads = json.loads
diff --git a/pandas/io/json/_normalize.py b/pandas/io/json/_normalize.py
index 8dcc9fa490635..975eb263eca07 100644
--- a/pandas/io/json/_normalize.py
+++ b/pandas/io/json/_normalize.py
@@ -2,9 +2,20 @@
# JSON normalization routines
from __future__ import annotations
-from collections import abc, defaultdict
+from collections import (
+ abc,
+ defaultdict,
+)
import copy
-from typing import Any, DefaultDict, Dict, Iterable, List, Optional, Union
+from typing import (
+ Any,
+ DefaultDict,
+ Dict,
+ Iterable,
+ List,
+ Optional,
+ Union,
+)
import numpy as np
diff --git a/pandas/io/json/_table_schema.py b/pandas/io/json/_table_schema.py
index 0499a35296490..4824dab764259 100644
--- a/pandas/io/json/_table_schema.py
+++ b/pandas/io/json/_table_schema.py
@@ -3,11 +3,21 @@
https://specs.frictionlessdata.io/json-table-schema/
"""
-from typing import TYPE_CHECKING, Any, Dict, Optional, cast
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Dict,
+ Optional,
+ cast,
+)
import warnings
import pandas._libs.json as json
-from pandas._typing import DtypeObj, FrameOrSeries, JSONSerializable
+from pandas._typing import (
+ DtypeObj,
+ FrameOrSeries,
+ JSONSerializable,
+)
from pandas.core.dtypes.common import (
is_bool_dtype,
diff --git a/pandas/io/orc.py b/pandas/io/orc.py
index a219be99540dc..df76156aac9eb 100644
--- a/pandas/io/orc.py
+++ b/pandas/io/orc.py
@@ -2,7 +2,11 @@
from __future__ import annotations
import distutils
-from typing import TYPE_CHECKING, List, Optional
+from typing import (
+ TYPE_CHECKING,
+ List,
+ Optional,
+)
from pandas._typing import FilePathOrBuffer
diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py
index 0a322059ed77c..183d753ddd60b 100644
--- a/pandas/io/parquet.py
+++ b/pandas/io/parquet.py
@@ -4,15 +4,29 @@
from distutils.version import LooseVersion
import io
import os
-from typing import Any, AnyStr, Dict, List, Optional, Tuple
+from typing import (
+ Any,
+ AnyStr,
+ Dict,
+ List,
+ Optional,
+ Tuple,
+)
from warnings import catch_warnings
-from pandas._typing import FilePathOrBuffer, StorageOptions
+from pandas._typing import (
+ FilePathOrBuffer,
+ StorageOptions,
+)
from pandas.compat._optional import import_optional_dependency
from pandas.errors import AbstractMethodError
from pandas.util._decorators import doc
-from pandas import DataFrame, MultiIndex, get_option
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ get_option,
+)
from pandas.core import generic
from pandas.io.common import (
diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py
index 8961fd0a7af06..2d17978b60327 100644
--- a/pandas/io/parsers/base_parser.py
+++ b/pandas/io/parsers/base_parser.py
@@ -24,8 +24,14 @@
import pandas._libs.parsers as parsers
from pandas._libs.parsers import STR_NA_VALUES
from pandas._libs.tslibs import parsing
-from pandas._typing import DtypeArg, FilePathOrBuffer
-from pandas.errors import ParserError, ParserWarning
+from pandas._typing import (
+ DtypeArg,
+ FilePathOrBuffer,
+)
+from pandas.errors import (
+ ParserError,
+ ParserWarning,
+)
from pandas.core.dtypes.cast import astype_nansafe
from pandas.core.dtypes.common import (
@@ -49,11 +55,18 @@
from pandas.core import algorithms
from pandas.core.arrays import Categorical
-from pandas.core.indexes.api import Index, MultiIndex, ensure_index_from_sequences
+from pandas.core.indexes.api import (
+ Index,
+ MultiIndex,
+ ensure_index_from_sequences,
+)
from pandas.core.series import Series
from pandas.core.tools import datetimes as tools
-from pandas.io.common import IOHandles, get_handle
+from pandas.io.common import (
+ IOHandles,
+ get_handle,
+)
from pandas.io.date_converters import generic_parser
parser_defaults = {
diff --git a/pandas/io/parsers/c_parser_wrapper.py b/pandas/io/parsers/c_parser_wrapper.py
index 27f06dc84a275..135e093cdc1e0 100644
--- a/pandas/io/parsers/c_parser_wrapper.py
+++ b/pandas/io/parsers/c_parser_wrapper.py
@@ -3,7 +3,10 @@
from pandas.core.indexes.api import ensure_index_from_sequences
-from pandas.io.parsers.base_parser import ParserBase, is_index_col
+from pandas.io.parsers.base_parser import (
+ ParserBase,
+ is_index_col,
+)
class CParserWrapper(ParserBase):
diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py
index cfd648636753d..37f553c724c9e 100644
--- a/pandas/io/parsers/python_parser.py
+++ b/pandas/io/parsers/python_parser.py
@@ -1,19 +1,39 @@
-from collections import abc, defaultdict
+from collections import (
+ abc,
+ defaultdict,
+)
import csv
from io import StringIO
import re
import sys
-from typing import DefaultDict, Iterator, List, Optional, Set, Tuple, cast
+from typing import (
+ DefaultDict,
+ Iterator,
+ List,
+ Optional,
+ Set,
+ Tuple,
+ cast,
+)
import numpy as np
import pandas._libs.lib as lib
-from pandas._typing import FilePathOrBuffer, Union
-from pandas.errors import EmptyDataError, ParserError
+from pandas._typing import (
+ FilePathOrBuffer,
+ Union,
+)
+from pandas.errors import (
+ EmptyDataError,
+ ParserError,
+)
from pandas.core.dtypes.common import is_integer
-from pandas.io.parsers.base_parser import ParserBase, parser_defaults
+from pandas.io.parsers.base_parser import (
+ ParserBase,
+ parser_defaults,
+)
# BOM character (byte order mark)
# This exists at the beginning of a file to indicate endianness
diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py
index dc45336bb4c0f..edfc7ee0b6258 100644
--- a/pandas/io/parsers/readers.py
+++ b/pandas/io/parsers/readers.py
@@ -5,27 +5,54 @@
import csv
import sys
from textwrap import fill
-from typing import Any, Dict, List, Optional, Set, Type
+from typing import (
+ Any,
+ Dict,
+ List,
+ Optional,
+ Set,
+ Type,
+)
import warnings
import numpy as np
import pandas._libs.lib as lib
from pandas._libs.parsers import STR_NA_VALUES
-from pandas._typing import DtypeArg, FilePathOrBuffer, StorageOptions, Union
-from pandas.errors import AbstractMethodError, ParserWarning
+from pandas._typing import (
+ DtypeArg,
+ FilePathOrBuffer,
+ StorageOptions,
+ Union,
+)
+from pandas.errors import (
+ AbstractMethodError,
+ ParserWarning,
+)
from pandas.util._decorators import Appender
-from pandas.core.dtypes.common import is_file_like, is_float, is_integer, is_list_like
+from pandas.core.dtypes.common import (
+ is_file_like,
+ is_float,
+ is_integer,
+ is_list_like,
+)
from pandas.core import generic
from pandas.core.frame import DataFrame
from pandas.core.indexes.api import RangeIndex
from pandas.io.common import validate_header_arg
-from pandas.io.parsers.base_parser import ParserBase, is_index_col, parser_defaults
+from pandas.io.parsers.base_parser import (
+ ParserBase,
+ is_index_col,
+ parser_defaults,
+)
from pandas.io.parsers.c_parser_wrapper import CParserWrapper
-from pandas.io.parsers.python_parser import FixedWidthFieldParser, PythonParser
+from pandas.io.parsers.python_parser import (
+ FixedWidthFieldParser,
+ PythonParser,
+)
_doc_read_csv_and_table = (
r"""
diff --git a/pandas/io/pickle.py b/pandas/io/pickle.py
index 2dcbaf38fa51a..785afce9e0214 100644
--- a/pandas/io/pickle.py
+++ b/pandas/io/pickle.py
@@ -3,7 +3,11 @@
from typing import Any
import warnings
-from pandas._typing import CompressionOptions, FilePathOrBuffer, StorageOptions
+from pandas._typing import (
+ CompressionOptions,
+ FilePathOrBuffer,
+ StorageOptions,
+)
from pandas.compat import pickle_compat as pc
from pandas.util._decorators import doc
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 077686d9bd642..88b444acfea62 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -6,7 +6,10 @@
from contextlib import suppress
import copy
-from datetime import date, tzinfo
+from datetime import (
+ date,
+ tzinfo,
+)
import itertools
import os
import re
@@ -29,11 +32,23 @@
import numpy as np
-from pandas._config import config, get_option
+from pandas._config import (
+ config,
+ get_option,
+)
-from pandas._libs import lib, writers as libwriters
+from pandas._libs import (
+ lib,
+ writers as libwriters,
+)
from pandas._libs.tslibs import timezones
-from pandas._typing import ArrayLike, DtypeArg, FrameOrSeries, FrameOrSeriesUnion, Shape
+from pandas._typing import (
+ ArrayLike,
+ DtypeArg,
+ FrameOrSeries,
+ FrameOrSeriesUnion,
+ Shape,
+)
from pandas.compat._optional import import_optional_dependency
from pandas.compat.pickle_compat import patch_pickle
from pandas.errors import PerformanceWarning
@@ -65,18 +80,32 @@
concat,
isna,
)
-from pandas.core.arrays import Categorical, DatetimeArray, PeriodArray
+from pandas.core.arrays import (
+ Categorical,
+ DatetimeArray,
+ PeriodArray,
+)
import pandas.core.common as com
-from pandas.core.computation.pytables import PyTablesExpr, maybe_expression
+from pandas.core.computation.pytables import (
+ PyTablesExpr,
+ maybe_expression,
+)
from pandas.core.construction import extract_array
from pandas.core.indexes.api import ensure_index
from pandas.core.internals import BlockManager
from pandas.io.common import stringify_path
-from pandas.io.formats.printing import adjoin, pprint_thing
+from pandas.io.formats.printing import (
+ adjoin,
+ pprint_thing,
+)
if TYPE_CHECKING:
- from tables import Col, File, Node
+ from tables import (
+ Col,
+ File,
+ Node,
+ )
from pandas.core.internals import Block
diff --git a/pandas/io/sas/sas7bdat.py b/pandas/io/sas/sas7bdat.py
index 9853fa41d3fb9..392dfa22ee67b 100644
--- a/pandas/io/sas/sas7bdat.py
+++ b/pandas/io/sas/sas7bdat.py
@@ -14,13 +14,24 @@
http://collaboration.cmc.ec.gc.ca/science/rpn/biblio/ddj/Website/articles/CUJ/1992/9210/ross/ross.htm
"""
from collections import abc
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import struct
-from typing import IO, Any, Union, cast
+from typing import (
+ IO,
+ Any,
+ Union,
+ cast,
+)
import numpy as np
-from pandas.errors import EmptyDataError, OutOfBoundsDatetime
+from pandas.errors import (
+ EmptyDataError,
+ OutOfBoundsDatetime,
+)
import pandas as pd
from pandas import isna
diff --git a/pandas/io/sas/sas_xport.py b/pandas/io/sas/sas_xport.py
index 2ecfbed8cc83f..c71de542bbf77 100644
--- a/pandas/io/sas/sas_xport.py
+++ b/pandas/io/sas/sas_xport.py
@@ -10,7 +10,10 @@
from collections import abc
from datetime import datetime
import struct
-from typing import IO, cast
+from typing import (
+ IO,
+ cast,
+)
import warnings
import numpy as np
diff --git a/pandas/io/sas/sasreader.py b/pandas/io/sas/sasreader.py
index 8888be02dd5ea..69da038929482 100644
--- a/pandas/io/sas/sasreader.py
+++ b/pandas/io/sas/sasreader.py
@@ -3,8 +3,17 @@
"""
from __future__ import annotations
-from abc import ABCMeta, abstractmethod
-from typing import TYPE_CHECKING, Hashable, Optional, Union, overload
+from abc import (
+ ABCMeta,
+ abstractmethod,
+)
+from typing import (
+ TYPE_CHECKING,
+ Hashable,
+ Optional,
+ Union,
+ overload,
+)
from pandas._typing import FilePathOrBuffer
diff --git a/pandas/io/spss.py b/pandas/io/spss.py
index 79cdfbf15392a..fb0ecee995463 100644
--- a/pandas/io/spss.py
+++ b/pandas/io/spss.py
@@ -1,5 +1,9 @@
from pathlib import Path
-from typing import Optional, Sequence, Union
+from typing import (
+ Optional,
+ Sequence,
+ Union,
+)
from pandas.compat._optional import import_optional_dependency
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index 725cb633918e7..c028e1f5c5dbe 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -4,10 +4,24 @@
"""
from contextlib import contextmanager
-from datetime import date, datetime, time
+from datetime import (
+ date,
+ datetime,
+ time,
+)
from functools import partial
import re
-from typing import Any, Dict, Iterator, List, Optional, Sequence, Union, cast, overload
+from typing import (
+ Any,
+ Dict,
+ Iterator,
+ List,
+ Optional,
+ Sequence,
+ Union,
+ cast,
+ overload,
+)
import warnings
import numpy as np
@@ -15,11 +29,18 @@
import pandas._libs.lib as lib
from pandas._typing import DtypeArg
-from pandas.core.dtypes.common import is_datetime64tz_dtype, is_dict_like, is_list_like
+from pandas.core.dtypes.common import (
+ is_datetime64tz_dtype,
+ is_dict_like,
+ is_list_like,
+)
from pandas.core.dtypes.dtypes import DatetimeTZDtype
from pandas.core.dtypes.missing import isna
-from pandas.core.api import DataFrame, Series
+from pandas.core.api import (
+ DataFrame,
+ Series,
+)
from pandas.core.base import PandasObject
from pandas.core.tools.datetimes import to_datetime
@@ -1036,7 +1057,11 @@ def _get_column_names_and_types(self, dtype_mapper):
return column_names_and_types
def _create_table_setup(self):
- from sqlalchemy import Column, PrimaryKeyConstraint, Table
+ from sqlalchemy import (
+ Column,
+ PrimaryKeyConstraint,
+ Table,
+ )
column_names_and_types = self._get_column_names_and_types(self._sqlalchemy_type)
@@ -1186,7 +1211,14 @@ def _sqlalchemy_type(self, col):
return Text
def _get_dtype(self, sqltype):
- from sqlalchemy.types import TIMESTAMP, Boolean, Date, DateTime, Float, Integer
+ from sqlalchemy.types import (
+ TIMESTAMP,
+ Boolean,
+ Date,
+ DateTime,
+ Float,
+ Integer,
+ )
if isinstance(sqltype, Float):
return float
@@ -1517,7 +1549,10 @@ def to_sql(
else:
dtype = cast(dict, dtype)
- from sqlalchemy.types import TypeEngine, to_instance
+ from sqlalchemy.types import (
+ TypeEngine,
+ to_instance,
+ )
for col, my_type in dtype.items():
if not isinstance(to_instance(my_type), TypeEngine):
diff --git a/pandas/io/stata.py b/pandas/io/stata.py
index 8f8c435fae4f3..462c7b41f4271 100644
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -36,8 +36,16 @@
from pandas._libs.lib import infer_dtype
from pandas._libs.writers import max_len_string_array
-from pandas._typing import Buffer, CompressionOptions, FilePathOrBuffer, StorageOptions
-from pandas.util._decorators import Appender, doc
+from pandas._typing import (
+ Buffer,
+ CompressionOptions,
+ FilePathOrBuffer,
+ StorageOptions,
+)
+from pandas.util._decorators import (
+ Appender,
+ doc,
+)
from pandas.core.dtypes.common import (
ensure_object,
diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py
index 597217ec67b0e..1a5efee586ee1 100644
--- a/pandas/plotting/_core.py
+++ b/pandas/plotting/_core.py
@@ -1,15 +1,30 @@
from __future__ import annotations
import importlib
-from typing import TYPE_CHECKING, Optional, Sequence, Tuple, Union
+from typing import (
+ TYPE_CHECKING,
+ Optional,
+ Sequence,
+ Tuple,
+ Union,
+)
from pandas._config import get_option
from pandas._typing import IndexLabel
-from pandas.util._decorators import Appender, Substitution
-
-from pandas.core.dtypes.common import is_integer, is_list_like
-from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
+from pandas.util._decorators import (
+ Appender,
+ Substitution,
+)
+
+from pandas.core.dtypes.common import (
+ is_integer,
+ is_list_like,
+)
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCSeries,
+)
from pandas.core.base import PandasObject
diff --git a/pandas/plotting/_matplotlib/__init__.py b/pandas/plotting/_matplotlib/__init__.py
index e212127549355..b12ca6187c945 100644
--- a/pandas/plotting/_matplotlib/__init__.py
+++ b/pandas/plotting/_matplotlib/__init__.py
@@ -1,6 +1,10 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Dict, Type
+from typing import (
+ TYPE_CHECKING,
+ Dict,
+ Type,
+)
from pandas.plotting._matplotlib.boxplot import (
BoxPlot,
@@ -8,7 +12,10 @@
boxplot_frame,
boxplot_frame_groupby,
)
-from pandas.plotting._matplotlib.converter import deregister, register
+from pandas.plotting._matplotlib.converter import (
+ deregister,
+ register,
+)
from pandas.plotting._matplotlib.core import (
AreaPlot,
BarhPlot,
@@ -18,7 +25,12 @@
PiePlot,
ScatterPlot,
)
-from pandas.plotting._matplotlib.hist import HistPlot, KdePlot, hist_frame, hist_series
+from pandas.plotting._matplotlib.hist import (
+ HistPlot,
+ KdePlot,
+ hist_frame,
+ hist_series,
+)
from pandas.plotting._matplotlib.misc import (
andrews_curves,
autocorrelation_plot,
diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py
index eec4c409a81b6..1ec4efe7b4795 100644
--- a/pandas/plotting/_matplotlib/boxplot.py
+++ b/pandas/plotting/_matplotlib/boxplot.py
@@ -14,7 +14,10 @@
import pandas.core.common as com
from pandas.io.formats.printing import pprint_thing
-from pandas.plotting._matplotlib.core import LinePlot, MPLPlot
+from pandas.plotting._matplotlib.core import (
+ LinePlot,
+ MPLPlot,
+)
from pandas.plotting._matplotlib.style import get_standard_colors
from pandas.plotting._matplotlib.tools import (
create_subplots,
diff --git a/pandas/plotting/_matplotlib/converter.py b/pandas/plotting/_matplotlib/converter.py
index 3d2d69162c70a..677c3e791c72b 100644
--- a/pandas/plotting/_matplotlib/converter.py
+++ b/pandas/plotting/_matplotlib/converter.py
@@ -1,18 +1,35 @@
import contextlib
import datetime as pydt
-from datetime import datetime, timedelta, tzinfo
+from datetime import (
+ datetime,
+ timedelta,
+ tzinfo,
+)
import functools
-from typing import Any, Dict, List, Optional, Tuple
+from typing import (
+ Any,
+ Dict,
+ List,
+ Optional,
+ Tuple,
+)
from dateutil.relativedelta import relativedelta
import matplotlib.dates as dates
-from matplotlib.ticker import AutoLocator, Formatter, Locator
+from matplotlib.ticker import (
+ AutoLocator,
+ Formatter,
+ Locator,
+)
from matplotlib.transforms import nonsingular
import matplotlib.units as units
import numpy as np
from pandas._libs import lib
-from pandas._libs.tslibs import Timestamp, to_offset
+from pandas._libs.tslibs import (
+ Timestamp,
+ to_offset,
+)
from pandas._libs.tslibs.dtypes import FreqGroup
from pandas._libs.tslibs.offsets import BaseOffset
@@ -24,10 +41,18 @@
is_nested_list_like,
)
-from pandas import Index, Series, get_option
+from pandas import (
+ Index,
+ Series,
+ get_option,
+)
import pandas.core.common as com
from pandas.core.indexes.datetimes import date_range
-from pandas.core.indexes.period import Period, PeriodIndex, period_range
+from pandas.core.indexes.period import (
+ Period,
+ PeriodIndex,
+ period_range,
+)
import pandas.core.tools.datetimes as tools
# constants
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py
index 2b6dd5347c3e7..3b0d59501ba05 100644
--- a/pandas/plotting/_matplotlib/core.py
+++ b/pandas/plotting/_matplotlib/core.py
@@ -1,6 +1,12 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Hashable, List, Optional, Tuple
+from typing import (
+ TYPE_CHECKING,
+ Hashable,
+ List,
+ Optional,
+ Tuple,
+)
import warnings
from matplotlib.artist import Artist
@@ -29,7 +35,10 @@
ABCPeriodIndex,
ABCSeries,
)
-from pandas.core.dtypes.missing import isna, notna
+from pandas.core.dtypes.missing import (
+ isna,
+ notna,
+)
import pandas.core.common as com
diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py
index 018d19e81d5c4..3de467c77d289 100644
--- a/pandas/plotting/_matplotlib/hist.py
+++ b/pandas/plotting/_matplotlib/hist.py
@@ -4,12 +4,24 @@
import numpy as np
-from pandas.core.dtypes.common import is_integer, is_list_like
-from pandas.core.dtypes.generic import ABCDataFrame, ABCIndex
-from pandas.core.dtypes.missing import isna, remove_na_arraylike
+from pandas.core.dtypes.common import (
+ is_integer,
+ is_list_like,
+)
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCIndex,
+)
+from pandas.core.dtypes.missing import (
+ isna,
+ remove_na_arraylike,
+)
from pandas.io.formats.printing import pprint_thing
-from pandas.plotting._matplotlib.core import LinePlot, MPLPlot
+from pandas.plotting._matplotlib.core import (
+ LinePlot,
+ MPLPlot,
+)
from pandas.plotting._matplotlib.tools import (
create_subplots,
flatten_axes,
diff --git a/pandas/plotting/_matplotlib/misc.py b/pandas/plotting/_matplotlib/misc.py
index 01ac3de4ff3bb..3d5f4af72db6c 100644
--- a/pandas/plotting/_matplotlib/misc.py
+++ b/pandas/plotting/_matplotlib/misc.py
@@ -1,7 +1,14 @@
from __future__ import annotations
import random
-from typing import TYPE_CHECKING, Dict, Hashable, List, Optional, Set
+from typing import (
+ TYPE_CHECKING,
+ Dict,
+ Hashable,
+ List,
+ Optional,
+ Set,
+)
import matplotlib.lines as mlines
import matplotlib.patches as patches
@@ -22,7 +29,10 @@
from matplotlib.axes import Axes
from matplotlib.figure import Figure
- from pandas import DataFrame, Series
+ from pandas import (
+ DataFrame,
+ Series,
+ )
def scatter_matrix(
diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py
index 51916075018a3..8374988708701 100644
--- a/pandas/plotting/_matplotlib/timeseries.py
+++ b/pandas/plotting/_matplotlib/timeseries.py
@@ -3,11 +3,19 @@
from __future__ import annotations
import functools
-from typing import TYPE_CHECKING, Optional, cast
+from typing import (
+ TYPE_CHECKING,
+ Optional,
+ cast,
+)
import numpy as np
-from pandas._libs.tslibs import BaseOffset, Period, to_offset
+from pandas._libs.tslibs import (
+ BaseOffset,
+ Period,
+ to_offset,
+)
from pandas._libs.tslibs.dtypes import FreqGroup
from pandas._typing import FrameOrSeriesUnion
@@ -23,12 +31,20 @@
TimeSeries_DateLocator,
TimeSeries_TimedeltaFormatter,
)
-from pandas.tseries.frequencies import get_period_alias, is_subperiod, is_superperiod
+from pandas.tseries.frequencies import (
+ get_period_alias,
+ is_subperiod,
+ is_superperiod,
+)
if TYPE_CHECKING:
from matplotlib.axes import Axes
- from pandas import DatetimeIndex, Index, Series
+ from pandas import (
+ DatetimeIndex,
+ Index,
+ Series,
+ )
# ---------------------------------------------------------------------
# Plotting functions and monkey patches
diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py
index df94b71f5e7a9..500d570835493 100644
--- a/pandas/plotting/_matplotlib/tools.py
+++ b/pandas/plotting/_matplotlib/tools.py
@@ -2,7 +2,14 @@
from __future__ import annotations
from math import ceil
-from typing import TYPE_CHECKING, Iterable, List, Sequence, Tuple, Union
+from typing import (
+ TYPE_CHECKING,
+ Iterable,
+ List,
+ Sequence,
+ Tuple,
+ Union,
+)
import warnings
import matplotlib.table
@@ -12,7 +19,11 @@
from pandas._typing import FrameOrSeriesUnion
from pandas.core.dtypes.common import is_list_like
-from pandas.core.dtypes.generic import ABCDataFrame, ABCIndex, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCDataFrame,
+ ABCIndex,
+ ABCSeries,
+)
from pandas.plotting._matplotlib import compat
diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py
index dd8904674428f..3ac9d98874f86 100644
--- a/pandas/tests/apply/test_frame_apply.py
+++ b/pandas/tests/apply/test_frame_apply.py
@@ -8,7 +8,14 @@
from pandas.core.dtypes.dtypes import CategoricalDtype
import pandas as pd
-from pandas import DataFrame, MultiIndex, Series, Timestamp, date_range, notna
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+ Timestamp,
+ date_range,
+ notna,
+)
import pandas._testing as tm
from pandas.core.base import SpecificationError
from pandas.tests.frame.common import zip_frames
diff --git a/pandas/tests/apply/test_frame_transform.py b/pandas/tests/apply/test_frame_transform.py
index c4959ee2c8962..6cee8b8a4b440 100644
--- a/pandas/tests/apply/test_frame_transform.py
+++ b/pandas/tests/apply/test_frame_transform.py
@@ -4,7 +4,11 @@
import numpy as np
import pytest
-from pandas import DataFrame, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
from pandas.core.base import SpecificationError
from pandas.core.groupby.base import transformation_kernels
diff --git a/pandas/tests/apply/test_series_apply.py b/pandas/tests/apply/test_series_apply.py
index a5c40af5c7f35..bf8311f992ea5 100644
--- a/pandas/tests/apply/test_series_apply.py
+++ b/pandas/tests/apply/test_series_apply.py
@@ -1,4 +1,7 @@
-from collections import Counter, defaultdict
+from collections import (
+ Counter,
+ defaultdict,
+)
from itertools import chain
import numpy as np
@@ -7,7 +10,15 @@
from pandas.core.dtypes.common import is_number
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series, concat, isna, timedelta_range
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ concat,
+ isna,
+ timedelta_range,
+)
import pandas._testing as tm
from pandas.core.base import SpecificationError
diff --git a/pandas/tests/apply/test_series_transform.py b/pandas/tests/apply/test_series_transform.py
index 73cc789c6eb3a..e67ea4f14e4ac 100644
--- a/pandas/tests/apply/test_series_transform.py
+++ b/pandas/tests/apply/test_series_transform.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import Series, concat
+from pandas import (
+ Series,
+ concat,
+)
import pandas._testing as tm
from pandas.core.base import SpecificationError
from pandas.core.groupby.base import transformation_kernels
diff --git a/pandas/tests/arithmetic/common.py b/pandas/tests/arithmetic/common.py
index e26bb513838a5..386490623dc47 100644
--- a/pandas/tests/arithmetic/common.py
+++ b/pandas/tests/arithmetic/common.py
@@ -4,7 +4,12 @@
import numpy as np
import pytest
-from pandas import DataFrame, Index, Series, array as pd_array
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ array as pd_array,
+)
import pandas._testing as tm
from pandas.core.arrays import PandasArray
diff --git a/pandas/tests/arithmetic/conftest.py b/pandas/tests/arithmetic/conftest.py
index f507c6d4f45fb..d90592c68e351 100644
--- a/pandas/tests/arithmetic/conftest.py
+++ b/pandas/tests/arithmetic/conftest.py
@@ -2,7 +2,12 @@
import pytest
import pandas as pd
-from pandas import Float64Index, Int64Index, RangeIndex, UInt64Index
+from pandas import (
+ Float64Index,
+ Int64Index,
+ RangeIndex,
+ UInt64Index,
+)
import pandas._testing as tm
# ------------------------------------------------------------------
diff --git a/pandas/tests/arithmetic/test_array_ops.py b/pandas/tests/arithmetic/test_array_ops.py
index 53cb10ba9fc5e..2c347d965bbf7 100644
--- a/pandas/tests/arithmetic/test_array_ops.py
+++ b/pandas/tests/arithmetic/test_array_ops.py
@@ -4,7 +4,10 @@
import pytest
import pandas._testing as tm
-from pandas.core.ops.array_ops import comparison_op, na_logical_op
+from pandas.core.ops.array_ops import (
+ comparison_op,
+ na_logical_op,
+)
def test_na_logical_op_2d():
diff --git a/pandas/tests/arithmetic/test_categorical.py b/pandas/tests/arithmetic/test_categorical.py
index a978f763fbaaa..924f32b5ac9ac 100644
--- a/pandas/tests/arithmetic/test_categorical.py
+++ b/pandas/tests/arithmetic/test_categorical.py
@@ -1,6 +1,9 @@
import numpy as np
-from pandas import Categorical, Series
+from pandas import (
+ Categorical,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py
index b2d88b3556388..423d20c46bdb1 100644
--- a/pandas/tests/arithmetic/test_datetime64.py
+++ b/pandas/tests/arithmetic/test_datetime64.py
@@ -1,8 +1,15 @@
# Arithmetic tests for DataFrame/Series/Index/Array classes that should
# behave identically.
# Specifically for datetime64 and datetime64tz dtypes
-from datetime import datetime, time, timedelta
-from itertools import product, starmap
+from datetime import (
+ datetime,
+ time,
+ timedelta,
+)
+from itertools import (
+ product,
+ starmap,
+)
import operator
import warnings
@@ -28,7 +35,10 @@
date_range,
)
import pandas._testing as tm
-from pandas.core.arrays import DatetimeArray, TimedeltaArray
+from pandas.core.arrays import (
+ DatetimeArray,
+ TimedeltaArray,
+)
from pandas.core.ops import roperator
from pandas.tests.arithmetic.common import (
assert_invalid_addsub_type,
diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py
index f4f258b559939..a41ecd5835e65 100644
--- a/pandas/tests/arithmetic/test_numeric.py
+++ b/pandas/tests/arithmetic/test_numeric.py
@@ -5,7 +5,10 @@
from decimal import Decimal
from itertools import combinations
import operator
-from typing import Any, List
+from typing import (
+ Any,
+ List,
+)
import numpy as np
import pytest
diff --git a/pandas/tests/arithmetic/test_object.py b/pandas/tests/arithmetic/test_object.py
index a31c2e6d8c258..c5e086d24ec0c 100644
--- a/pandas/tests/arithmetic/test_object.py
+++ b/pandas/tests/arithmetic/test_object.py
@@ -9,7 +9,10 @@
import pytest
import pandas as pd
-from pandas import Series, Timestamp
+from pandas import (
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
from pandas.core import ops
diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py
index 4a2e8ba8219aa..f0c03fee50b39 100644
--- a/pandas/tests/arithmetic/test_period.py
+++ b/pandas/tests/arithmetic/test_period.py
@@ -6,11 +6,22 @@
import numpy as np
import pytest
-from pandas._libs.tslibs import IncompatibleFrequency, Period, Timestamp, to_offset
+from pandas._libs.tslibs import (
+ IncompatibleFrequency,
+ Period,
+ Timestamp,
+ to_offset,
+)
from pandas.errors import PerformanceWarning
import pandas as pd
-from pandas import PeriodIndex, Series, Timedelta, TimedeltaIndex, period_range
+from pandas import (
+ PeriodIndex,
+ Series,
+ Timedelta,
+ TimedeltaIndex,
+ period_range,
+)
import pandas._testing as tm
from pandas.core import ops
from pandas.core.arrays import TimedeltaArray
diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py
index 740ec3be4a1c6..75e17e13ad864 100644
--- a/pandas/tests/arithmetic/test_timedelta64.py
+++ b/pandas/tests/arithmetic/test_timedelta64.py
@@ -1,11 +1,17 @@
# Arithmetic tests for DataFrame/Series/Index/Array classes that should
# behave identically.
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import numpy as np
import pytest
-from pandas.errors import OutOfBoundsDatetime, PerformanceWarning
+from pandas.errors import (
+ OutOfBoundsDatetime,
+ PerformanceWarning,
+)
import pandas as pd
from pandas import (
diff --git a/pandas/tests/arrays/categorical/test_analytics.py b/pandas/tests/arrays/categorical/test_analytics.py
index abf4ddd681d69..6899d821f80ad 100644
--- a/pandas/tests/arrays/categorical/test_analytics.py
+++ b/pandas/tests/arrays/categorical/test_analytics.py
@@ -6,7 +6,13 @@
from pandas.compat import PYPY
-from pandas import Categorical, Index, NaT, Series, date_range
+from pandas import (
+ Categorical,
+ Index,
+ NaT,
+ Series,
+ date_range,
+)
import pandas._testing as tm
from pandas.api.types import is_scalar
diff --git a/pandas/tests/arrays/categorical/test_api.py b/pandas/tests/arrays/categorical/test_api.py
index 98b0f978c5f59..a6dea639488a2 100644
--- a/pandas/tests/arrays/categorical/test_api.py
+++ b/pandas/tests/arrays/categorical/test_api.py
@@ -3,7 +3,13 @@
import numpy as np
import pytest
-from pandas import Categorical, CategoricalIndex, DataFrame, Index, Series
+from pandas import (
+ Categorical,
+ CategoricalIndex,
+ DataFrame,
+ Index,
+ Series,
+)
import pandas._testing as tm
from pandas.core.arrays.categorical import recode_for_categories
from pandas.tests.arrays.categorical.common import TestCategorical
diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py
index 556f8c24f2ab1..7c144c390a128 100644
--- a/pandas/tests/arrays/categorical/test_constructors.py
+++ b/pandas/tests/arrays/categorical/test_constructors.py
@@ -1,11 +1,20 @@
-from datetime import date, datetime
+from datetime import (
+ date,
+ datetime,
+)
import numpy as np
import pytest
-from pandas.compat import IS64, is_platform_windows
+from pandas.compat import (
+ IS64,
+ is_platform_windows,
+)
-from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype
+from pandas.core.dtypes.common import (
+ is_float_dtype,
+ is_integer_dtype,
+)
from pandas.core.dtypes.dtypes import CategoricalDtype
import pandas as pd
diff --git a/pandas/tests/arrays/categorical/test_dtypes.py b/pandas/tests/arrays/categorical/test_dtypes.py
index 6be9a424a5544..209891ba8f043 100644
--- a/pandas/tests/arrays/categorical/test_dtypes.py
+++ b/pandas/tests/arrays/categorical/test_dtypes.py
@@ -3,7 +3,13 @@
from pandas.core.dtypes.dtypes import CategoricalDtype
-from pandas import Categorical, CategoricalIndex, Index, Series, Timestamp
+from pandas import (
+ Categorical,
+ CategoricalIndex,
+ Index,
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
diff --git a/pandas/tests/arrays/categorical/test_missing.py b/pandas/tests/arrays/categorical/test_missing.py
index 36ed790eff63c..0a35f490ff210 100644
--- a/pandas/tests/arrays/categorical/test_missing.py
+++ b/pandas/tests/arrays/categorical/test_missing.py
@@ -6,7 +6,13 @@
from pandas.core.dtypes.dtypes import CategoricalDtype
import pandas as pd
-from pandas import Categorical, DataFrame, Index, Series, isna
+from pandas import (
+ Categorical,
+ DataFrame,
+ Index,
+ Series,
+ isna,
+)
import pandas._testing as tm
diff --git a/pandas/tests/arrays/categorical/test_operators.py b/pandas/tests/arrays/categorical/test_operators.py
index 328b5771e617c..4a00df2d783cf 100644
--- a/pandas/tests/arrays/categorical/test_operators.py
+++ b/pandas/tests/arrays/categorical/test_operators.py
@@ -5,7 +5,12 @@
import pytest
import pandas as pd
-from pandas import Categorical, DataFrame, Series, date_range
+from pandas import (
+ Categorical,
+ DataFrame,
+ Series,
+ date_range,
+)
import pandas._testing as tm
from pandas.tests.arrays.categorical.common import TestCategorical
diff --git a/pandas/tests/arrays/categorical/test_sorting.py b/pandas/tests/arrays/categorical/test_sorting.py
index 9589216557cd5..4f65c8dfaf0be 100644
--- a/pandas/tests/arrays/categorical/test_sorting.py
+++ b/pandas/tests/arrays/categorical/test_sorting.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import Categorical, Index
+from pandas import (
+ Categorical,
+ Index,
+)
import pandas._testing as tm
diff --git a/pandas/tests/arrays/categorical/test_take.py b/pandas/tests/arrays/categorical/test_take.py
index 97d9db483c401..6cb54908724c9 100644
--- a/pandas/tests/arrays/categorical/test_take.py
+++ b/pandas/tests/arrays/categorical/test_take.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import Categorical, Index
+from pandas import (
+ Categorical,
+ Index,
+)
import pandas._testing as tm
diff --git a/pandas/tests/arrays/floating/conftest.py b/pandas/tests/arrays/floating/conftest.py
index 1e80518e15941..9eab11516c295 100644
--- a/pandas/tests/arrays/floating/conftest.py
+++ b/pandas/tests/arrays/floating/conftest.py
@@ -2,7 +2,10 @@
import pytest
import pandas as pd
-from pandas.core.arrays.floating import Float32Dtype, Float64Dtype
+from pandas.core.arrays.floating import (
+ Float32Dtype,
+ Float64Dtype,
+)
@pytest.fixture(params=[Float32Dtype, Float64Dtype])
diff --git a/pandas/tests/arrays/floating/test_construction.py b/pandas/tests/arrays/floating/test_construction.py
index a3eade98d99d6..4ce3dd35b538b 100644
--- a/pandas/tests/arrays/floating/test_construction.py
+++ b/pandas/tests/arrays/floating/test_construction.py
@@ -4,7 +4,10 @@
import pandas as pd
import pandas._testing as tm
from pandas.core.arrays import FloatingArray
-from pandas.core.arrays.floating import Float32Dtype, Float64Dtype
+from pandas.core.arrays.floating import (
+ Float32Dtype,
+ Float64Dtype,
+)
def test_uses_pandas_na():
diff --git a/pandas/tests/arrays/floating/test_repr.py b/pandas/tests/arrays/floating/test_repr.py
index 8767b79242c83..a8868fd93747a 100644
--- a/pandas/tests/arrays/floating/test_repr.py
+++ b/pandas/tests/arrays/floating/test_repr.py
@@ -2,7 +2,10 @@
import pytest
import pandas as pd
-from pandas.core.arrays.floating import Float32Dtype, Float64Dtype
+from pandas.core.arrays.floating import (
+ Float32Dtype,
+ Float64Dtype,
+)
def test_dtypes(dtype):
diff --git a/pandas/tests/arrays/integer/test_construction.py b/pandas/tests/arrays/integer/test_construction.py
index a7e31ede8e384..b48567d37ecaf 100644
--- a/pandas/tests/arrays/integer/test_construction.py
+++ b/pandas/tests/arrays/integer/test_construction.py
@@ -5,7 +5,11 @@
import pandas._testing as tm
from pandas.api.types import is_integer
from pandas.core.arrays import IntegerArray
-from pandas.core.arrays.integer import Int8Dtype, Int32Dtype, Int64Dtype
+from pandas.core.arrays.integer import (
+ Int8Dtype,
+ Int32Dtype,
+ Int64Dtype,
+)
@pytest.fixture(params=[pd.array, IntegerArray._from_sequence])
diff --git a/pandas/tests/arrays/integer/test_dtypes.py b/pandas/tests/arrays/integer/test_dtypes.py
index 457117c167749..e3f59205aa07c 100644
--- a/pandas/tests/arrays/integer/test_dtypes.py
+++ b/pandas/tests/arrays/integer/test_dtypes.py
@@ -5,7 +5,10 @@
import pandas as pd
import pandas._testing as tm
-from pandas.core.arrays.integer import Int8Dtype, UInt32Dtype
+from pandas.core.arrays.integer import (
+ Int8Dtype,
+ UInt32Dtype,
+)
def test_dtypes(dtype):
diff --git a/pandas/tests/arrays/interval/test_astype.py b/pandas/tests/arrays/interval/test_astype.py
index e118e40196e43..d7a2140f817f3 100644
--- a/pandas/tests/arrays/interval/test_astype.py
+++ b/pandas/tests/arrays/interval/test_astype.py
@@ -1,6 +1,11 @@
import pytest
-from pandas import Categorical, CategoricalDtype, Index, IntervalIndex
+from pandas import (
+ Categorical,
+ CategoricalDtype,
+ Index,
+ IntervalIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/arrays/interval/test_ops.py b/pandas/tests/arrays/interval/test_ops.py
index 9c78c2a48b9ff..4853bec51106c 100644
--- a/pandas/tests/arrays/interval/test_ops.py
+++ b/pandas/tests/arrays/interval/test_ops.py
@@ -2,7 +2,12 @@
import numpy as np
import pytest
-from pandas import Interval, IntervalIndex, Timedelta, Timestamp
+from pandas import (
+ Interval,
+ IntervalIndex,
+ Timedelta,
+ Timestamp,
+)
import pandas._testing as tm
from pandas.core.arrays import IntervalArray
diff --git a/pandas/tests/arrays/masked/test_arithmetic.py b/pandas/tests/arrays/masked/test_arithmetic.py
index 1d2833c5da276..88e11f57a7835 100644
--- a/pandas/tests/arrays/masked/test_arithmetic.py
+++ b/pandas/tests/arrays/masked/test_arithmetic.py
@@ -1,4 +1,7 @@
-from typing import Any, List
+from typing import (
+ Any,
+ List,
+)
import numpy as np
import pytest
diff --git a/pandas/tests/arrays/period/test_arrow_compat.py b/pandas/tests/arrays/period/test_arrow_compat.py
index 8dc9d2a996728..f4e803cf4405f 100644
--- a/pandas/tests/arrays/period/test_arrow_compat.py
+++ b/pandas/tests/arrays/period/test_arrow_compat.py
@@ -6,7 +6,10 @@
import pandas as pd
import pandas._testing as tm
-from pandas.core.arrays import PeriodArray, period_array
+from pandas.core.arrays import (
+ PeriodArray,
+ period_array,
+)
pyarrow_skip = pyarrow_skip = td.skip_if_no("pyarrow", min_version="0.15.1.dev")
diff --git a/pandas/tests/arrays/period/test_constructors.py b/pandas/tests/arrays/period/test_constructors.py
index 0a8a106767fb6..52543d91e8f2a 100644
--- a/pandas/tests/arrays/period/test_constructors.py
+++ b/pandas/tests/arrays/period/test_constructors.py
@@ -6,7 +6,10 @@
import pandas as pd
import pandas._testing as tm
-from pandas.core.arrays import PeriodArray, period_array
+from pandas.core.arrays import (
+ PeriodArray,
+ period_array,
+)
@pytest.mark.parametrize(
diff --git a/pandas/tests/arrays/sparse/test_accessor.py b/pandas/tests/arrays/sparse/test_accessor.py
index 4c6781509f8af..10f5a7e9a1dc4 100644
--- a/pandas/tests/arrays/sparse/test_accessor.py
+++ b/pandas/tests/arrays/sparse/test_accessor.py
@@ -7,7 +7,10 @@
import pandas as pd
import pandas._testing as tm
-from pandas.core.arrays.sparse import SparseArray, SparseDtype
+from pandas.core.arrays.sparse import (
+ SparseArray,
+ SparseDtype,
+)
class TestSeriesAccessor:
diff --git a/pandas/tests/arrays/sparse/test_arithmetics.py b/pandas/tests/arrays/sparse/test_arithmetics.py
index 6cc730ce49840..79cf8298ab1a6 100644
--- a/pandas/tests/arrays/sparse/test_arithmetics.py
+++ b/pandas/tests/arrays/sparse/test_arithmetics.py
@@ -8,7 +8,10 @@
import pandas as pd
import pandas._testing as tm
from pandas.core import ops
-from pandas.core.arrays.sparse import SparseArray, SparseDtype
+from pandas.core.arrays.sparse import (
+ SparseArray,
+ SparseDtype,
+)
@pytest.fixture(params=["integer", "block"])
diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py
index 7f1b0f49ebd1e..31522f24fc7a2 100644
--- a/pandas/tests/arrays/sparse/test_array.py
+++ b/pandas/tests/arrays/sparse/test_array.py
@@ -11,7 +11,10 @@
import pandas as pd
from pandas import isna
import pandas._testing as tm
-from pandas.core.arrays.sparse import SparseArray, SparseDtype
+from pandas.core.arrays.sparse import (
+ SparseArray,
+ SparseDtype,
+)
class TestSparseArray:
diff --git a/pandas/tests/arrays/sparse/test_libsparse.py b/pandas/tests/arrays/sparse/test_libsparse.py
index 992dff218415d..c1466882b8443 100644
--- a/pandas/tests/arrays/sparse/test_libsparse.py
+++ b/pandas/tests/arrays/sparse/test_libsparse.py
@@ -8,7 +8,11 @@
from pandas import Series
import pandas._testing as tm
-from pandas.core.arrays.sparse import BlockIndex, IntIndex, make_sparse_index
+from pandas.core.arrays.sparse import (
+ BlockIndex,
+ IntIndex,
+ make_sparse_index,
+)
TEST_LENGTH = 20
diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py
index 8c766b96ecb9a..d5254adc1ee24 100644
--- a/pandas/tests/arrays/string_/test_string.py
+++ b/pandas/tests/arrays/string_/test_string.py
@@ -9,7 +9,10 @@
import pandas as pd
import pandas._testing as tm
-from pandas.core.arrays.string_arrow import ArrowStringArray, ArrowStringDtype
+from pandas.core.arrays.string_arrow import (
+ ArrowStringArray,
+ ArrowStringDtype,
+)
skip_if_no_pyarrow = td.skip_if_no("pyarrow", min_version="1.0.0")
diff --git a/pandas/tests/arrays/test_array.py b/pandas/tests/arrays/test_array.py
index f14d5349dcea3..5d2b7c43f6765 100644
--- a/pandas/tests/arrays/test_array.py
+++ b/pandas/tests/arrays/test_array.py
@@ -21,8 +21,15 @@
StringArray,
TimedeltaArray,
)
-from pandas.core.arrays import PandasArray, period_array
-from pandas.tests.extension.decimal import DecimalArray, DecimalDtype, to_decimal
+from pandas.core.arrays import (
+ PandasArray,
+ period_array,
+)
+from pandas.tests.extension.decimal import (
+ DecimalArray,
+ DecimalDtype,
+ to_decimal,
+)
@pytest.mark.parametrize(
diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py
index b43812b8024bb..070dec307f527 100644
--- a/pandas/tests/arrays/test_datetimelike.py
+++ b/pandas/tests/arrays/test_datetimelike.py
@@ -1,16 +1,33 @@
import re
-from typing import Type, Union
+from typing import (
+ Type,
+ Union,
+)
import numpy as np
import pytest
-from pandas._libs import NaT, OutOfBoundsDatetime, Timestamp
+from pandas._libs import (
+ NaT,
+ OutOfBoundsDatetime,
+ Timestamp,
+)
from pandas.compat import np_version_under1p18
import pandas as pd
-from pandas import DatetimeIndex, Period, PeriodIndex, TimedeltaIndex
+from pandas import (
+ DatetimeIndex,
+ Period,
+ PeriodIndex,
+ TimedeltaIndex,
+)
import pandas._testing as tm
-from pandas.core.arrays import DatetimeArray, PandasArray, PeriodArray, TimedeltaArray
+from pandas.core.arrays import (
+ DatetimeArray,
+ PandasArray,
+ PeriodArray,
+ TimedeltaArray,
+)
# TODO: more freq variants
diff --git a/pandas/tests/arrays/test_period.py b/pandas/tests/arrays/test_period.py
index d044b191cf279..e7f3e8c659316 100644
--- a/pandas/tests/arrays/test_period.py
+++ b/pandas/tests/arrays/test_period.py
@@ -9,7 +9,10 @@
import pandas as pd
import pandas._testing as tm
-from pandas.core.arrays import PeriodArray, period_array
+from pandas.core.arrays import (
+ PeriodArray,
+ period_array,
+)
# ----------------------------------------------------------------------------
# Dtype
diff --git a/pandas/tests/base/test_constructors.py b/pandas/tests/base/test_constructors.py
index 697364fc87175..b042e29986c80 100644
--- a/pandas/tests/base/test_constructors.py
+++ b/pandas/tests/base/test_constructors.py
@@ -7,10 +7,17 @@
from pandas.compat import PYPY
import pandas as pd
-from pandas import DataFrame, Index, Series
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+)
import pandas._testing as tm
from pandas.core.accessor import PandasDelegate
-from pandas.core.base import NoNewAttributesMixin, PandasObject
+from pandas.core.base import (
+ NoNewAttributesMixin,
+ PandasObject,
+)
@pytest.fixture(
diff --git a/pandas/tests/base/test_conversion.py b/pandas/tests/base/test_conversion.py
index 67e519553517f..8be475d5a922a 100644
--- a/pandas/tests/base/test_conversion.py
+++ b/pandas/tests/base/test_conversion.py
@@ -1,11 +1,20 @@
import numpy as np
import pytest
-from pandas.core.dtypes.common import is_datetime64_dtype, is_timedelta64_dtype
+from pandas.core.dtypes.common import (
+ is_datetime64_dtype,
+ is_timedelta64_dtype,
+)
from pandas.core.dtypes.dtypes import DatetimeTZDtype
import pandas as pd
-from pandas import CategoricalIndex, Series, Timedelta, Timestamp, date_range
+from pandas import (
+ CategoricalIndex,
+ Series,
+ Timedelta,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
from pandas.core.arrays import (
DatetimeArray,
diff --git a/pandas/tests/base/test_misc.py b/pandas/tests/base/test_misc.py
index d02078814f60f..c0250e2b3e958 100644
--- a/pandas/tests/base/test_misc.py
+++ b/pandas/tests/base/test_misc.py
@@ -3,12 +3,22 @@
import numpy as np
import pytest
-from pandas.compat import IS64, PYPY
+from pandas.compat import (
+ IS64,
+ PYPY,
+)
-from pandas.core.dtypes.common import is_categorical_dtype, is_object_dtype
+from pandas.core.dtypes.common import (
+ is_categorical_dtype,
+ is_object_dtype,
+)
import pandas as pd
-from pandas import DataFrame, Index, Series
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+)
@pytest.mark.parametrize(
diff --git a/pandas/tests/base/test_unique.py b/pandas/tests/base/test_unique.py
index 1a554c85e018b..4aefa4be176fb 100644
--- a/pandas/tests/base/test_unique.py
+++ b/pandas/tests/base/test_unique.py
@@ -3,7 +3,10 @@
from pandas._libs import iNaT
-from pandas.core.dtypes.common import is_datetime64tz_dtype, needs_i8_conversion
+from pandas.core.dtypes.common import (
+ is_datetime64tz_dtype,
+ needs_i8_conversion,
+)
import pandas as pd
import pandas._testing as tm
diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py
index 37ee61417eeab..5b8179bdc10a9 100644
--- a/pandas/tests/computation/test_eval.py
+++ b/pandas/tests/computation/test_eval.py
@@ -2,31 +2,53 @@
from functools import reduce
from itertools import product
import operator
-from typing import Dict, List, Type
+from typing import (
+ Dict,
+ List,
+ Type,
+)
import warnings
import numpy as np
import pytest
-from pandas.compat import is_platform_windows, np_version_under1p17
+from pandas.compat import (
+ is_platform_windows,
+ np_version_under1p17,
+)
from pandas.errors import PerformanceWarning
import pandas.util._test_decorators as td
-from pandas.core.dtypes.common import is_bool, is_list_like, is_scalar
+from pandas.core.dtypes.common import (
+ is_bool,
+ is_list_like,
+ is_scalar,
+)
import pandas as pd
-from pandas import DataFrame, Series, compat, date_range
+from pandas import (
+ DataFrame,
+ Series,
+ compat,
+ date_range,
+)
import pandas._testing as tm
from pandas.core.computation import pytables
from pandas.core.computation.check import NUMEXPR_VERSION
-from pandas.core.computation.engines import ENGINES, NumExprClobberingError
+from pandas.core.computation.engines import (
+ ENGINES,
+ NumExprClobberingError,
+)
import pandas.core.computation.expr as expr
from pandas.core.computation.expr import (
BaseExprVisitor,
PandasExprVisitor,
PythonExprVisitor,
)
-from pandas.core.computation.expressions import NUMEXPR_INSTALLED, USE_NUMEXPR
+from pandas.core.computation.expressions import (
+ NUMEXPR_INSTALLED,
+ USE_NUMEXPR,
+)
from pandas.core.computation.ops import (
ARITH_OPS_SYMS,
SPECIAL_CASE_ARITH_OPS_SYMS,
diff --git a/pandas/tests/config/test_localization.py b/pandas/tests/config/test_localization.py
index e815a90207a08..21b1b7ed6ee65 100644
--- a/pandas/tests/config/test_localization.py
+++ b/pandas/tests/config/test_localization.py
@@ -4,7 +4,11 @@
import pytest
-from pandas._config.localization import can_set_locale, get_locales, set_locale
+from pandas._config.localization import (
+ can_set_locale,
+ get_locales,
+ set_locale,
+)
from pandas.compat import is_platform_windows
diff --git a/pandas/tests/dtypes/cast/test_construct_from_scalar.py b/pandas/tests/dtypes/cast/test_construct_from_scalar.py
index 4ff3375d1988d..eccd838a11331 100644
--- a/pandas/tests/dtypes/cast/test_construct_from_scalar.py
+++ b/pandas/tests/dtypes/cast/test_construct_from_scalar.py
@@ -4,7 +4,11 @@
from pandas.core.dtypes.cast import construct_1d_arraylike_from_scalar
from pandas.core.dtypes.dtypes import CategoricalDtype
-from pandas import Categorical, Timedelta, Timestamp
+from pandas import (
+ Categorical,
+ Timedelta,
+ Timestamp,
+)
import pandas._testing as tm
diff --git a/pandas/tests/dtypes/cast/test_downcast.py b/pandas/tests/dtypes/cast/test_downcast.py
index e9057e9635f37..0c3e9841eba3e 100644
--- a/pandas/tests/dtypes/cast/test_downcast.py
+++ b/pandas/tests/dtypes/cast/test_downcast.py
@@ -5,7 +5,11 @@
from pandas.core.dtypes.cast import maybe_downcast_to_dtype
-from pandas import DatetimeIndex, Series, Timestamp
+from pandas import (
+ DatetimeIndex,
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
diff --git a/pandas/tests/dtypes/cast/test_find_common_type.py b/pandas/tests/dtypes/cast/test_find_common_type.py
index 50f7c7c2e085a..8484b5525a92a 100644
--- a/pandas/tests/dtypes/cast/test_find_common_type.py
+++ b/pandas/tests/dtypes/cast/test_find_common_type.py
@@ -9,7 +9,10 @@
PeriodDtype,
)
-from pandas import Categorical, Index
+from pandas import (
+ Categorical,
+ Index,
+)
@pytest.mark.parametrize(
diff --git a/pandas/tests/dtypes/cast/test_infer_datetimelike.py b/pandas/tests/dtypes/cast/test_infer_datetimelike.py
index f4253e9d9e37b..3c3844e69586d 100644
--- a/pandas/tests/dtypes/cast/test_infer_datetimelike.py
+++ b/pandas/tests/dtypes/cast/test_infer_datetimelike.py
@@ -1,7 +1,12 @@
import numpy as np
import pytest
-from pandas import DataFrame, NaT, Series, Timestamp
+from pandas import (
+ DataFrame,
+ NaT,
+ Series,
+ Timestamp,
+)
@pytest.mark.parametrize(
diff --git a/pandas/tests/dtypes/cast/test_infer_dtype.py b/pandas/tests/dtypes/cast/test_infer_dtype.py
index 2b18d110346e4..b08dc82a48fe3 100644
--- a/pandas/tests/dtypes/cast/test_infer_dtype.py
+++ b/pandas/tests/dtypes/cast/test_infer_dtype.py
@@ -1,4 +1,8 @@
-from datetime import date, datetime, timedelta
+from datetime import (
+ date,
+ datetime,
+ timedelta,
+)
import numpy as np
import pytest
diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py
index c0a2a0c3a9897..bf83085058cfc 100644
--- a/pandas/tests/dtypes/test_dtypes.py
+++ b/pandas/tests/dtypes/test_dtypes.py
@@ -35,7 +35,10 @@
date_range,
)
import pandas._testing as tm
-from pandas.core.arrays.sparse import SparseArray, SparseDtype
+from pandas.core.arrays.sparse import (
+ SparseArray,
+ SparseDtype,
+)
class Base:
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py
index 0f4cef772458f..046256535df57 100644
--- a/pandas/tests/dtypes/test_inference.py
+++ b/pandas/tests/dtypes/test_inference.py
@@ -5,7 +5,12 @@
"""
import collections
from collections import namedtuple
-from datetime import date, datetime, time, timedelta
+from datetime import (
+ date,
+ datetime,
+ time,
+ timedelta,
+)
from decimal import Decimal
from fractions import Fraction
from io import StringIO
@@ -16,7 +21,10 @@
import pytest
import pytz
-from pandas._libs import lib, missing as libmissing
+from pandas._libs import (
+ lib,
+ missing as libmissing,
+)
import pandas.util._test_decorators as td
from pandas.core.dtypes import inference
diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py
index f6566d205e65c..57efe8e4840f1 100644
--- a/pandas/tests/dtypes/test_missing.py
+++ b/pandas/tests/dtypes/test_missing.py
@@ -8,10 +8,20 @@
from pandas._config import config as cf
from pandas._libs import missing as libmissing
-from pandas._libs.tslibs import iNaT, is_null_datetimelike
+from pandas._libs.tslibs import (
+ iNaT,
+ is_null_datetimelike,
+)
-from pandas.core.dtypes.common import is_float, is_scalar
-from pandas.core.dtypes.dtypes import DatetimeTZDtype, IntervalDtype, PeriodDtype
+from pandas.core.dtypes.common import (
+ is_float,
+ is_scalar,
+)
+from pandas.core.dtypes.dtypes import (
+ DatetimeTZDtype,
+ IntervalDtype,
+ PeriodDtype,
+)
from pandas.core.dtypes.missing import (
array_equivalent,
isna,
@@ -22,7 +32,14 @@
)
import pandas as pd
-from pandas import DatetimeIndex, Float64Index, NaT, Series, TimedeltaIndex, date_range
+from pandas import (
+ DatetimeIndex,
+ Float64Index,
+ NaT,
+ Series,
+ TimedeltaIndex,
+ date_range,
+)
import pandas._testing as tm
now = pd.Timestamp.now()
diff --git a/pandas/tests/extension/arrow/test_timestamp.py b/pandas/tests/extension/arrow/test_timestamp.py
index 10e560b34a21c..819e5549d05ae 100644
--- a/pandas/tests/extension/arrow/test_timestamp.py
+++ b/pandas/tests/extension/arrow/test_timestamp.py
@@ -6,7 +6,10 @@
import pytest
import pandas as pd
-from pandas.api.extensions import ExtensionDtype, register_extension_dtype
+from pandas.api.extensions import (
+ ExtensionDtype,
+ register_extension_dtype,
+)
pytest.importorskip("pyarrow", minversion="0.13.0")
diff --git a/pandas/tests/extension/base/dtype.py b/pandas/tests/extension/base/dtype.py
index b63af0c22b450..ea4443010c6a6 100644
--- a/pandas/tests/extension/base/dtype.py
+++ b/pandas/tests/extension/base/dtype.py
@@ -4,7 +4,11 @@
import pytest
import pandas as pd
-from pandas.api.types import infer_dtype, is_object_dtype, is_string_dtype
+from pandas.api.types import (
+ infer_dtype,
+ is_object_dtype,
+ is_string_dtype,
+)
from pandas.tests.extension.base.base import BaseExtensionTests
diff --git a/pandas/tests/extension/base/ops.py b/pandas/tests/extension/base/ops.py
index bae8e9df72d41..2a27f670fa046 100644
--- a/pandas/tests/extension/base/ops.py
+++ b/pandas/tests/extension/base/ops.py
@@ -1,4 +1,7 @@
-from typing import Optional, Type
+from typing import (
+ Optional,
+ Type,
+)
import pytest
diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py
index c7976c5800173..9e1c517704743 100644
--- a/pandas/tests/extension/decimal/array.py
+++ b/pandas/tests/extension/decimal/array.py
@@ -9,13 +9,26 @@
import numpy as np
from pandas.core.dtypes.base import ExtensionDtype
-from pandas.core.dtypes.common import is_dtype_equal, is_float, pandas_dtype
+from pandas.core.dtypes.common import (
+ is_dtype_equal,
+ is_float,
+ pandas_dtype,
+)
import pandas as pd
-from pandas.api.extensions import no_default, register_extension_dtype
-from pandas.api.types import is_list_like, is_scalar
+from pandas.api.extensions import (
+ no_default,
+ register_extension_dtype,
+)
+from pandas.api.types import (
+ is_list_like,
+ is_scalar,
+)
from pandas.core.arraylike import OpsMixin
-from pandas.core.arrays import ExtensionArray, ExtensionScalarOpsMixin
+from pandas.core.arrays import (
+ ExtensionArray,
+ ExtensionScalarOpsMixin,
+)
from pandas.core.indexers import check_array_indexer
diff --git a/pandas/tests/extension/json/__init__.py b/pandas/tests/extension/json/__init__.py
index b6402b6c09526..7ebfd54a5b0d6 100644
--- a/pandas/tests/extension/json/__init__.py
+++ b/pandas/tests/extension/json/__init__.py
@@ -1,3 +1,7 @@
-from pandas.tests.extension.json.array import JSONArray, JSONDtype, make_data
+from pandas.tests.extension.json.array import (
+ JSONArray,
+ JSONDtype,
+ make_data,
+)
__all__ = ["JSONArray", "JSONDtype", "make_data"]
diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py
index 5fcfe4faac55a..ca593da6d97bc 100644
--- a/pandas/tests/extension/json/array.py
+++ b/pandas/tests/extension/json/array.py
@@ -13,20 +13,30 @@
"""
from __future__ import annotations
-from collections import UserDict, abc
+from collections import (
+ UserDict,
+ abc,
+)
import itertools
import numbers
import random
import string
import sys
-from typing import Any, Mapping, Type
+from typing import (
+ Any,
+ Mapping,
+ Type,
+)
import numpy as np
from pandas.core.dtypes.common import pandas_dtype
import pandas as pd
-from pandas.api.extensions import ExtensionArray, ExtensionDtype
+from pandas.api.extensions import (
+ ExtensionArray,
+ ExtensionDtype,
+)
from pandas.api.types import is_bool_dtype
diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py
index 90a39f3b33e95..b8fa158083327 100644
--- a/pandas/tests/extension/json/test_json.py
+++ b/pandas/tests/extension/json/test_json.py
@@ -6,7 +6,11 @@
import pandas as pd
import pandas._testing as tm
from pandas.tests.extension import base
-from pandas.tests.extension.json.array import JSONArray, JSONDtype, make_data
+from pandas.tests.extension.json.array import (
+ JSONArray,
+ JSONDtype,
+ make_data,
+)
@pytest.fixture
diff --git a/pandas/tests/extension/list/__init__.py b/pandas/tests/extension/list/__init__.py
index 1cd85657e0de4..0f3f2f3537788 100644
--- a/pandas/tests/extension/list/__init__.py
+++ b/pandas/tests/extension/list/__init__.py
@@ -1,3 +1,7 @@
-from pandas.tests.extension.list.array import ListArray, ListDtype, make_data
+from pandas.tests.extension.list.array import (
+ ListArray,
+ ListDtype,
+ make_data,
+)
__all__ = ["ListArray", "ListDtype", "make_data"]
diff --git a/pandas/tests/extension/list/array.py b/pandas/tests/extension/list/array.py
index 998dad208033e..4715bbdad6428 100644
--- a/pandas/tests/extension/list/array.py
+++ b/pandas/tests/extension/list/array.py
@@ -15,7 +15,10 @@
from pandas.core.dtypes.base import ExtensionDtype
import pandas as pd
-from pandas.api.types import is_object_dtype, is_string_dtype
+from pandas.api.types import (
+ is_object_dtype,
+ is_string_dtype,
+)
from pandas.core.arrays import ExtensionArray
diff --git a/pandas/tests/extension/list/test_list.py b/pandas/tests/extension/list/test_list.py
index 832bdf5bea3cf..295f08679c3eb 100644
--- a/pandas/tests/extension/list/test_list.py
+++ b/pandas/tests/extension/list/test_list.py
@@ -1,7 +1,11 @@
import pytest
import pandas as pd
-from pandas.tests.extension.list.array import ListArray, ListDtype, make_data
+from pandas.tests.extension.list.array import (
+ ListArray,
+ ListDtype,
+ make_data,
+)
@pytest.fixture
diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py
index 10e82a8c9bff1..3f1f2c02c79f7 100644
--- a/pandas/tests/extension/test_categorical.py
+++ b/pandas/tests/extension/test_categorical.py
@@ -19,7 +19,11 @@
import pytest
import pandas as pd
-from pandas import Categorical, CategoricalIndex, Timestamp
+from pandas import (
+ Categorical,
+ CategoricalIndex,
+ Timestamp,
+)
import pandas._testing as tm
from pandas.api.types import CategoricalDtype
from pandas.tests.extension import base
diff --git a/pandas/tests/extension/test_floating.py b/pandas/tests/extension/test_floating.py
index e6ab3a4de86f6..617dfc694741e 100644
--- a/pandas/tests/extension/test_floating.py
+++ b/pandas/tests/extension/test_floating.py
@@ -21,7 +21,10 @@
import pandas as pd
import pandas._testing as tm
from pandas.api.types import is_float_dtype
-from pandas.core.arrays.floating import Float32Dtype, Float64Dtype
+from pandas.core.arrays.floating import (
+ Float32Dtype,
+ Float64Dtype,
+)
from pandas.tests.extension import base
diff --git a/pandas/tests/extension/test_integer.py b/pandas/tests/extension/test_integer.py
index 4ee9cb89fc227..2305edc1e1327 100644
--- a/pandas/tests/extension/test_integer.py
+++ b/pandas/tests/extension/test_integer.py
@@ -18,7 +18,10 @@
import pandas as pd
import pandas._testing as tm
-from pandas.api.types import is_extension_array_dtype, is_integer_dtype
+from pandas.api.types import (
+ is_extension_array_dtype,
+ is_integer_dtype,
+)
from pandas.core.arrays.integer import (
Int8Dtype,
Int16Dtype,
diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py
index a5b54bc153f5d..2cd4da6b491bb 100644
--- a/pandas/tests/extension/test_numpy.py
+++ b/pandas/tests/extension/test_numpy.py
@@ -16,7 +16,10 @@
import numpy as np
import pytest
-from pandas.core.dtypes.dtypes import ExtensionDtype, PandasDtype
+from pandas.core.dtypes.dtypes import (
+ ExtensionDtype,
+ PandasDtype,
+)
import pandas as pd
import pandas._testing as tm
diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py
index 766910618d925..067fada5edcae 100644
--- a/pandas/tests/extension/test_sparse.py
+++ b/pandas/tests/extension/test_sparse.py
@@ -16,7 +16,10 @@
import numpy as np
import pytest
-from pandas.compat import IS64, is_platform_windows
+from pandas.compat import (
+ IS64,
+ is_platform_windows,
+)
from pandas.errors import PerformanceWarning
from pandas.core.dtypes.common import is_object_dtype
diff --git a/pandas/tests/frame/common.py b/pandas/tests/frame/common.py
index 95ebaa4641d1b..65f228f2be411 100644
--- a/pandas/tests/frame/common.py
+++ b/pandas/tests/frame/common.py
@@ -1,6 +1,9 @@
from typing import List
-from pandas import DataFrame, concat
+from pandas import (
+ DataFrame,
+ concat,
+)
def _check_mixed_float(df, dtype=None):
diff --git a/pandas/tests/frame/conftest.py b/pandas/tests/frame/conftest.py
index c6c8515d3b89b..7d485ee62c7d2 100644
--- a/pandas/tests/frame/conftest.py
+++ b/pandas/tests/frame/conftest.py
@@ -3,7 +3,11 @@
import numpy as np
import pytest
-from pandas import DataFrame, NaT, date_range
+from pandas import (
+ DataFrame,
+ NaT,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/constructors/test_from_dict.py b/pandas/tests/frame/constructors/test_from_dict.py
index 6c9e6751fd9a4..72107d849f598 100644
--- a/pandas/tests/frame/constructors/test_from_dict.py
+++ b/pandas/tests/frame/constructors/test_from_dict.py
@@ -3,7 +3,12 @@
import numpy as np
import pytest
-from pandas import DataFrame, Index, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
from pandas.core.construction import create_series_with_explicit_dtype
diff --git a/pandas/tests/frame/constructors/test_from_records.py b/pandas/tests/frame/constructors/test_from_records.py
index ed6333bac1caa..0d36f3bd80e26 100644
--- a/pandas/tests/frame/constructors/test_from_records.py
+++ b/pandas/tests/frame/constructors/test_from_records.py
@@ -7,7 +7,14 @@
from pandas.compat import is_platform_little_endian
-from pandas import CategoricalIndex, DataFrame, Index, Interval, RangeIndex, Series
+from pandas import (
+ CategoricalIndex,
+ DataFrame,
+ Index,
+ Interval,
+ RangeIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/indexing/test_categorical.py b/pandas/tests/frame/indexing/test_categorical.py
index b3e0783d7388f..464b24e45abf4 100644
--- a/pandas/tests/frame/indexing/test_categorical.py
+++ b/pandas/tests/frame/indexing/test_categorical.py
@@ -4,7 +4,12 @@
from pandas.core.dtypes.dtypes import CategoricalDtype
import pandas as pd
-from pandas import Categorical, DataFrame, Index, Series
+from pandas import (
+ Categorical,
+ DataFrame,
+ Index,
+ Series,
+)
import pandas._testing as tm
msg1 = "Cannot setitem on a Categorical with a new category, set the categories first"
diff --git a/pandas/tests/frame/indexing/test_delitem.py b/pandas/tests/frame/indexing/test_delitem.py
index f6c7b6ed5d14d..fa10c9ef7b85a 100644
--- a/pandas/tests/frame/indexing/test_delitem.py
+++ b/pandas/tests/frame/indexing/test_delitem.py
@@ -3,7 +3,10 @@
import numpy as np
import pytest
-from pandas import DataFrame, MultiIndex
+from pandas import (
+ DataFrame,
+ MultiIndex,
+)
class TestDataFrameDelItem:
diff --git a/pandas/tests/frame/indexing/test_get_value.py b/pandas/tests/frame/indexing/test_get_value.py
index 9a2ec975f1e31..65a1c64a1578a 100644
--- a/pandas/tests/frame/indexing/test_get_value.py
+++ b/pandas/tests/frame/indexing/test_get_value.py
@@ -1,6 +1,9 @@
import pytest
-from pandas import DataFrame, MultiIndex
+from pandas import (
+ DataFrame,
+ MultiIndex,
+)
class TestGetValue:
diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py
index 6808ffe65e561..fc4809d333e57 100644
--- a/pandas/tests/frame/indexing/test_indexing.py
+++ b/pandas/tests/frame/indexing/test_indexing.py
@@ -1,4 +1,9 @@
-from datetime import date, datetime, time, timedelta
+from datetime import (
+ date,
+ datetime,
+ time,
+ timedelta,
+)
import re
import numpy as np
diff --git a/pandas/tests/frame/indexing/test_insert.py b/pandas/tests/frame/indexing/test_insert.py
index 6e4deb5469777..921d277e09230 100644
--- a/pandas/tests/frame/indexing/test_insert.py
+++ b/pandas/tests/frame/indexing/test_insert.py
@@ -8,7 +8,10 @@
from pandas.errors import PerformanceWarning
-from pandas import DataFrame, Index
+from pandas import (
+ DataFrame,
+ Index,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/indexing/test_lookup.py b/pandas/tests/frame/indexing/test_lookup.py
index 21d732695fba4..caab5feea853b 100644
--- a/pandas/tests/frame/indexing/test_lookup.py
+++ b/pandas/tests/frame/indexing/test_lookup.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/indexing/test_mask.py b/pandas/tests/frame/indexing/test_mask.py
index bd541719c0877..afa8c757c23e4 100644
--- a/pandas/tests/frame/indexing/test_mask.py
+++ b/pandas/tests/frame/indexing/test_mask.py
@@ -4,7 +4,10 @@
import numpy as np
-from pandas import DataFrame, isna
+from pandas import (
+ DataFrame,
+ isna,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/indexing/test_set_value.py b/pandas/tests/frame/indexing/test_set_value.py
index 84def57f6b6e0..b8150c26aa6bb 100644
--- a/pandas/tests/frame/indexing/test_set_value.py
+++ b/pandas/tests/frame/indexing/test_set_value.py
@@ -3,7 +3,10 @@
from pandas.core.dtypes.common import is_float_dtype
-from pandas import DataFrame, isna
+from pandas import (
+ DataFrame,
+ isna,
+)
class TestSetValue:
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py
index 4dfbc0b918aaa..657faa0f9b505 100644
--- a/pandas/tests/frame/indexing/test_setitem.py
+++ b/pandas/tests/frame/indexing/test_setitem.py
@@ -7,7 +7,11 @@
is_interval_dtype,
is_object_dtype,
)
-from pandas.core.dtypes.dtypes import DatetimeTZDtype, IntervalDtype, PeriodDtype
+from pandas.core.dtypes.dtypes import (
+ DatetimeTZDtype,
+ IntervalDtype,
+ PeriodDtype,
+)
from pandas import (
Categorical,
diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py
index c057968c9574d..bc84d7c70b01c 100644
--- a/pandas/tests/frame/indexing/test_where.py
+++ b/pandas/tests/frame/indexing/test_where.py
@@ -6,7 +6,14 @@
from pandas.core.dtypes.common import is_scalar
import pandas as pd
-from pandas import DataFrame, DatetimeIndex, Series, Timestamp, date_range, isna
+from pandas import (
+ DataFrame,
+ DatetimeIndex,
+ Series,
+ Timestamp,
+ date_range,
+ isna,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/indexing/test_xs.py b/pandas/tests/frame/indexing/test_xs.py
index 3be3ce15622b4..59c88af265c08 100644
--- a/pandas/tests/frame/indexing/test_xs.py
+++ b/pandas/tests/frame/indexing/test_xs.py
@@ -3,7 +3,14 @@
import numpy as np
import pytest
-from pandas import DataFrame, Index, IndexSlice, MultiIndex, Series, concat
+from pandas import (
+ DataFrame,
+ Index,
+ IndexSlice,
+ MultiIndex,
+ Series,
+ concat,
+)
import pandas._testing as tm
import pandas.core.common as com
diff --git a/pandas/tests/frame/methods/test_align.py b/pandas/tests/frame/methods/test_align.py
index 5dd4f7f8f8800..a6e6914ba701e 100644
--- a/pandas/tests/frame/methods/test_align.py
+++ b/pandas/tests/frame/methods/test_align.py
@@ -3,7 +3,12 @@
import pytz
import pandas as pd
-from pandas import DataFrame, Index, Series, date_range
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_append.py b/pandas/tests/frame/methods/test_append.py
index 36c875b8abe6f..ba58d88fb4863 100644
--- a/pandas/tests/frame/methods/test_append.py
+++ b/pandas/tests/frame/methods/test_append.py
@@ -4,7 +4,13 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import DataFrame, Series, Timestamp, date_range, timedelta_range
+from pandas import (
+ DataFrame,
+ Series,
+ Timestamp,
+ date_range,
+ timedelta_range,
+)
import pandas._testing as tm
# TODO td.skip_array_manager_not_yet_implemented
diff --git a/pandas/tests/frame/methods/test_asfreq.py b/pandas/tests/frame/methods/test_asfreq.py
index 368ce88abe165..8a32841466b18 100644
--- a/pandas/tests/frame/methods/test_asfreq.py
+++ b/pandas/tests/frame/methods/test_asfreq.py
@@ -2,7 +2,13 @@
import numpy as np
-from pandas import DataFrame, DatetimeIndex, Series, date_range, to_datetime
+from pandas import (
+ DataFrame,
+ DatetimeIndex,
+ Series,
+ date_range,
+ to_datetime,
+)
import pandas._testing as tm
from pandas.tseries import offsets
diff --git a/pandas/tests/frame/methods/test_at_time.py b/pandas/tests/frame/methods/test_at_time.py
index 7ac3868e8ddf4..e9ac4336701a3 100644
--- a/pandas/tests/frame/methods/test_at_time.py
+++ b/pandas/tests/frame/methods/test_at_time.py
@@ -6,7 +6,10 @@
from pandas._libs.tslibs import timezones
-from pandas import DataFrame, date_range
+from pandas import (
+ DataFrame,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_between_time.py b/pandas/tests/frame/methods/test_between_time.py
index 73722f36a0b86..073368019e0f5 100644
--- a/pandas/tests/frame/methods/test_between_time.py
+++ b/pandas/tests/frame/methods/test_between_time.py
@@ -1,4 +1,7 @@
-from datetime import datetime, time
+from datetime import (
+ datetime,
+ time,
+)
import numpy as np
import pytest
@@ -6,7 +9,11 @@
from pandas._libs.tslibs import timezones
import pandas.util._test_decorators as td
-from pandas import DataFrame, Series, date_range
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_clip.py b/pandas/tests/frame/methods/test_clip.py
index 2da6c6e3f0a51..8a2374a414482 100644
--- a/pandas/tests/frame/methods/test_clip.py
+++ b/pandas/tests/frame/methods/test_clip.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_combine_first.py b/pandas/tests/frame/methods/test_combine_first.py
index 1325bfbda24c6..b4d8a53e4b23f 100644
--- a/pandas/tests/frame/methods/test_combine_first.py
+++ b/pandas/tests/frame/methods/test_combine_first.py
@@ -3,10 +3,18 @@
import numpy as np
import pytest
-from pandas.core.dtypes.cast import find_common_type, is_dtype_equal
+from pandas.core.dtypes.cast import (
+ find_common_type,
+ is_dtype_equal,
+)
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_convert.py b/pandas/tests/frame/methods/test_convert.py
index a00b2b5960884..13fec9829c3db 100644
--- a/pandas/tests/frame/methods/test_convert.py
+++ b/pandas/tests/frame/methods/test_convert.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_count.py b/pandas/tests/frame/methods/test_count.py
index 1727a76c191ee..1dbcc36c83abc 100644
--- a/pandas/tests/frame/methods/test_count.py
+++ b/pandas/tests/frame/methods/test_count.py
@@ -3,7 +3,11 @@
import pandas.util._test_decorators as td
-from pandas import DataFrame, Index, Series
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_cov_corr.py b/pandas/tests/frame/methods/test_cov_corr.py
index f8d729a215ba8..33b98fc5c2135 100644
--- a/pandas/tests/frame/methods/test_cov_corr.py
+++ b/pandas/tests/frame/methods/test_cov_corr.py
@@ -6,7 +6,11 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import DataFrame, Series, isna
+from pandas import (
+ DataFrame,
+ Series,
+ isna,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_describe.py b/pandas/tests/frame/methods/test_describe.py
index 15bafb7a835ba..4bc45e3abca32 100644
--- a/pandas/tests/frame/methods/test_describe.py
+++ b/pandas/tests/frame/methods/test_describe.py
@@ -4,7 +4,13 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import Categorical, DataFrame, Series, Timestamp, date_range
+from pandas import (
+ Categorical,
+ DataFrame,
+ Series,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
# TODO(ArrayManager) quantile is needed for describe()
diff --git a/pandas/tests/frame/methods/test_diff.py b/pandas/tests/frame/methods/test_diff.py
index b8328b43a6b13..c3dfca4c121db 100644
--- a/pandas/tests/frame/methods/test_diff.py
+++ b/pandas/tests/frame/methods/test_diff.py
@@ -2,7 +2,12 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Series, Timestamp, date_range
+from pandas import (
+ DataFrame,
+ Series,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_dot.py b/pandas/tests/frame/methods/test_dot.py
index ecbec6b06e923..555e5f0e26eaf 100644
--- a/pandas/tests/frame/methods/test_dot.py
+++ b/pandas/tests/frame/methods/test_dot.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_drop.py b/pandas/tests/frame/methods/test_drop.py
index 4568cda24d5cf..6749865367399 100644
--- a/pandas/tests/frame/methods/test_drop.py
+++ b/pandas/tests/frame/methods/test_drop.py
@@ -7,7 +7,13 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series, Timestamp
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_drop_duplicates.py b/pandas/tests/frame/methods/test_drop_duplicates.py
index b1d3890540bf9..10c1f37f4c9ba 100644
--- a/pandas/tests/frame/methods/test_drop_duplicates.py
+++ b/pandas/tests/frame/methods/test_drop_duplicates.py
@@ -4,7 +4,10 @@
import numpy as np
import pytest
-from pandas import DataFrame, NaT
+from pandas import (
+ DataFrame,
+ NaT,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_droplevel.py b/pandas/tests/frame/methods/test_droplevel.py
index ce98704b03106..e1302d4b73f2b 100644
--- a/pandas/tests/frame/methods/test_droplevel.py
+++ b/pandas/tests/frame/methods/test_droplevel.py
@@ -1,6 +1,10 @@
import pytest
-from pandas import DataFrame, Index, MultiIndex
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_dropna.py b/pandas/tests/frame/methods/test_dropna.py
index 9cbfee5e663ae..e28c716544209 100644
--- a/pandas/tests/frame/methods/test_dropna.py
+++ b/pandas/tests/frame/methods/test_dropna.py
@@ -5,7 +5,10 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_dtypes.py b/pandas/tests/frame/methods/test_dtypes.py
index 840e23604939a..84841ad7a634e 100644
--- a/pandas/tests/frame/methods/test_dtypes.py
+++ b/pandas/tests/frame/methods/test_dtypes.py
@@ -5,7 +5,12 @@
from pandas.core.dtypes.dtypes import DatetimeTZDtype
import pandas as pd
-from pandas import DataFrame, Series, date_range, option_context
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+ option_context,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_duplicated.py b/pandas/tests/frame/methods/test_duplicated.py
index 7a1c16adc2a09..0b90914281d3b 100644
--- a/pandas/tests/frame/methods/test_duplicated.py
+++ b/pandas/tests/frame/methods/test_duplicated.py
@@ -3,7 +3,11 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series, date_range
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_equals.py b/pandas/tests/frame/methods/test_equals.py
index ac9a66b4c7a6f..dddd6c6d2eaf2 100644
--- a/pandas/tests/frame/methods/test_equals.py
+++ b/pandas/tests/frame/methods/test_equals.py
@@ -1,6 +1,9 @@
import numpy as np
-from pandas import DataFrame, date_range
+from pandas import (
+ DataFrame,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_first_and_last.py b/pandas/tests/frame/methods/test_first_and_last.py
index 43469a093f827..70b9af358c1b9 100644
--- a/pandas/tests/frame/methods/test_first_and_last.py
+++ b/pandas/tests/frame/methods/test_first_and_last.py
@@ -3,7 +3,10 @@
"""
import pytest
-from pandas import DataFrame, bdate_range
+from pandas import (
+ DataFrame,
+ bdate_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_first_valid_index.py b/pandas/tests/frame/methods/test_first_valid_index.py
index 8d021f0e3954e..c2de1a6bb7b14 100644
--- a/pandas/tests/frame/methods/test_first_valid_index.py
+++ b/pandas/tests/frame/methods/test_first_valid_index.py
@@ -4,7 +4,11 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series, date_range
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_get_numeric_data.py b/pandas/tests/frame/methods/test_get_numeric_data.py
index 25b2a41b4b3a5..8628b76f54b1d 100644
--- a/pandas/tests/frame/methods/test_get_numeric_data.py
+++ b/pandas/tests/frame/methods/test_get_numeric_data.py
@@ -1,7 +1,13 @@
import numpy as np
import pandas as pd
-from pandas import Categorical, DataFrame, Index, Series, Timestamp
+from pandas import (
+ Categorical,
+ DataFrame,
+ Index,
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
from pandas.core.arrays import IntervalArray
diff --git a/pandas/tests/frame/methods/test_interpolate.py b/pandas/tests/frame/methods/test_interpolate.py
index 2477ad79d8a2c..5c6fcec887dfb 100644
--- a/pandas/tests/frame/methods/test_interpolate.py
+++ b/pandas/tests/frame/methods/test_interpolate.py
@@ -3,7 +3,11 @@
import pandas.util._test_decorators as td
-from pandas import DataFrame, Series, date_range
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_is_homogeneous_dtype.py b/pandas/tests/frame/methods/test_is_homogeneous_dtype.py
index 126c78a657c58..a5f285d31301b 100644
--- a/pandas/tests/frame/methods/test_is_homogeneous_dtype.py
+++ b/pandas/tests/frame/methods/test_is_homogeneous_dtype.py
@@ -3,7 +3,10 @@
import pandas.util._test_decorators as td
-from pandas import Categorical, DataFrame
+from pandas import (
+ Categorical,
+ DataFrame,
+)
# _is_homogeneous_type always returns True for ArrayManager
pytestmark = td.skip_array_manager_invalid_test
diff --git a/pandas/tests/frame/methods/test_isin.py b/pandas/tests/frame/methods/test_isin.py
index 5e50e63016f26..d2ebd09c4cc48 100644
--- a/pandas/tests/frame/methods/test_isin.py
+++ b/pandas/tests/frame/methods/test_isin.py
@@ -2,7 +2,11 @@
import pytest
import pandas as pd
-from pandas import DataFrame, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_join.py b/pandas/tests/frame/methods/test_join.py
index 42694dc3ff37c..11e83a3d94151 100644
--- a/pandas/tests/frame/methods/test_join.py
+++ b/pandas/tests/frame/methods/test_join.py
@@ -6,7 +6,13 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, date_range, period_range
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ date_range,
+ period_range,
+)
import pandas._testing as tm
# TODO(ArrayManager) concat with reindexing
diff --git a/pandas/tests/frame/methods/test_matmul.py b/pandas/tests/frame/methods/test_matmul.py
index c34bf991ffc4c..702ab3916d77a 100644
--- a/pandas/tests/frame/methods/test_matmul.py
+++ b/pandas/tests/frame/methods/test_matmul.py
@@ -3,7 +3,11 @@
import numpy as np
import pytest
-from pandas import DataFrame, Index, Series
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_pct_change.py b/pandas/tests/frame/methods/test_pct_change.py
index 56fb9ab0d8f00..8749218df59e1 100644
--- a/pandas/tests/frame/methods/test_pct_change.py
+++ b/pandas/tests/frame/methods/test_pct_change.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_pipe.py b/pandas/tests/frame/methods/test_pipe.py
index b865c191aebaf..26ea904260a65 100644
--- a/pandas/tests/frame/methods/test_pipe.py
+++ b/pandas/tests/frame/methods/test_pipe.py
@@ -1,6 +1,9 @@
import pytest
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_pop.py b/pandas/tests/frame/methods/test_pop.py
index 2926e29e61d56..a4f99b8287188 100644
--- a/pandas/tests/frame/methods/test_pop.py
+++ b/pandas/tests/frame/methods/test_pop.py
@@ -1,6 +1,10 @@
import numpy as np
-from pandas import DataFrame, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_quantile.py b/pandas/tests/frame/methods/test_quantile.py
index 6d6016df52238..46d3e335539fb 100644
--- a/pandas/tests/frame/methods/test_quantile.py
+++ b/pandas/tests/frame/methods/test_quantile.py
@@ -4,7 +4,11 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import DataFrame, Series, Timestamp
+from pandas import (
+ DataFrame,
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
pytestmark = td.skip_array_manager_not_yet_implemented
diff --git a/pandas/tests/frame/methods/test_rank.py b/pandas/tests/frame/methods/test_rank.py
index 5b66f58b8f069..ce46d1d8b1869 100644
--- a/pandas/tests/frame/methods/test_rank.py
+++ b/pandas/tests/frame/methods/test_rank.py
@@ -1,13 +1,22 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import numpy as np
import pytest
from pandas._libs import iNaT
-from pandas._libs.algos import Infinity, NegInfinity
+from pandas._libs.algos import (
+ Infinity,
+ NegInfinity,
+)
import pandas.util._test_decorators as td
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_reindex.py b/pandas/tests/frame/methods/test_reindex.py
index 5b7d096d0ab99..128942cd64926 100644
--- a/pandas/tests/frame/methods/test_reindex.py
+++ b/pandas/tests/frame/methods/test_reindex.py
@@ -1,4 +1,7 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import inspect
from itertools import permutations
diff --git a/pandas/tests/frame/methods/test_rename.py b/pandas/tests/frame/methods/test_rename.py
index 1080d97b30987..10ed862225c01 100644
--- a/pandas/tests/frame/methods/test_rename.py
+++ b/pandas/tests/frame/methods/test_rename.py
@@ -4,7 +4,12 @@
import numpy as np
import pytest
-from pandas import DataFrame, Index, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_rename_axis.py b/pandas/tests/frame/methods/test_rename_axis.py
index 3339119841813..dd4a77c6509b8 100644
--- a/pandas/tests/frame/methods/test_rename_axis.py
+++ b/pandas/tests/frame/methods/test_rename_axis.py
@@ -1,7 +1,11 @@
import numpy as np
import pytest
-from pandas import DataFrame, Index, MultiIndex
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_reorder_levels.py b/pandas/tests/frame/methods/test_reorder_levels.py
index 451fc9a5cf717..0173de88b6d6d 100644
--- a/pandas/tests/frame/methods/test_reorder_levels.py
+++ b/pandas/tests/frame/methods/test_reorder_levels.py
@@ -3,7 +3,10 @@
import pandas.util._test_decorators as td
-from pandas import DataFrame, MultiIndex
+from pandas import (
+ DataFrame,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py
index febd113f309ae..9ae5bb151b685 100644
--- a/pandas/tests/frame/methods/test_replace.py
+++ b/pandas/tests/frame/methods/test_replace.py
@@ -1,13 +1,23 @@
from datetime import datetime
from io import StringIO
import re
-from typing import Dict, List, Union
+from typing import (
+ Dict,
+ List,
+ Union,
+)
import numpy as np
import pytest
import pandas as pd
-from pandas import DataFrame, Index, Series, Timestamp, date_range
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py
index 8644f56e4f253..2ca23127c751a 100644
--- a/pandas/tests/frame/methods/test_reset_index.py
+++ b/pandas/tests/frame/methods/test_reset_index.py
@@ -6,7 +6,10 @@
import pandas.util._test_decorators as td
-from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype
+from pandas.core.dtypes.common import (
+ is_float_dtype,
+ is_integer_dtype,
+)
import pandas as pd
from pandas import (
diff --git a/pandas/tests/frame/methods/test_round.py b/pandas/tests/frame/methods/test_round.py
index 5cf5aea8846c5..ebe33922be541 100644
--- a/pandas/tests/frame/methods/test_round.py
+++ b/pandas/tests/frame/methods/test_round.py
@@ -2,7 +2,11 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Series, date_range
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_sample.py b/pandas/tests/frame/methods/test_sample.py
index e17c14940746d..f11e13ca2574e 100644
--- a/pandas/tests/frame/methods/test_sample.py
+++ b/pandas/tests/frame/methods/test_sample.py
@@ -3,7 +3,10 @@
from pandas.compat import np_version_under1p17
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
import pandas.core.common as com
diff --git a/pandas/tests/frame/methods/test_select_dtypes.py b/pandas/tests/frame/methods/test_select_dtypes.py
index 2a94b18b806f8..7d3333e493136 100644
--- a/pandas/tests/frame/methods/test_select_dtypes.py
+++ b/pandas/tests/frame/methods/test_select_dtypes.py
@@ -4,7 +4,10 @@
from pandas.core.dtypes.dtypes import ExtensionDtype
import pandas as pd
-from pandas import DataFrame, Timestamp
+from pandas import (
+ DataFrame,
+ Timestamp,
+)
import pandas._testing as tm
from pandas.core.arrays import ExtensionArray
diff --git a/pandas/tests/frame/methods/test_set_axis.py b/pandas/tests/frame/methods/test_set_axis.py
index a46a91811f40e..ee538e1d9d9ac 100644
--- a/pandas/tests/frame/methods/test_set_axis.py
+++ b/pandas/tests/frame/methods/test_set_axis.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_set_index.py b/pandas/tests/frame/methods/test_set_index.py
index 70232dfd1d79a..430abd9700a23 100644
--- a/pandas/tests/frame/methods/test_set_index.py
+++ b/pandas/tests/frame/methods/test_set_index.py
@@ -2,7 +2,10 @@
See also: test_reindex.py:TestReindexSetIndex
"""
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import numpy as np
import pytest
diff --git a/pandas/tests/frame/methods/test_shift.py b/pandas/tests/frame/methods/test_shift.py
index aefc407d0c432..0474206aec06f 100644
--- a/pandas/tests/frame/methods/test_shift.py
+++ b/pandas/tests/frame/methods/test_shift.py
@@ -4,7 +4,14 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import CategoricalIndex, DataFrame, Index, Series, date_range, offsets
+from pandas import (
+ CategoricalIndex,
+ DataFrame,
+ Index,
+ Series,
+ date_range,
+ offsets,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py
index 053684ba08484..24ff20872baef 100644
--- a/pandas/tests/frame/methods/test_sort_values.py
+++ b/pandas/tests/frame/methods/test_sort_values.py
@@ -6,7 +6,13 @@
from pandas.errors import PerformanceWarning
import pandas as pd
-from pandas import Categorical, DataFrame, NaT, Timestamp, date_range
+from pandas import (
+ Categorical,
+ DataFrame,
+ NaT,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_to_dict.py b/pandas/tests/frame/methods/test_to_dict.py
index db96543dc69b8..c17ad197ac09a 100644
--- a/pandas/tests/frame/methods/test_to_dict.py
+++ b/pandas/tests/frame/methods/test_to_dict.py
@@ -1,11 +1,18 @@
-from collections import OrderedDict, defaultdict
+from collections import (
+ OrderedDict,
+ defaultdict,
+)
from datetime import datetime
import numpy as np
import pytest
import pytz
-from pandas import DataFrame, Series, Timestamp
+from pandas import (
+ DataFrame,
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_to_dict_of_blocks.py b/pandas/tests/frame/methods/test_to_dict_of_blocks.py
index 8de47cb17d7d3..8b5f45465cb3c 100644
--- a/pandas/tests/frame/methods/test_to_dict_of_blocks.py
+++ b/pandas/tests/frame/methods/test_to_dict_of_blocks.py
@@ -2,7 +2,10 @@
import pandas.util._test_decorators as td
-from pandas import DataFrame, MultiIndex
+from pandas import (
+ DataFrame,
+ MultiIndex,
+)
import pandas._testing as tm
from pandas.core.arrays import PandasArray
diff --git a/pandas/tests/frame/methods/test_to_numpy.py b/pandas/tests/frame/methods/test_to_numpy.py
index 0682989294457..532f7c87557c8 100644
--- a/pandas/tests/frame/methods/test_to_numpy.py
+++ b/pandas/tests/frame/methods/test_to_numpy.py
@@ -2,7 +2,10 @@
import pandas.util._test_decorators as td
-from pandas import DataFrame, Timestamp
+from pandas import (
+ DataFrame,
+ Timestamp,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_transpose.py b/pandas/tests/frame/methods/test_transpose.py
index 548842e653a63..d6ab3268c8c37 100644
--- a/pandas/tests/frame/methods/test_transpose.py
+++ b/pandas/tests/frame/methods/test_transpose.py
@@ -3,7 +3,10 @@
import pandas.util._test_decorators as td
-from pandas import DataFrame, date_range
+from pandas import (
+ DataFrame,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_truncate.py b/pandas/tests/frame/methods/test_truncate.py
index c6d6637edc88c..210e86067566a 100644
--- a/pandas/tests/frame/methods/test_truncate.py
+++ b/pandas/tests/frame/methods/test_truncate.py
@@ -2,7 +2,11 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Series, date_range
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_tz_convert.py b/pandas/tests/frame/methods/test_tz_convert.py
index 9176d2300c39e..046f7a4f9e1c3 100644
--- a/pandas/tests/frame/methods/test_tz_convert.py
+++ b/pandas/tests/frame/methods/test_tz_convert.py
@@ -1,7 +1,13 @@
import numpy as np
import pytest
-from pandas import DataFrame, Index, MultiIndex, Series, date_range
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_tz_localize.py b/pandas/tests/frame/methods/test_tz_localize.py
index 9108bd52bdfa0..425ec4335455e 100644
--- a/pandas/tests/frame/methods/test_tz_localize.py
+++ b/pandas/tests/frame/methods/test_tz_localize.py
@@ -1,7 +1,11 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series, date_range
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_update.py b/pandas/tests/frame/methods/test_update.py
index d9de026dbf4e9..59e0605cc5a91 100644
--- a/pandas/tests/frame/methods/test_update.py
+++ b/pandas/tests/frame/methods/test_update.py
@@ -2,7 +2,11 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Series, date_range
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/methods/test_values.py b/pandas/tests/frame/methods/test_values.py
index 5426e4368722e..94ea369d26b97 100644
--- a/pandas/tests/frame/methods/test_values.py
+++ b/pandas/tests/frame/methods/test_values.py
@@ -3,7 +3,14 @@
import pandas.util._test_decorators as td
-from pandas import DataFrame, NaT, Series, Timestamp, date_range, period_range
+from pandas import (
+ DataFrame,
+ NaT,
+ Series,
+ Timestamp,
+ date_range,
+ period_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py
index 6b8284908213a..8d3d049cf82f1 100644
--- a/pandas/tests/frame/test_api.py
+++ b/pandas/tests/frame/test_api.py
@@ -6,10 +6,18 @@
import pytest
import pandas.util._test_decorators as td
-from pandas.util._test_decorators import async_mark, skip_if_no
+from pandas.util._test_decorators import (
+ async_mark,
+ skip_if_no,
+)
import pandas as pd
-from pandas import DataFrame, Series, date_range, timedelta_range
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+ timedelta_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py
index afc25c48beb5f..26710b1f9ed73 100644
--- a/pandas/tests/frame/test_arithmetic.py
+++ b/pandas/tests/frame/test_arithmetic.py
@@ -8,11 +8,21 @@
import pytz
import pandas as pd
-from pandas import DataFrame, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
import pandas.core.common as com
-from pandas.core.computation.expressions import _MIN_ELEMENTS, NUMEXPR_INSTALLED
-from pandas.tests.frame.common import _check_mixed_float, _check_mixed_int
+from pandas.core.computation.expressions import (
+ _MIN_ELEMENTS,
+ NUMEXPR_INSTALLED,
+)
+from pandas.tests.frame.common import (
+ _check_mixed_float,
+ _check_mixed_int,
+)
class DummyElement:
diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py
index b36f6fcf8b9f8..193f1617fbb55 100644
--- a/pandas/tests/frame/test_block_internals.py
+++ b/pandas/tests/frame/test_block_internals.py
@@ -1,4 +1,7 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
from io import StringIO
import itertools
@@ -18,7 +21,10 @@
option_context,
)
import pandas._testing as tm
-from pandas.core.internals import NumericBlock, ObjectBlock
+from pandas.core.internals import (
+ NumericBlock,
+ ObjectBlock,
+)
# Segregated collection of methods that require the BlockManager internal data
# structure
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index 5fcab5200e305..93bffd7fea95b 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -1,5 +1,12 @@
-from collections import OrderedDict, abc
-from datetime import date, datetime, timedelta
+from collections import (
+ OrderedDict,
+ abc,
+)
+from datetime import (
+ date,
+ datetime,
+ timedelta,
+)
import functools
import itertools
import re
@@ -13,7 +20,11 @@
from pandas.compat import np_version_under1p19
from pandas.core.dtypes.common import is_integer_dtype
-from pandas.core.dtypes.dtypes import DatetimeTZDtype, IntervalDtype, PeriodDtype
+from pandas.core.dtypes.dtypes import (
+ DatetimeTZDtype,
+ IntervalDtype,
+ PeriodDtype,
+)
import pandas as pd
from pandas import (
@@ -33,7 +44,11 @@
isna,
)
import pandas._testing as tm
-from pandas.arrays import IntervalArray, PeriodArray, SparseArray
+from pandas.arrays import (
+ IntervalArray,
+ PeriodArray,
+ SparseArray,
+)
MIXED_FLOAT_DTYPES = ["float16", "float32", "float64"]
MIXED_INT_DTYPES = [
diff --git a/pandas/tests/frame/test_cumulative.py b/pandas/tests/frame/test_cumulative.py
index 248f3500c41df..39714a4566494 100644
--- a/pandas/tests/frame/test_cumulative.py
+++ b/pandas/tests/frame/test_cumulative.py
@@ -8,7 +8,10 @@
import numpy as np
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/test_iteration.py b/pandas/tests/frame/test_iteration.py
index d6268f90b2681..c6e5aa6f86d29 100644
--- a/pandas/tests/frame/test_iteration.py
+++ b/pandas/tests/frame/test_iteration.py
@@ -2,9 +2,17 @@
import numpy as np
-from pandas.compat import IS64, is_platform_windows
-
-from pandas import Categorical, DataFrame, Series, date_range
+from pandas.compat import (
+ IS64,
+ is_platform_windows,
+)
+
+from pandas import (
+ Categorical,
+ DataFrame,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/test_logical_ops.py b/pandas/tests/frame/test_logical_ops.py
index dca12c632a418..f509ae52ad5a5 100644
--- a/pandas/tests/frame/test_logical_ops.py
+++ b/pandas/tests/frame/test_logical_ops.py
@@ -4,7 +4,13 @@
import numpy as np
import pytest
-from pandas import CategoricalIndex, DataFrame, Interval, Series, isnull
+from pandas import (
+ CategoricalIndex,
+ DataFrame,
+ Interval,
+ Series,
+ isnull,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py
index 1f892c3a03e85..3e48883232243 100644
--- a/pandas/tests/frame/test_nonunique_indexes.py
+++ b/pandas/tests/frame/test_nonunique_indexes.py
@@ -2,7 +2,12 @@
import pytest
import pandas as pd
-from pandas import DataFrame, MultiIndex, Series, date_range
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/test_npfuncs.py b/pandas/tests/frame/test_npfuncs.py
index 1e37822798244..0b7699e46d720 100644
--- a/pandas/tests/frame/test_npfuncs.py
+++ b/pandas/tests/frame/test_npfuncs.py
@@ -3,7 +3,10 @@
"""
import numpy as np
-from pandas import Categorical, DataFrame
+from pandas import (
+ Categorical,
+ DataFrame,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py
index af134db587306..0cc4c4ad81208 100644
--- a/pandas/tests/frame/test_query_eval.py
+++ b/pandas/tests/frame/test_query_eval.py
@@ -7,7 +7,13 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series, date_range
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ date_range,
+)
import pandas._testing as tm
from pandas.core.computation.check import NUMEXPR_INSTALLED
diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py
index 1c397d6a6a1b5..e85b399e69874 100644
--- a/pandas/tests/frame/test_reductions.py
+++ b/pandas/tests/frame/test_reductions.py
@@ -285,7 +285,10 @@ def test_stat_op_api(self, float_frame, float_string_frame):
assert_stat_op_api("median", float_frame, float_string_frame)
try:
- from scipy.stats import kurtosis, skew # noqa:F401
+ from scipy.stats import ( # noqa:F401
+ kurtosis,
+ skew,
+ )
assert_stat_op_api("skew", float_frame, float_string_frame)
assert_stat_op_api("kurt", float_frame, float_string_frame)
@@ -368,7 +371,10 @@ def kurt(x):
)
try:
- from scipy import kurtosis, skew # noqa:F401
+ from scipy import ( # noqa:F401
+ kurtosis,
+ skew,
+ )
assert_stat_op_calc("skew", skewness, float_frame_with_na)
assert_stat_op_calc("kurt", kurt, float_frame_with_na)
diff --git a/pandas/tests/frame/test_repr_info.py b/pandas/tests/frame/test_repr_info.py
index 22b50310cedd6..c8131049b51d2 100644
--- a/pandas/tests/frame/test_repr_info.py
+++ b/pandas/tests/frame/test_repr_info.py
@@ -1,4 +1,7 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
from io import StringIO
import warnings
diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py
index 81e10d276e79c..6f453ec5df71f 100644
--- a/pandas/tests/frame/test_stack_unstack.py
+++ b/pandas/tests/frame/test_stack_unstack.py
@@ -6,7 +6,15 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Period, Series, Timedelta, date_range
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Period,
+ Series,
+ Timedelta,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/test_subclass.py b/pandas/tests/frame/test_subclass.py
index 2b462d5a10c51..c32d8f63831ac 100644
--- a/pandas/tests/frame/test_subclass.py
+++ b/pandas/tests/frame/test_subclass.py
@@ -4,7 +4,12 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/frame/test_ufunc.py b/pandas/tests/frame/test_ufunc.py
index 62b12f8a60307..0bcb62251fc5c 100644
--- a/pandas/tests/frame/test_ufunc.py
+++ b/pandas/tests/frame/test_ufunc.py
@@ -218,7 +218,10 @@ def test_alignment_deprecation_many_inputs():
# https://github.com/pandas-dev/pandas/issues/39184
# test that the deprecation also works with > 2 inputs -> using a numba
# written ufunc for this because numpy itself doesn't have such ufuncs
- from numba import float64, vectorize
+ from numba import (
+ float64,
+ vectorize,
+ )
@vectorize([float64(float64, float64, float64)])
def my_ufunc(x, y, z):
diff --git a/pandas/tests/generic/test_frame.py b/pandas/tests/generic/test_frame.py
index 194b8bdd4715e..49a1dc8bbb21c 100644
--- a/pandas/tests/generic/test_frame.py
+++ b/pandas/tests/generic/test_frame.py
@@ -5,7 +5,12 @@
import pytest
import pandas as pd
-from pandas import DataFrame, MultiIndex, Series, date_range
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+ date_range,
+)
import pandas._testing as tm
from pandas.tests.generic.test_generic import Generic
diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py
index 199c521cfc81b..8574589cb27bb 100644
--- a/pandas/tests/generic/test_generic.py
+++ b/pandas/tests/generic/test_generic.py
@@ -1,11 +1,17 @@
-from copy import copy, deepcopy
+from copy import (
+ copy,
+ deepcopy,
+)
import numpy as np
import pytest
from pandas.core.dtypes.common import is_scalar
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
# ----------------------------------------------------------------------
diff --git a/pandas/tests/generic/test_series.py b/pandas/tests/generic/test_series.py
index 38ab8d333e880..823ce7435f229 100644
--- a/pandas/tests/generic/test_series.py
+++ b/pandas/tests/generic/test_series.py
@@ -4,7 +4,11 @@
import pytest
import pandas as pd
-from pandas import MultiIndex, Series, date_range
+from pandas import (
+ MultiIndex,
+ Series,
+ date_range,
+)
import pandas._testing as tm
from pandas.tests.generic.test_generic import Generic
diff --git a/pandas/tests/generic/test_to_xarray.py b/pandas/tests/generic/test_to_xarray.py
index a6aa45406305c..8e33465efcbf7 100644
--- a/pandas/tests/generic/test_to_xarray.py
+++ b/pandas/tests/generic/test_to_xarray.py
@@ -3,7 +3,13 @@
import pandas.util._test_decorators as td
-from pandas import Categorical, DataFrame, MultiIndex, Series, date_range
+from pandas import (
+ Categorical,
+ DataFrame,
+ MultiIndex,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py
index 48527de6b2047..92b7aefa6dd8c 100644
--- a/pandas/tests/groupby/aggregate/test_aggregate.py
+++ b/pandas/tests/groupby/aggregate/test_aggregate.py
@@ -13,7 +13,13 @@
from pandas.core.dtypes.common import is_integer_dtype
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series, concat
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ concat,
+)
import pandas._testing as tm
from pandas.core.base import SpecificationError
from pandas.core.groupby.grouper import Grouping
diff --git a/pandas/tests/groupby/aggregate/test_cython.py b/pandas/tests/groupby/aggregate/test_cython.py
index 8799f6faa775c..f9b45f4d9f4cf 100644
--- a/pandas/tests/groupby/aggregate/test_cython.py
+++ b/pandas/tests/groupby/aggregate/test_cython.py
@@ -8,7 +8,15 @@
from pandas.core.dtypes.common import is_float_dtype
import pandas as pd
-from pandas import DataFrame, Index, NaT, Series, Timedelta, Timestamp, bdate_range
+from pandas import (
+ DataFrame,
+ Index,
+ NaT,
+ Series,
+ Timedelta,
+ Timestamp,
+ bdate_range,
+)
import pandas._testing as tm
from pandas.core.groupby.groupby import DataError
diff --git a/pandas/tests/groupby/aggregate/test_numba.py b/pandas/tests/groupby/aggregate/test_numba.py
index c4266996748c2..6de81d03ca418 100644
--- a/pandas/tests/groupby/aggregate/test_numba.py
+++ b/pandas/tests/groupby/aggregate/test_numba.py
@@ -4,7 +4,11 @@
from pandas.errors import NumbaUtilError
import pandas.util._test_decorators as td
-from pandas import DataFrame, NamedAgg, option_context
+from pandas import (
+ DataFrame,
+ NamedAgg,
+ option_context,
+)
import pandas._testing as tm
from pandas.core.util.numba_ import NUMBA_FUNC_CACHE
diff --git a/pandas/tests/groupby/aggregate/test_other.py b/pandas/tests/groupby/aggregate/test_other.py
index 04f17865b088a..f945f898603ac 100644
--- a/pandas/tests/groupby/aggregate/test_other.py
+++ b/pandas/tests/groupby/aggregate/test_other.py
@@ -627,7 +627,11 @@ def test_groupby_agg_err_catching(err_cls):
# in _python_agg_general
# Use a non-standard EA to make sure we don't go down ndarray paths
- from pandas.tests.extension.decimal.array import DecimalArray, make_data, to_decimal
+ from pandas.tests.extension.decimal.array import (
+ DecimalArray,
+ make_data,
+ to_decimal,
+ )
data = make_data()[:5]
df = DataFrame(
diff --git a/pandas/tests/groupby/conftest.py b/pandas/tests/groupby/conftest.py
index 0b9721968a881..b69a467f91659 100644
--- a/pandas/tests/groupby/conftest.py
+++ b/pandas/tests/groupby/conftest.py
@@ -1,9 +1,15 @@
import numpy as np
import pytest
-from pandas import DataFrame, MultiIndex
+from pandas import (
+ DataFrame,
+ MultiIndex,
+)
import pandas._testing as tm
-from pandas.core.groupby.base import reduction_kernels, transformation_kernels
+from pandas.core.groupby.base import (
+ reduction_kernels,
+ transformation_kernels,
+)
@pytest.fixture
diff --git a/pandas/tests/groupby/test_allowlist.py b/pandas/tests/groupby/test_allowlist.py
index 57ccf6ebd24bd..de8335738791d 100644
--- a/pandas/tests/groupby/test_allowlist.py
+++ b/pandas/tests/groupby/test_allowlist.py
@@ -8,7 +8,13 @@
import numpy as np
import pytest
-from pandas import DataFrame, Index, MultiIndex, Series, date_range
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ date_range,
+)
import pandas._testing as tm
from pandas.core.groupby.base import (
groupby_other_methods,
diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py
index 975cebe16dc55..4bbdba9fedbff 100644
--- a/pandas/tests/groupby/test_apply.py
+++ b/pandas/tests/groupby/test_apply.py
@@ -1,11 +1,20 @@
-from datetime import date, datetime
+from datetime import (
+ date,
+ datetime,
+)
from io import StringIO
import numpy as np
import pytest
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series, bdate_range
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ bdate_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/groupby/test_bin_groupby.py b/pandas/tests/groupby/test_bin_groupby.py
index aff9911961b25..ce46afc0ccd65 100644
--- a/pandas/tests/groupby/test_bin_groupby.py
+++ b/pandas/tests/groupby/test_bin_groupby.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas._libs import lib, reduction as libreduction
+from pandas._libs import (
+ lib,
+ reduction as libreduction,
+)
import pandas as pd
from pandas import Series
diff --git a/pandas/tests/groupby/test_filters.py b/pandas/tests/groupby/test_filters.py
index 448e6c6e6f64a..995fd58a84cbd 100644
--- a/pandas/tests/groupby/test_filters.py
+++ b/pandas/tests/groupby/test_filters.py
@@ -2,7 +2,11 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Series, Timestamp
+from pandas import (
+ DataFrame,
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py
index f532e496ccca9..ecd9d16228939 100644
--- a/pandas/tests/groupby/test_function.py
+++ b/pandas/tests/groupby/test_function.py
@@ -7,7 +7,15 @@
from pandas.errors import UnsupportedFunctionCall
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, date_range, isna
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ Timestamp,
+ date_range,
+ isna,
+)
import pandas._testing as tm
import pandas.core.nanops as nanops
from pandas.util import _test_decorators as td
diff --git a/pandas/tests/groupby/test_groupby_shift_diff.py b/pandas/tests/groupby/test_groupby_shift_diff.py
index 1410038274152..c6f3e7618e3f7 100644
--- a/pandas/tests/groupby/test_groupby_shift_diff.py
+++ b/pandas/tests/groupby/test_groupby_shift_diff.py
@@ -1,7 +1,13 @@
import numpy as np
import pytest
-from pandas import DataFrame, NaT, Series, Timedelta, Timestamp
+from pandas import (
+ DataFrame,
+ NaT,
+ Series,
+ Timedelta,
+ Timestamp,
+)
import pandas._testing as tm
diff --git a/pandas/tests/groupby/test_groupby_subclass.py b/pandas/tests/groupby/test_groupby_subclass.py
index d268d87708552..8008c6c98acc9 100644
--- a/pandas/tests/groupby/test_groupby_subclass.py
+++ b/pandas/tests/groupby/test_groupby_subclass.py
@@ -3,7 +3,10 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py
index 10e69ddcd5f80..a1d956a6fe096 100644
--- a/pandas/tests/groupby/test_grouping.py
+++ b/pandas/tests/groupby/test_grouping.py
@@ -167,7 +167,10 @@ def test_grouper_multilevel_freq(self):
# GH 7885
# with level and freq specified in a pd.Grouper
- from datetime import date, timedelta
+ from datetime import (
+ date,
+ timedelta,
+ )
d0 = date.today() - timedelta(days=14)
dates = date_range(d0, date.today())
diff --git a/pandas/tests/groupby/test_missing.py b/pandas/tests/groupby/test_missing.py
index e2ca63d9ab922..e53518269408a 100644
--- a/pandas/tests/groupby/test_missing.py
+++ b/pandas/tests/groupby/test_missing.py
@@ -2,7 +2,11 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, date_range
+from pandas import (
+ DataFrame,
+ Index,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/groupby/test_nth.py b/pandas/tests/groupby/test_nth.py
index 26b3af4234be1..1b74096cbfbdf 100644
--- a/pandas/tests/groupby/test_nth.py
+++ b/pandas/tests/groupby/test_nth.py
@@ -2,7 +2,14 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, isna
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ Timestamp,
+ isna,
+)
import pandas._testing as tm
diff --git a/pandas/tests/groupby/test_nunique.py b/pandas/tests/groupby/test_nunique.py
index 22970eff28f19..6656fd565f79d 100644
--- a/pandas/tests/groupby/test_nunique.py
+++ b/pandas/tests/groupby/test_nunique.py
@@ -5,7 +5,14 @@
import pytest
import pandas as pd
-from pandas import DataFrame, MultiIndex, NaT, Series, Timestamp, date_range
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ NaT,
+ Series,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/groupby/test_pipe.py b/pandas/tests/groupby/test_pipe.py
index 1acbc8cf5c0ad..3e43d13bb8b67 100644
--- a/pandas/tests/groupby/test_pipe.py
+++ b/pandas/tests/groupby/test_pipe.py
@@ -1,7 +1,10 @@
import numpy as np
import pandas as pd
-from pandas import DataFrame, Index
+from pandas import (
+ DataFrame,
+ Index,
+)
import pandas._testing as tm
diff --git a/pandas/tests/groupby/test_quantile.py b/pandas/tests/groupby/test_quantile.py
index c8d6d09577c2b..9c9d1aa881890 100644
--- a/pandas/tests/groupby/test_quantile.py
+++ b/pandas/tests/groupby/test_quantile.py
@@ -2,7 +2,10 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index
+from pandas import (
+ DataFrame,
+ Index,
+)
import pandas._testing as tm
diff --git a/pandas/tests/groupby/test_rank.py b/pandas/tests/groupby/test_rank.py
index f2046c5768668..6116703ebd174 100644
--- a/pandas/tests/groupby/test_rank.py
+++ b/pandas/tests/groupby/test_rank.py
@@ -2,7 +2,11 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Series, concat
+from pandas import (
+ DataFrame,
+ Series,
+ concat,
+)
import pandas._testing as tm
from pandas.core.base import DataError
diff --git a/pandas/tests/groupby/test_sample.py b/pandas/tests/groupby/test_sample.py
index 412e3e8f732de..13147ca704b56 100644
--- a/pandas/tests/groupby/test_sample.py
+++ b/pandas/tests/groupby/test_sample.py
@@ -1,6 +1,10 @@
import pytest
-from pandas import DataFrame, Index, Series
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/groupby/test_size.py b/pandas/tests/groupby/test_size.py
index ba27e5a24ba00..f87e4117f57fd 100644
--- a/pandas/tests/groupby/test_size.py
+++ b/pandas/tests/groupby/test_size.py
@@ -1,7 +1,12 @@
import numpy as np
import pytest
-from pandas import DataFrame, Index, PeriodIndex, Series
+from pandas import (
+ DataFrame,
+ Index,
+ PeriodIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/groupby/transform/test_numba.py b/pandas/tests/groupby/transform/test_numba.py
index 3a184bdd007c7..fbee2361b9b45 100644
--- a/pandas/tests/groupby/transform/test_numba.py
+++ b/pandas/tests/groupby/transform/test_numba.py
@@ -3,7 +3,10 @@
from pandas.errors import NumbaUtilError
import pandas.util._test_decorators as td
-from pandas import DataFrame, option_context
+from pandas import (
+ DataFrame,
+ option_context,
+)
import pandas._testing as tm
from pandas.core.util.numba_ import NUMBA_FUNC_CACHE
diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py
index 04eb2f42d745b..ae0f7545df8cf 100644
--- a/pandas/tests/groupby/transform/test_transform.py
+++ b/pandas/tests/groupby/transform/test_transform.py
@@ -4,7 +4,10 @@
import numpy as np
import pytest
-from pandas.core.dtypes.common import ensure_platform_int, is_timedelta64_dtype
+from pandas.core.dtypes.common import (
+ ensure_platform_int,
+ is_timedelta64_dtype,
+)
import pandas as pd
from pandas import (
diff --git a/pandas/tests/indexes/base_class/test_constructors.py b/pandas/tests/indexes/base_class/test_constructors.py
index b3229b4eda030..0c4f9c6d759b9 100644
--- a/pandas/tests/indexes/base_class/test_constructors.py
+++ b/pandas/tests/indexes/base_class/test_constructors.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import Index, MultiIndex
+from pandas import (
+ Index,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/base_class/test_setops.py b/pandas/tests/indexes/base_class/test_setops.py
index ddcb3c5b87ebc..2bc9b2cd1a1bd 100644
--- a/pandas/tests/indexes/base_class/test_setops.py
+++ b/pandas/tests/indexes/base_class/test_setops.py
@@ -4,7 +4,10 @@
import pytest
import pandas as pd
-from pandas import Index, Series
+from pandas import (
+ Index,
+ Series,
+)
import pandas._testing as tm
from pandas.core.algorithms import safe_sort
diff --git a/pandas/tests/indexes/categorical/test_astype.py b/pandas/tests/indexes/categorical/test_astype.py
index 48a90652a2c06..854ae8b62db30 100644
--- a/pandas/tests/indexes/categorical/test_astype.py
+++ b/pandas/tests/indexes/categorical/test_astype.py
@@ -3,7 +3,13 @@
import numpy as np
import pytest
-from pandas import Categorical, CategoricalDtype, CategoricalIndex, Index, IntervalIndex
+from pandas import (
+ Categorical,
+ CategoricalDtype,
+ CategoricalIndex,
+ Index,
+ IntervalIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py
index 75b3a6ece0b21..4b2df268f5c1a 100644
--- a/pandas/tests/indexes/categorical/test_category.py
+++ b/pandas/tests/indexes/categorical/test_category.py
@@ -6,7 +6,10 @@
import pandas as pd
from pandas import Categorical
import pandas._testing as tm
-from pandas.core.indexes.api import CategoricalIndex, Index
+from pandas.core.indexes.api import (
+ CategoricalIndex,
+ Index,
+)
from pandas.tests.indexes.common import Base
diff --git a/pandas/tests/indexes/categorical/test_constructors.py b/pandas/tests/indexes/categorical/test_constructors.py
index 255e6a11d945d..2acf79ee0bced 100644
--- a/pandas/tests/indexes/categorical/test_constructors.py
+++ b/pandas/tests/indexes/categorical/test_constructors.py
@@ -1,7 +1,12 @@
import numpy as np
import pytest
-from pandas import Categorical, CategoricalDtype, CategoricalIndex, Index
+from pandas import (
+ Categorical,
+ CategoricalDtype,
+ CategoricalIndex,
+ Index,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/categorical/test_equals.py b/pandas/tests/indexes/categorical/test_equals.py
index 3f9a58c6a06cd..2648155c938b0 100644
--- a/pandas/tests/indexes/categorical/test_equals.py
+++ b/pandas/tests/indexes/categorical/test_equals.py
@@ -1,7 +1,11 @@
import numpy as np
import pytest
-from pandas import Categorical, CategoricalIndex, Index
+from pandas import (
+ Categorical,
+ CategoricalIndex,
+ Index,
+)
class TestEquals:
diff --git a/pandas/tests/indexes/categorical/test_indexing.py b/pandas/tests/indexes/categorical/test_indexing.py
index 7ec67d83e4b3b..490a68233367a 100644
--- a/pandas/tests/indexes/categorical/test_indexing.py
+++ b/pandas/tests/indexes/categorical/test_indexing.py
@@ -4,7 +4,12 @@
from pandas.errors import InvalidIndexError
import pandas as pd
-from pandas import CategoricalIndex, Index, IntervalIndex, Timestamp
+from pandas import (
+ CategoricalIndex,
+ Index,
+ IntervalIndex,
+ Timestamp,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/categorical/test_map.py b/pandas/tests/indexes/categorical/test_map.py
index c15818bc87f7c..71ee82981721d 100644
--- a/pandas/tests/indexes/categorical/test_map.py
+++ b/pandas/tests/indexes/categorical/test_map.py
@@ -2,7 +2,11 @@
import pytest
import pandas as pd
-from pandas import CategoricalIndex, Index, Series
+from pandas import (
+ CategoricalIndex,
+ Index,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/categorical/test_reindex.py b/pandas/tests/indexes/categorical/test_reindex.py
index 8228c5139ccdd..33139359cfe72 100644
--- a/pandas/tests/indexes/categorical/test_reindex.py
+++ b/pandas/tests/indexes/categorical/test_reindex.py
@@ -1,7 +1,13 @@
import numpy as np
import pytest
-from pandas import Categorical, CategoricalIndex, DataFrame, Index, Series
+from pandas import (
+ Categorical,
+ CategoricalIndex,
+ DataFrame,
+ Index,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/datetimelike_/test_equals.py b/pandas/tests/indexes/datetimelike_/test_equals.py
index 55a90f982a971..7221e560c1112 100644
--- a/pandas/tests/indexes/datetimelike_/test_equals.py
+++ b/pandas/tests/indexes/datetimelike_/test_equals.py
@@ -1,7 +1,10 @@
"""
Tests shared for DatetimeIndex/TimedeltaIndex/PeriodIndex
"""
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import numpy as np
import pytest
diff --git a/pandas/tests/indexes/datetimelike_/test_indexing.py b/pandas/tests/indexes/datetimelike_/test_indexing.py
index 51de446eea3e3..eb37c2c4ad2a3 100644
--- a/pandas/tests/indexes/datetimelike_/test_indexing.py
+++ b/pandas/tests/indexes/datetimelike_/test_indexing.py
@@ -2,7 +2,10 @@
import pytest
import pandas as pd
-from pandas import DatetimeIndex, Index
+from pandas import (
+ DatetimeIndex,
+ Index,
+)
import pandas._testing as tm
dtlike_dtypes = [
diff --git a/pandas/tests/indexes/datetimes/methods/test_factorize.py b/pandas/tests/indexes/datetimes/methods/test_factorize.py
index 6e095e29e47cd..90ad65c46046f 100644
--- a/pandas/tests/indexes/datetimes/methods/test_factorize.py
+++ b/pandas/tests/indexes/datetimes/methods/test_factorize.py
@@ -1,6 +1,11 @@
import numpy as np
-from pandas import DatetimeIndex, Index, date_range, factorize
+from pandas import (
+ DatetimeIndex,
+ Index,
+ date_range,
+ factorize,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/datetimes/methods/test_shift.py b/pandas/tests/indexes/datetimes/methods/test_shift.py
index 611df5d99cb9c..5a47b36a2a8d0 100644
--- a/pandas/tests/indexes/datetimes/methods/test_shift.py
+++ b/pandas/tests/indexes/datetimes/methods/test_shift.py
@@ -6,7 +6,11 @@
from pandas.errors import NullFrequencyError
import pandas as pd
-from pandas import DatetimeIndex, Series, date_range
+from pandas import (
+ DatetimeIndex,
+ Series,
+ date_range,
+)
import pandas._testing as tm
START, END = datetime(2009, 1, 1), datetime(2010, 1, 1)
diff --git a/pandas/tests/indexes/datetimes/methods/test_snap.py b/pandas/tests/indexes/datetimes/methods/test_snap.py
index 8baea9fe8341f..e591441c4f148 100644
--- a/pandas/tests/indexes/datetimes/methods/test_snap.py
+++ b/pandas/tests/indexes/datetimes/methods/test_snap.py
@@ -1,6 +1,9 @@
import pytest
-from pandas import DatetimeIndex, date_range
+from pandas import (
+ DatetimeIndex,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/datetimes/methods/test_to_series.py b/pandas/tests/indexes/datetimes/methods/test_to_series.py
index 5998fc0dde499..5a216d3c89899 100644
--- a/pandas/tests/indexes/datetimes/methods/test_to_series.py
+++ b/pandas/tests/indexes/datetimes/methods/test_to_series.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import DatetimeIndex, Series
+from pandas import (
+ DatetimeIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py
index 3f30a1a076eda..07cd89c23f1e0 100644
--- a/pandas/tests/indexes/datetimes/test_constructors.py
+++ b/pandas/tests/indexes/datetimes/test_constructors.py
@@ -1,4 +1,8 @@
-from datetime import datetime, timedelta, timezone
+from datetime import (
+ datetime,
+ timedelta,
+ timezone,
+)
from functools import partial
from operator import attrgetter
@@ -7,12 +11,25 @@
import pytest
import pytz
-from pandas._libs.tslibs import OutOfBoundsDatetime, conversion
+from pandas._libs.tslibs import (
+ OutOfBoundsDatetime,
+ conversion,
+)
import pandas as pd
-from pandas import DatetimeIndex, Index, Timestamp, date_range, offsets, to_datetime
+from pandas import (
+ DatetimeIndex,
+ Index,
+ Timestamp,
+ date_range,
+ offsets,
+ to_datetime,
+)
import pandas._testing as tm
-from pandas.core.arrays import DatetimeArray, period_array
+from pandas.core.arrays import (
+ DatetimeArray,
+ period_array,
+)
class TestDatetimeIndex:
diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py
index b8def8072a3b7..9399945bf1913 100644
--- a/pandas/tests/indexes/datetimes/test_date_range.py
+++ b/pandas/tests/indexes/datetimes/test_date_range.py
@@ -2,7 +2,11 @@
test date_range, bdate_range construction from the convenience range functions
"""
-from datetime import datetime, time, timedelta
+from datetime import (
+ datetime,
+ time,
+ timedelta,
+)
import numpy as np
import pytest
@@ -10,12 +14,25 @@
from pytz import timezone
from pandas._libs.tslibs import timezones
-from pandas._libs.tslibs.offsets import BDay, CDay, DateOffset, MonthEnd, prefix_mapping
+from pandas._libs.tslibs.offsets import (
+ BDay,
+ CDay,
+ DateOffset,
+ MonthEnd,
+ prefix_mapping,
+)
from pandas.errors import OutOfBoundsDatetime
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import DatetimeIndex, Timedelta, Timestamp, bdate_range, date_range, offsets
+from pandas import (
+ DatetimeIndex,
+ Timedelta,
+ Timestamp,
+ bdate_range,
+ date_range,
+ offsets,
+)
import pandas._testing as tm
from pandas.core.arrays.datetimes import generate_range
diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py
index 846bca2ecf2f6..a93c68e0c6d9a 100644
--- a/pandas/tests/indexes/datetimes/test_datetime.py
+++ b/pandas/tests/indexes/datetimes/test_datetime.py
@@ -5,7 +5,14 @@
import pytest
import pandas as pd
-from pandas import DataFrame, DatetimeIndex, Index, Timestamp, date_range, offsets
+from pandas import (
+ DataFrame,
+ DatetimeIndex,
+ Index,
+ Timestamp,
+ date_range,
+ offsets,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/datetimes/test_datetimelike.py b/pandas/tests/indexes/datetimes/test_datetimelike.py
index 0360b33a4a519..94303359958b3 100644
--- a/pandas/tests/indexes/datetimes/test_datetimelike.py
+++ b/pandas/tests/indexes/datetimes/test_datetimelike.py
@@ -1,7 +1,10 @@
""" generic tests from the Datetimelike class """
import pytest
-from pandas import DatetimeIndex, date_range
+from pandas import (
+ DatetimeIndex,
+ date_range,
+)
import pandas._testing as tm
from pandas.tests.indexes.datetimelike import DatetimeLike
diff --git a/pandas/tests/indexes/datetimes/test_delete.py b/pandas/tests/indexes/datetimes/test_delete.py
index 4fbb440bc89e5..e9de5a055a5c2 100644
--- a/pandas/tests/indexes/datetimes/test_delete.py
+++ b/pandas/tests/indexes/datetimes/test_delete.py
@@ -1,6 +1,10 @@
import pytest
-from pandas import DatetimeIndex, Series, date_range
+from pandas import (
+ DatetimeIndex,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/datetimes/test_formats.py b/pandas/tests/indexes/datetimes/test_formats.py
index a98a96b436107..36046aaeacaae 100644
--- a/pandas/tests/indexes/datetimes/test_formats.py
+++ b/pandas/tests/indexes/datetimes/test_formats.py
@@ -6,7 +6,10 @@
import pytz
import pandas as pd
-from pandas import DatetimeIndex, Series
+from pandas import (
+ DatetimeIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py
index 3e935d0dfdd5f..819ec52e1a52f 100644
--- a/pandas/tests/indexes/datetimes/test_indexing.py
+++ b/pandas/tests/indexes/datetimes/test_indexing.py
@@ -1,4 +1,9 @@
-from datetime import date, datetime, time, timedelta
+from datetime import (
+ date,
+ datetime,
+ time,
+ timedelta,
+)
import numpy as np
import pytest
@@ -6,10 +11,20 @@
from pandas.errors import InvalidIndexError
import pandas as pd
-from pandas import DatetimeIndex, Index, Timestamp, bdate_range, date_range, notna
+from pandas import (
+ DatetimeIndex,
+ Index,
+ Timestamp,
+ bdate_range,
+ date_range,
+ notna,
+)
import pandas._testing as tm
-from pandas.tseries.offsets import BDay, CDay
+from pandas.tseries.offsets import (
+ BDay,
+ CDay,
+)
START, END = datetime(2009, 1, 1), datetime(2010, 1, 1)
diff --git a/pandas/tests/indexes/datetimes/test_insert.py b/pandas/tests/indexes/datetimes/test_insert.py
index 6dbd1287b7306..bf3d5bf88149e 100644
--- a/pandas/tests/indexes/datetimes/test_insert.py
+++ b/pandas/tests/indexes/datetimes/test_insert.py
@@ -4,7 +4,14 @@
import pytest
import pytz
-from pandas import NA, DatetimeIndex, Index, NaT, Timestamp, date_range
+from pandas import (
+ NA,
+ DatetimeIndex,
+ Index,
+ NaT,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/datetimes/test_join.py b/pandas/tests/indexes/datetimes/test_join.py
index 9a9c94fa19e6d..8b633e8db8836 100644
--- a/pandas/tests/indexes/datetimes/test_join.py
+++ b/pandas/tests/indexes/datetimes/test_join.py
@@ -3,10 +3,19 @@
import numpy as np
import pytest
-from pandas import DatetimeIndex, Index, Timestamp, date_range, to_datetime
+from pandas import (
+ DatetimeIndex,
+ Index,
+ Timestamp,
+ date_range,
+ to_datetime,
+)
import pandas._testing as tm
-from pandas.tseries.offsets import BDay, BMonthEnd
+from pandas.tseries.offsets import (
+ BDay,
+ BMonthEnd,
+)
class TestJoin:
diff --git a/pandas/tests/indexes/datetimes/test_map.py b/pandas/tests/indexes/datetimes/test_map.py
index 2644ad7616b51..45698ef225151 100644
--- a/pandas/tests/indexes/datetimes/test_map.py
+++ b/pandas/tests/indexes/datetimes/test_map.py
@@ -1,6 +1,12 @@
import pytest
-from pandas import DatetimeIndex, Index, MultiIndex, Period, date_range
+from pandas import (
+ DatetimeIndex,
+ Index,
+ MultiIndex,
+ Period,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/datetimes/test_misc.py b/pandas/tests/indexes/datetimes/test_misc.py
index 333a1ac169bb7..d230aa43e43d1 100644
--- a/pandas/tests/indexes/datetimes/test_misc.py
+++ b/pandas/tests/indexes/datetimes/test_misc.py
@@ -7,7 +7,14 @@
import pytest
import pandas as pd
-from pandas import DatetimeIndex, Index, Timedelta, Timestamp, date_range, offsets
+from pandas import (
+ DatetimeIndex,
+ Index,
+ Timedelta,
+ Timestamp,
+ date_range,
+ offsets,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py
index 090e21be254e3..676c0ee99ef7c 100644
--- a/pandas/tests/indexes/datetimes/test_ops.py
+++ b/pandas/tests/indexes/datetimes/test_ops.py
@@ -18,7 +18,11 @@
)
import pandas._testing as tm
-from pandas.tseries.offsets import BDay, Day, Hour
+from pandas.tseries.offsets import (
+ BDay,
+ Day,
+ Hour,
+)
START, END = datetime(2009, 1, 1), datetime(2010, 1, 1)
diff --git a/pandas/tests/indexes/datetimes/test_pickle.py b/pandas/tests/indexes/datetimes/test_pickle.py
index bb08d4c66cb3c..3905daa9688ac 100644
--- a/pandas/tests/indexes/datetimes/test_pickle.py
+++ b/pandas/tests/indexes/datetimes/test_pickle.py
@@ -1,6 +1,10 @@
import pytest
-from pandas import NaT, date_range, to_datetime
+from pandas import (
+ NaT,
+ date_range,
+ to_datetime,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/datetimes/test_reindex.py b/pandas/tests/indexes/datetimes/test_reindex.py
index fa847ad072ada..e4911aa3c4a29 100644
--- a/pandas/tests/indexes/datetimes/test_reindex.py
+++ b/pandas/tests/indexes/datetimes/test_reindex.py
@@ -2,7 +2,10 @@
import numpy as np
-from pandas import DatetimeIndex, date_range
+from pandas import (
+ DatetimeIndex,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/datetimes/test_scalar_compat.py b/pandas/tests/indexes/datetimes/test_scalar_compat.py
index d6016b9e14743..40a03396cf98e 100644
--- a/pandas/tests/indexes/datetimes/test_scalar_compat.py
+++ b/pandas/tests/indexes/datetimes/test_scalar_compat.py
@@ -6,11 +6,18 @@
import numpy as np
import pytest
-from pandas._libs.tslibs import OutOfBoundsDatetime, to_offset
+from pandas._libs.tslibs import (
+ OutOfBoundsDatetime,
+ to_offset,
+)
from pandas._libs.tslibs.offsets import INVALID_FREQ_ERR_MSG
import pandas as pd
-from pandas import DatetimeIndex, Timestamp, date_range
+from pandas import (
+ DatetimeIndex,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/datetimes/test_setops.py b/pandas/tests/indexes/datetimes/test_setops.py
index c7632c3c5c455..513a47d6be7ab 100644
--- a/pandas/tests/indexes/datetimes/test_setops.py
+++ b/pandas/tests/indexes/datetimes/test_setops.py
@@ -17,7 +17,11 @@
)
import pandas._testing as tm
-from pandas.tseries.offsets import BMonthEnd, Minute, MonthEnd
+from pandas.tseries.offsets import (
+ BMonthEnd,
+ Minute,
+ MonthEnd,
+)
START, END = datetime(2009, 1, 1), datetime(2010, 1, 1)
diff --git a/pandas/tests/indexes/datetimes/test_timezones.py b/pandas/tests/indexes/datetimes/test_timezones.py
index e448cf0b578ae..3ab58471cdbed 100644
--- a/pandas/tests/indexes/datetimes/test_timezones.py
+++ b/pandas/tests/indexes/datetimes/test_timezones.py
@@ -1,15 +1,27 @@
"""
Tests for DatetimeIndex timezone-related methods
"""
-from datetime import date, datetime, time, timedelta, tzinfo
+from datetime import (
+ date,
+ datetime,
+ time,
+ timedelta,
+ tzinfo,
+)
import dateutil
-from dateutil.tz import gettz, tzlocal
+from dateutil.tz import (
+ gettz,
+ tzlocal,
+)
import numpy as np
import pytest
import pytz
-from pandas._libs.tslibs import conversion, timezones
+from pandas._libs.tslibs import (
+ conversion,
+ timezones,
+)
import pandas.util._test_decorators as td
import pandas as pd
diff --git a/pandas/tests/indexes/datetimes/test_unique.py b/pandas/tests/indexes/datetimes/test_unique.py
index f85cc87ee88a8..a6df9cb748294 100644
--- a/pandas/tests/indexes/datetimes/test_unique.py
+++ b/pandas/tests/indexes/datetimes/test_unique.py
@@ -1,8 +1,15 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import pytest
-from pandas import DatetimeIndex, NaT, Timestamp
+from pandas import (
+ DatetimeIndex,
+ NaT,
+ Timestamp,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/interval/test_astype.py b/pandas/tests/indexes/interval/test_astype.py
index c269d6ff11896..f421a4695138c 100644
--- a/pandas/tests/indexes/interval/test_astype.py
+++ b/pandas/tests/indexes/interval/test_astype.py
@@ -3,7 +3,10 @@
import numpy as np
import pytest
-from pandas.core.dtypes.dtypes import CategoricalDtype, IntervalDtype
+from pandas.core.dtypes.dtypes import (
+ CategoricalDtype,
+ IntervalDtype,
+)
from pandas import (
CategoricalIndex,
diff --git a/pandas/tests/indexes/interval/test_base.py b/pandas/tests/indexes/interval/test_base.py
index 738f0be2dbc86..8bf418a2fc731 100644
--- a/pandas/tests/indexes/interval/test_base.py
+++ b/pandas/tests/indexes/interval/test_base.py
@@ -1,7 +1,11 @@
import numpy as np
import pytest
-from pandas import IntervalIndex, Series, date_range
+from pandas import (
+ IntervalIndex,
+ Series,
+ date_range,
+)
import pandas._testing as tm
from pandas.tests.indexes.common import Base
diff --git a/pandas/tests/indexes/interval/test_equals.py b/pandas/tests/indexes/interval/test_equals.py
index e53a836366432..87e2348e5fdb3 100644
--- a/pandas/tests/indexes/interval/test_equals.py
+++ b/pandas/tests/indexes/interval/test_equals.py
@@ -1,6 +1,9 @@
import numpy as np
-from pandas import IntervalIndex, date_range
+from pandas import (
+ IntervalIndex,
+ date_range,
+)
class TestEquals:
diff --git a/pandas/tests/indexes/interval/test_setops.py b/pandas/tests/indexes/interval/test_setops.py
index e3b25ca4993c6..059b0b75f4190 100644
--- a/pandas/tests/indexes/interval/test_setops.py
+++ b/pandas/tests/indexes/interval/test_setops.py
@@ -1,7 +1,12 @@
import numpy as np
import pytest
-from pandas import Index, IntervalIndex, Timestamp, interval_range
+from pandas import (
+ Index,
+ IntervalIndex,
+ Timestamp,
+ interval_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/multi/conftest.py b/pandas/tests/indexes/multi/conftest.py
index ce477485bb21e..9d0a2fa81b53b 100644
--- a/pandas/tests/indexes/multi/conftest.py
+++ b/pandas/tests/indexes/multi/conftest.py
@@ -2,7 +2,10 @@
import pytest
import pandas as pd
-from pandas import Index, MultiIndex
+from pandas import (
+ Index,
+ MultiIndex,
+)
# Note: identical the the "multi" entry in the top-level "index" fixture
diff --git a/pandas/tests/indexes/multi/test_analytics.py b/pandas/tests/indexes/multi/test_analytics.py
index e842fafda0327..83515d7fb82b1 100644
--- a/pandas/tests/indexes/multi/test_analytics.py
+++ b/pandas/tests/indexes/multi/test_analytics.py
@@ -4,7 +4,12 @@
from pandas.compat import np_version_under1p17
import pandas as pd
-from pandas import Index, MultiIndex, date_range, period_range
+from pandas import (
+ Index,
+ MultiIndex,
+ date_range,
+ period_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/multi/test_constructors.py b/pandas/tests/indexes/multi/test_constructors.py
index 11687b535d2b7..c4b4562fe9e47 100644
--- a/pandas/tests/indexes/multi/test_constructors.py
+++ b/pandas/tests/indexes/multi/test_constructors.py
@@ -1,4 +1,7 @@
-from datetime import date, datetime
+from datetime import (
+ date,
+ datetime,
+)
import itertools
import numpy as np
@@ -9,7 +12,12 @@
from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
import pandas as pd
-from pandas import Index, MultiIndex, Series, date_range
+from pandas import (
+ Index,
+ MultiIndex,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/multi/test_conversion.py b/pandas/tests/indexes/multi/test_conversion.py
index c80548783d148..2d504b8172ba8 100644
--- a/pandas/tests/indexes/multi/test_conversion.py
+++ b/pandas/tests/indexes/multi/test_conversion.py
@@ -2,7 +2,10 @@
import pytest
import pandas as pd
-from pandas import DataFrame, MultiIndex
+from pandas import (
+ DataFrame,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/multi/test_copy.py b/pandas/tests/indexes/multi/test_copy.py
index 5dd74819444cf..9a0e4bc0996be 100644
--- a/pandas/tests/indexes/multi/test_copy.py
+++ b/pandas/tests/indexes/multi/test_copy.py
@@ -1,4 +1,7 @@
-from copy import copy, deepcopy
+from copy import (
+ copy,
+ deepcopy,
+)
import pytest
diff --git a/pandas/tests/indexes/multi/test_drop.py b/pandas/tests/indexes/multi/test_drop.py
index 76d704737688d..2dbc4185256de 100644
--- a/pandas/tests/indexes/multi/test_drop.py
+++ b/pandas/tests/indexes/multi/test_drop.py
@@ -6,7 +6,10 @@
from pandas.errors import PerformanceWarning
import pandas as pd
-from pandas import Index, MultiIndex
+from pandas import (
+ Index,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/multi/test_duplicates.py b/pandas/tests/indexes/multi/test_duplicates.py
index 9497ccb46da07..bc0b6e0b028a8 100644
--- a/pandas/tests/indexes/multi/test_duplicates.py
+++ b/pandas/tests/indexes/multi/test_duplicates.py
@@ -5,7 +5,10 @@
from pandas._libs import hashtable
-from pandas import DatetimeIndex, MultiIndex
+from pandas import (
+ DatetimeIndex,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/multi/test_equivalence.py b/pandas/tests/indexes/multi/test_equivalence.py
index c44f7622c04dd..be27091618b0a 100644
--- a/pandas/tests/indexes/multi/test_equivalence.py
+++ b/pandas/tests/indexes/multi/test_equivalence.py
@@ -2,7 +2,11 @@
import pytest
import pandas as pd
-from pandas import Index, MultiIndex, Series
+from pandas import (
+ Index,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/multi/test_formats.py b/pandas/tests/indexes/multi/test_formats.py
index 4e56b7c73c64f..17699aa32929e 100644
--- a/pandas/tests/indexes/multi/test_formats.py
+++ b/pandas/tests/indexes/multi/test_formats.py
@@ -4,7 +4,10 @@
import pytest
import pandas as pd
-from pandas import Index, MultiIndex
+from pandas import (
+ Index,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/multi/test_get_level_values.py b/pandas/tests/indexes/multi/test_get_level_values.py
index f976515870259..25b4501a03adb 100644
--- a/pandas/tests/indexes/multi/test_get_level_values.py
+++ b/pandas/tests/indexes/multi/test_get_level_values.py
@@ -1,7 +1,13 @@
import numpy as np
import pandas as pd
-from pandas import CategoricalIndex, Index, MultiIndex, Timestamp, date_range
+from pandas import (
+ CategoricalIndex,
+ Index,
+ MultiIndex,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
@@ -94,7 +100,10 @@ def test_get_level_values_na():
def test_get_level_values_when_periods():
# GH33131. See also discussion in GH32669.
# This test can probably be removed when PeriodIndex._engine is removed.
- from pandas import Period, PeriodIndex
+ from pandas import (
+ Period,
+ PeriodIndex,
+ )
idx = MultiIndex.from_arrays(
[PeriodIndex([Period("2019Q1"), Period("2019Q2")], name="b")]
diff --git a/pandas/tests/indexes/multi/test_get_set.py b/pandas/tests/indexes/multi/test_get_set.py
index d43ee3330ef08..0c561395788ad 100644
--- a/pandas/tests/indexes/multi/test_get_set.py
+++ b/pandas/tests/indexes/multi/test_get_set.py
@@ -4,7 +4,10 @@
from pandas.core.dtypes.dtypes import DatetimeTZDtype
import pandas as pd
-from pandas import CategoricalIndex, MultiIndex
+from pandas import (
+ CategoricalIndex,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/multi/test_indexing.py b/pandas/tests/indexes/multi/test_indexing.py
index b6f131e5c1c9b..fba94960ddaad 100644
--- a/pandas/tests/indexes/multi/test_indexing.py
+++ b/pandas/tests/indexes/multi/test_indexing.py
@@ -3,10 +3,18 @@
import numpy as np
import pytest
-from pandas.errors import InvalidIndexError, PerformanceWarning
+from pandas.errors import (
+ InvalidIndexError,
+ PerformanceWarning,
+)
import pandas as pd
-from pandas import Categorical, Index, MultiIndex, date_range
+from pandas import (
+ Categorical,
+ Index,
+ MultiIndex,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/multi/test_integrity.py b/pandas/tests/indexes/multi/test_integrity.py
index 2fdf6d1913a0f..ff0c2a0d67885 100644
--- a/pandas/tests/indexes/multi/test_integrity.py
+++ b/pandas/tests/indexes/multi/test_integrity.py
@@ -6,7 +6,11 @@
from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
import pandas as pd
-from pandas import IntervalIndex, MultiIndex, RangeIndex
+from pandas import (
+ IntervalIndex,
+ MultiIndex,
+ RangeIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/multi/test_join.py b/pandas/tests/indexes/multi/test_join.py
index 6b6b9346fe1fe..42a3c28e6797b 100644
--- a/pandas/tests/indexes/multi/test_join.py
+++ b/pandas/tests/indexes/multi/test_join.py
@@ -2,7 +2,10 @@
import pytest
import pandas as pd
-from pandas import Index, MultiIndex
+from pandas import (
+ Index,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/multi/test_monotonic.py b/pandas/tests/indexes/multi/test_monotonic.py
index 11bcd61383a7c..b31e50330d3cd 100644
--- a/pandas/tests/indexes/multi/test_monotonic.py
+++ b/pandas/tests/indexes/multi/test_monotonic.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import Index, MultiIndex
+from pandas import (
+ Index,
+ MultiIndex,
+)
def test_is_monotonic_increasing():
diff --git a/pandas/tests/indexes/multi/test_partial_indexing.py b/pandas/tests/indexes/multi/test_partial_indexing.py
index 7dfe0b20a7478..286522f6b946d 100644
--- a/pandas/tests/indexes/multi/test_partial_indexing.py
+++ b/pandas/tests/indexes/multi/test_partial_indexing.py
@@ -1,6 +1,11 @@
import pytest
-from pandas import DataFrame, IndexSlice, MultiIndex, date_range
+from pandas import (
+ DataFrame,
+ IndexSlice,
+ MultiIndex,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/multi/test_reindex.py b/pandas/tests/indexes/multi/test_reindex.py
index ceb14aa82a76c..446a52ef02581 100644
--- a/pandas/tests/indexes/multi/test_reindex.py
+++ b/pandas/tests/indexes/multi/test_reindex.py
@@ -2,7 +2,10 @@
import pytest
import pandas as pd
-from pandas import Index, MultiIndex
+from pandas import (
+ Index,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/multi/test_reshape.py b/pandas/tests/indexes/multi/test_reshape.py
index 6d8a396119ef3..f8afc49b4b41c 100644
--- a/pandas/tests/indexes/multi/test_reshape.py
+++ b/pandas/tests/indexes/multi/test_reshape.py
@@ -5,7 +5,10 @@
import pytz
import pandas as pd
-from pandas import Index, MultiIndex
+from pandas import (
+ Index,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/multi/test_setops.py b/pandas/tests/indexes/multi/test_setops.py
index f872315374174..85866e7d97bcc 100644
--- a/pandas/tests/indexes/multi/test_setops.py
+++ b/pandas/tests/indexes/multi/test_setops.py
@@ -2,7 +2,11 @@
import pytest
import pandas as pd
-from pandas import Index, MultiIndex, Series
+from pandas import (
+ Index,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/multi/test_sorting.py b/pandas/tests/indexes/multi/test_sorting.py
index 5f957f54c05cd..63d3fe53f9db5 100644
--- a/pandas/tests/indexes/multi/test_sorting.py
+++ b/pandas/tests/indexes/multi/test_sorting.py
@@ -3,9 +3,18 @@
import numpy as np
import pytest
-from pandas.errors import PerformanceWarning, UnsortedIndexError
+from pandas.errors import (
+ PerformanceWarning,
+ UnsortedIndexError,
+)
-from pandas import CategoricalIndex, DataFrame, Index, MultiIndex, RangeIndex
+from pandas import (
+ CategoricalIndex,
+ DataFrame,
+ Index,
+ MultiIndex,
+ RangeIndex,
+)
import pandas._testing as tm
from pandas.core.indexes.frozen import FrozenList
diff --git a/pandas/tests/indexes/numeric/test_astype.py b/pandas/tests/indexes/numeric/test_astype.py
index 1771f4336df67..bda66856fb57a 100644
--- a/pandas/tests/indexes/numeric/test_astype.py
+++ b/pandas/tests/indexes/numeric/test_astype.py
@@ -5,7 +5,11 @@
from pandas.core.dtypes.common import pandas_dtype
-from pandas import Float64Index, Index, Int64Index
+from pandas import (
+ Float64Index,
+ Index,
+ Int64Index,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/numeric/test_join.py b/pandas/tests/indexes/numeric/test_join.py
index c8dffa411e5fd..43d731f8c3142 100644
--- a/pandas/tests/indexes/numeric/test_join.py
+++ b/pandas/tests/indexes/numeric/test_join.py
@@ -1,7 +1,11 @@
import numpy as np
import pytest
-from pandas import Index, Int64Index, UInt64Index
+from pandas import (
+ Index,
+ Int64Index,
+ UInt64Index,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/numeric/test_setops.py b/pandas/tests/indexes/numeric/test_setops.py
index 27e19468dddd2..5a7db9858dbad 100644
--- a/pandas/tests/indexes/numeric/test_setops.py
+++ b/pandas/tests/indexes/numeric/test_setops.py
@@ -1,9 +1,18 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import numpy as np
import pytest
-from pandas import Float64Index, Index, Int64Index, RangeIndex, UInt64Index
+from pandas import (
+ Float64Index,
+ Index,
+ Int64Index,
+ RangeIndex,
+ UInt64Index,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/period/methods/test_asfreq.py b/pandas/tests/indexes/period/methods/test_asfreq.py
index 8c04ac1177676..23b88fb6ab0d3 100644
--- a/pandas/tests/indexes/period/methods/test_asfreq.py
+++ b/pandas/tests/indexes/period/methods/test_asfreq.py
@@ -1,6 +1,9 @@
import pytest
-from pandas import PeriodIndex, period_range
+from pandas import (
+ PeriodIndex,
+ period_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/period/methods/test_fillna.py b/pandas/tests/indexes/period/methods/test_fillna.py
index 602e87333a6c1..12a07bac25a59 100644
--- a/pandas/tests/indexes/period/methods/test_fillna.py
+++ b/pandas/tests/indexes/period/methods/test_fillna.py
@@ -1,4 +1,9 @@
-from pandas import Index, NaT, Period, PeriodIndex
+from pandas import (
+ Index,
+ NaT,
+ Period,
+ PeriodIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/period/methods/test_shift.py b/pandas/tests/indexes/period/methods/test_shift.py
index 278bb7f07c679..730172ca56938 100644
--- a/pandas/tests/indexes/period/methods/test_shift.py
+++ b/pandas/tests/indexes/period/methods/test_shift.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import PeriodIndex, period_range
+from pandas import (
+ PeriodIndex,
+ period_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/period/test_formats.py b/pandas/tests/indexes/period/test_formats.py
index b60ae8819023f..7d054a7af4a4d 100644
--- a/pandas/tests/indexes/period/test_formats.py
+++ b/pandas/tests/indexes/period/test_formats.py
@@ -2,7 +2,10 @@
import pytest
import pandas as pd
-from pandas import PeriodIndex, Series
+from pandas import (
+ PeriodIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py
index 00babd2d56aeb..fcf01f850711b 100644
--- a/pandas/tests/indexes/period/test_indexing.py
+++ b/pandas/tests/indexes/period/test_indexing.py
@@ -1,4 +1,7 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import re
import numpy as np
diff --git a/pandas/tests/indexes/period/test_join.py b/pandas/tests/indexes/period/test_join.py
index e895bb81ea061..2f16daa36d1fd 100644
--- a/pandas/tests/indexes/period/test_join.py
+++ b/pandas/tests/indexes/period/test_join.py
@@ -3,7 +3,11 @@
from pandas._libs.tslibs import IncompatibleFrequency
-from pandas import Index, PeriodIndex, period_range
+from pandas import (
+ Index,
+ PeriodIndex,
+ period_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/period/test_monotonic.py b/pandas/tests/indexes/period/test_monotonic.py
index e06e7da1773f5..15cb8f71cdcf3 100644
--- a/pandas/tests/indexes/period/test_monotonic.py
+++ b/pandas/tests/indexes/period/test_monotonic.py
@@ -1,4 +1,7 @@
-from pandas import Period, PeriodIndex
+from pandas import (
+ Period,
+ PeriodIndex,
+)
def test_is_monotonic_increasing():
diff --git a/pandas/tests/indexes/period/test_ops.py b/pandas/tests/indexes/period/test_ops.py
index fd0a77bf7930b..52f8de27cb6c6 100644
--- a/pandas/tests/indexes/period/test_ops.py
+++ b/pandas/tests/indexes/period/test_ops.py
@@ -2,7 +2,12 @@
import pytest
import pandas as pd
-from pandas import Index, NaT, PeriodIndex, Series
+from pandas import (
+ Index,
+ NaT,
+ PeriodIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/period/test_partial_slicing.py b/pandas/tests/indexes/period/test_partial_slicing.py
index f354682bf6f70..b0e573250d02e 100644
--- a/pandas/tests/indexes/period/test_partial_slicing.py
+++ b/pandas/tests/indexes/period/test_partial_slicing.py
@@ -1,7 +1,12 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series, date_range, period_range
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+ period_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/period/test_period_range.py b/pandas/tests/indexes/period/test_period_range.py
index 68b48a55957ff..a5be19731b54a 100644
--- a/pandas/tests/indexes/period/test_period_range.py
+++ b/pandas/tests/indexes/period/test_period_range.py
@@ -1,7 +1,13 @@
import numpy as np
import pytest
-from pandas import NaT, Period, PeriodIndex, date_range, period_range
+from pandas import (
+ NaT,
+ Period,
+ PeriodIndex,
+ date_range,
+ period_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/period/test_scalar_compat.py b/pandas/tests/indexes/period/test_scalar_compat.py
index e9d17e7e20778..a42b8496b0bcf 100644
--- a/pandas/tests/indexes/period/test_scalar_compat.py
+++ b/pandas/tests/indexes/period/test_scalar_compat.py
@@ -1,6 +1,10 @@
"""Tests for PeriodIndex behaving like a vectorized Period scalar"""
-from pandas import Timedelta, date_range, period_range
+from pandas import (
+ Timedelta,
+ date_range,
+ period_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/period/test_searchsorted.py b/pandas/tests/indexes/period/test_searchsorted.py
index 5e1a3b899755d..af243eeccc7a4 100644
--- a/pandas/tests/indexes/period/test_searchsorted.py
+++ b/pandas/tests/indexes/period/test_searchsorted.py
@@ -4,7 +4,13 @@
from pandas._libs.tslibs import IncompatibleFrequency
from pandas.compat import np_version_under1p18
-from pandas import NaT, Period, PeriodIndex, Series, array
+from pandas import (
+ NaT,
+ Period,
+ PeriodIndex,
+ Series,
+ array,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/period/test_setops.py b/pandas/tests/indexes/period/test_setops.py
index 02c007c394ff5..fcd2c7d3422e1 100644
--- a/pandas/tests/indexes/period/test_setops.py
+++ b/pandas/tests/indexes/period/test_setops.py
@@ -1,7 +1,11 @@
import numpy as np
import pandas as pd
-from pandas import PeriodIndex, date_range, period_range
+from pandas import (
+ PeriodIndex,
+ date_range,
+ period_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/period/test_tools.py b/pandas/tests/indexes/period/test_tools.py
index 82c13240c6bf2..82a3721b0cbb9 100644
--- a/pandas/tests/indexes/period/test_tools.py
+++ b/pandas/tests/indexes/period/test_tools.py
@@ -1,7 +1,11 @@
import numpy as np
import pytest
-from pandas import Period, PeriodIndex, period_range
+from pandas import (
+ Period,
+ PeriodIndex,
+ period_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/ranges/test_constructors.py b/pandas/tests/indexes/ranges/test_constructors.py
index f83c885a7850b..599df3732a33b 100644
--- a/pandas/tests/indexes/ranges/test_constructors.py
+++ b/pandas/tests/indexes/ranges/test_constructors.py
@@ -3,7 +3,11 @@
import numpy as np
import pytest
-from pandas import Index, RangeIndex, Series
+from pandas import (
+ Index,
+ RangeIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/ranges/test_join.py b/pandas/tests/indexes/ranges/test_join.py
index 76013d2b7a387..6668a7c6a3d02 100644
--- a/pandas/tests/indexes/ranges/test_join.py
+++ b/pandas/tests/indexes/ranges/test_join.py
@@ -1,6 +1,10 @@
import numpy as np
-from pandas import Index, Int64Index, RangeIndex
+from pandas import (
+ Index,
+ Int64Index,
+ RangeIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/ranges/test_range.py b/pandas/tests/indexes/ranges/test_range.py
index 57df2a1e83418..fb670c508a8f1 100644
--- a/pandas/tests/indexes/ranges/test_range.py
+++ b/pandas/tests/indexes/ranges/test_range.py
@@ -4,7 +4,12 @@
from pandas.core.dtypes.common import ensure_platform_int
import pandas as pd
-from pandas import Float64Index, Index, Int64Index, RangeIndex
+from pandas import (
+ Float64Index,
+ Index,
+ Int64Index,
+ RangeIndex,
+)
import pandas._testing as tm
from pandas.tests.indexes.test_numeric import Numeric
diff --git a/pandas/tests/indexes/ranges/test_setops.py b/pandas/tests/indexes/ranges/test_setops.py
index 660269f2d02a4..ba938f82e9d89 100644
--- a/pandas/tests/indexes/ranges/test_setops.py
+++ b/pandas/tests/indexes/ranges/test_setops.py
@@ -1,9 +1,17 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import numpy as np
import pytest
-from pandas import Index, Int64Index, RangeIndex, UInt64Index
+from pandas import (
+ Index,
+ Int64Index,
+ RangeIndex,
+ UInt64Index,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index 5fd1a15416e23..127f0432efa01 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -1,5 +1,8 @@
from collections import defaultdict
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
from io import StringIO
import math
import operator
@@ -9,7 +12,10 @@
import pytest
from pandas._libs.tslib import Timestamp
-from pandas.compat import IS64, np_datetime64_compat
+from pandas.compat import (
+ IS64,
+ np_datetime64_compat,
+)
from pandas.util._test_decorators import async_mark
import pandas as pd
diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py
index e5895c0b507e3..97fe35bb7f2c9 100644
--- a/pandas/tests/indexes/test_common.py
+++ b/pandas/tests/indexes/test_common.py
@@ -11,7 +11,10 @@
from pandas._libs.tslibs import iNaT
from pandas.compat import IS64
-from pandas.core.dtypes.common import is_period_dtype, needs_i8_conversion
+from pandas.core.dtypes.common import (
+ is_period_dtype,
+ needs_i8_conversion,
+)
import pandas as pd
from pandas import (
@@ -108,7 +111,10 @@ def test_set_name_methods(self, index_flat):
assert index.names == [name]
def test_copy_and_deepcopy(self, index_flat):
- from copy import copy, deepcopy
+ from copy import (
+ copy,
+ deepcopy,
+ )
index = index_flat
diff --git a/pandas/tests/indexes/test_engines.py b/pandas/tests/indexes/test_engines.py
index 9ea70a457e516..52af29d999fcc 100644
--- a/pandas/tests/indexes/test_engines.py
+++ b/pandas/tests/indexes/test_engines.py
@@ -3,7 +3,10 @@
import numpy as np
import pytest
-from pandas._libs import algos as libalgos, index as libindex
+from pandas._libs import (
+ algos as libalgos,
+ index as libindex,
+)
import pandas as pd
import pandas._testing as tm
diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py
index d6b92999305b2..74c961418176b 100644
--- a/pandas/tests/indexes/test_numeric.py
+++ b/pandas/tests/indexes/test_numeric.py
@@ -6,7 +6,14 @@
from pandas._libs.tslibs import Timestamp
import pandas as pd
-from pandas import Float64Index, Index, Int64Index, RangeIndex, Series, UInt64Index
+from pandas import (
+ Float64Index,
+ Index,
+ Int64Index,
+ RangeIndex,
+ Series,
+ UInt64Index,
+)
import pandas._testing as tm
from pandas.tests.indexes.common import Base
diff --git a/pandas/tests/indexes/test_numpy_compat.py b/pandas/tests/indexes/test_numpy_compat.py
index f7f6456f736c0..1ee7c5547ecf9 100644
--- a/pandas/tests/indexes/test_numpy_compat.py
+++ b/pandas/tests/indexes/test_numpy_compat.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas.compat import np_version_under1p17, np_version_under1p18
+from pandas.compat import (
+ np_version_under1p17,
+ np_version_under1p18,
+)
from pandas import (
DatetimeIndex,
diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py
index 746b6d6fb6e2a..11514b9f04b59 100644
--- a/pandas/tests/indexes/test_setops.py
+++ b/pandas/tests/indexes/test_setops.py
@@ -20,7 +20,10 @@
UInt64Index,
)
import pandas._testing as tm
-from pandas.api.types import is_datetime64tz_dtype, pandas_dtype
+from pandas.api.types import (
+ is_datetime64tz_dtype,
+ pandas_dtype,
+)
COMPATIBLE_INCONSISTENT_PAIRS = {
(Int64Index, RangeIndex): (tm.makeIntIndex, tm.makeRangeIndex),
diff --git a/pandas/tests/indexes/timedeltas/methods/test_factorize.py b/pandas/tests/indexes/timedeltas/methods/test_factorize.py
index dcf8cefba70fd..24ab3888412d0 100644
--- a/pandas/tests/indexes/timedeltas/methods/test_factorize.py
+++ b/pandas/tests/indexes/timedeltas/methods/test_factorize.py
@@ -1,6 +1,10 @@
import numpy as np
-from pandas import TimedeltaIndex, factorize, timedelta_range
+from pandas import (
+ TimedeltaIndex,
+ factorize,
+ timedelta_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/timedeltas/methods/test_fillna.py b/pandas/tests/indexes/timedeltas/methods/test_fillna.py
index 47b2f2ff597f4..40aa95d0a4605 100644
--- a/pandas/tests/indexes/timedeltas/methods/test_fillna.py
+++ b/pandas/tests/indexes/timedeltas/methods/test_fillna.py
@@ -1,4 +1,9 @@
-from pandas import Index, NaT, Timedelta, TimedeltaIndex
+from pandas import (
+ Index,
+ NaT,
+ Timedelta,
+ TimedeltaIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/timedeltas/test_constructors.py b/pandas/tests/indexes/timedeltas/test_constructors.py
index ffc10faaf8150..20b8ffc062982 100644
--- a/pandas/tests/indexes/timedeltas/test_constructors.py
+++ b/pandas/tests/indexes/timedeltas/test_constructors.py
@@ -4,9 +4,17 @@
import pytest
import pandas as pd
-from pandas import Timedelta, TimedeltaIndex, timedelta_range, to_timedelta
+from pandas import (
+ Timedelta,
+ TimedeltaIndex,
+ timedelta_range,
+ to_timedelta,
+)
import pandas._testing as tm
-from pandas.core.arrays.timedeltas import TimedeltaArray, sequence_to_td64ns
+from pandas.core.arrays.timedeltas import (
+ TimedeltaArray,
+ sequence_to_td64ns,
+)
class TestTimedeltaIndex:
diff --git a/pandas/tests/indexes/timedeltas/test_delete.py b/pandas/tests/indexes/timedeltas/test_delete.py
index 63f2b450aa818..6e6f54702ce1a 100644
--- a/pandas/tests/indexes/timedeltas/test_delete.py
+++ b/pandas/tests/indexes/timedeltas/test_delete.py
@@ -1,4 +1,7 @@
-from pandas import TimedeltaIndex, timedelta_range
+from pandas import (
+ TimedeltaIndex,
+ timedelta_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/timedeltas/test_formats.py b/pandas/tests/indexes/timedeltas/test_formats.py
index 8a8e2abd17165..751f9e4cc9eee 100644
--- a/pandas/tests/indexes/timedeltas/test_formats.py
+++ b/pandas/tests/indexes/timedeltas/test_formats.py
@@ -1,7 +1,10 @@
import pytest
import pandas as pd
-from pandas import Series, TimedeltaIndex
+from pandas import (
+ Series,
+ TimedeltaIndex,
+)
class TestTimedeltaIndexRendering:
diff --git a/pandas/tests/indexes/timedeltas/test_indexing.py b/pandas/tests/indexes/timedeltas/test_indexing.py
index 34316e1470573..7acfb50fe944b 100644
--- a/pandas/tests/indexes/timedeltas/test_indexing.py
+++ b/pandas/tests/indexes/timedeltas/test_indexing.py
@@ -1,11 +1,20 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import re
import numpy as np
import pytest
import pandas as pd
-from pandas import Index, Timedelta, TimedeltaIndex, notna, timedelta_range
+from pandas import (
+ Index,
+ Timedelta,
+ TimedeltaIndex,
+ notna,
+ timedelta_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/timedeltas/test_insert.py b/pandas/tests/indexes/timedeltas/test_insert.py
index d501f81fd9dce..067031c694810 100644
--- a/pandas/tests/indexes/timedeltas/test_insert.py
+++ b/pandas/tests/indexes/timedeltas/test_insert.py
@@ -6,7 +6,12 @@
from pandas._libs import lib
import pandas as pd
-from pandas import Index, Timedelta, TimedeltaIndex, timedelta_range
+from pandas import (
+ Index,
+ Timedelta,
+ TimedeltaIndex,
+ timedelta_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/timedeltas/test_join.py b/pandas/tests/indexes/timedeltas/test_join.py
index aaf4ef29e162b..2d8795b45f276 100644
--- a/pandas/tests/indexes/timedeltas/test_join.py
+++ b/pandas/tests/indexes/timedeltas/test_join.py
@@ -1,6 +1,10 @@
import numpy as np
-from pandas import Index, Timedelta, timedelta_range
+from pandas import (
+ Index,
+ Timedelta,
+ timedelta_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/timedeltas/test_ops.py b/pandas/tests/indexes/timedeltas/test_ops.py
index 83b8fcc1b15fe..4e6d69913900d 100644
--- a/pandas/tests/indexes/timedeltas/test_ops.py
+++ b/pandas/tests/indexes/timedeltas/test_ops.py
@@ -2,10 +2,18 @@
import pytest
import pandas as pd
-from pandas import Series, TimedeltaIndex, timedelta_range
+from pandas import (
+ Series,
+ TimedeltaIndex,
+ timedelta_range,
+)
import pandas._testing as tm
-from pandas.tseries.offsets import DateOffset, Day, Hour
+from pandas.tseries.offsets import (
+ DateOffset,
+ Day,
+ Hour,
+)
class TestTimedeltaIndexOps:
diff --git a/pandas/tests/indexes/timedeltas/test_partial_slicing.py b/pandas/tests/indexes/timedeltas/test_partial_slicing.py
index 6d53fe4563e41..cca211c1eb155 100644
--- a/pandas/tests/indexes/timedeltas/test_partial_slicing.py
+++ b/pandas/tests/indexes/timedeltas/test_partial_slicing.py
@@ -1,6 +1,9 @@
import numpy as np
-from pandas import Series, timedelta_range
+from pandas import (
+ Series,
+ timedelta_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/timedeltas/test_scalar_compat.py b/pandas/tests/indexes/timedeltas/test_scalar_compat.py
index 2f9e1a88a04a8..5e4b228ba2d32 100644
--- a/pandas/tests/indexes/timedeltas/test_scalar_compat.py
+++ b/pandas/tests/indexes/timedeltas/test_scalar_compat.py
@@ -7,7 +7,13 @@
from pandas._libs.tslibs.offsets import INVALID_FREQ_ERR_MSG
-from pandas import Index, Series, Timedelta, TimedeltaIndex, timedelta_range
+from pandas import (
+ Index,
+ Series,
+ Timedelta,
+ TimedeltaIndex,
+ timedelta_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/timedeltas/test_searchsorted.py b/pandas/tests/indexes/timedeltas/test_searchsorted.py
index e3b52058469f0..8a48da91ef31d 100644
--- a/pandas/tests/indexes/timedeltas/test_searchsorted.py
+++ b/pandas/tests/indexes/timedeltas/test_searchsorted.py
@@ -1,7 +1,12 @@
import numpy as np
import pytest
-from pandas import Series, TimedeltaIndex, Timestamp, array
+from pandas import (
+ Series,
+ TimedeltaIndex,
+ Timestamp,
+ array,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexes/timedeltas/test_setops.py b/pandas/tests/indexes/timedeltas/test_setops.py
index 2e4e4bfde9202..907a3463971ca 100644
--- a/pandas/tests/indexes/timedeltas/test_setops.py
+++ b/pandas/tests/indexes/timedeltas/test_setops.py
@@ -2,7 +2,11 @@
import pytest
import pandas as pd
-from pandas import Int64Index, TimedeltaIndex, timedelta_range
+from pandas import (
+ Int64Index,
+ TimedeltaIndex,
+ timedelta_range,
+)
import pandas._testing as tm
from pandas.tseries.offsets import Hour
diff --git a/pandas/tests/indexes/timedeltas/test_timedelta_range.py b/pandas/tests/indexes/timedeltas/test_timedelta_range.py
index dc3df4427f351..7277595f1d631 100644
--- a/pandas/tests/indexes/timedeltas/test_timedelta_range.py
+++ b/pandas/tests/indexes/timedeltas/test_timedelta_range.py
@@ -1,10 +1,17 @@
import numpy as np
import pytest
-from pandas import Timedelta, timedelta_range, to_timedelta
+from pandas import (
+ Timedelta,
+ timedelta_range,
+ to_timedelta,
+)
import pandas._testing as tm
-from pandas.tseries.offsets import Day, Second
+from pandas.tseries.offsets import (
+ Day,
+ Second,
+)
class TestTimedeltas:
diff --git a/pandas/tests/indexing/common.py b/pandas/tests/indexing/common.py
index fb6f4da2a482e..f70897147c867 100644
--- a/pandas/tests/indexing/common.py
+++ b/pandas/tests/indexing/common.py
@@ -3,7 +3,14 @@
import numpy as np
-from pandas import DataFrame, Float64Index, MultiIndex, Series, UInt64Index, date_range
+from pandas import (
+ DataFrame,
+ Float64Index,
+ MultiIndex,
+ Series,
+ UInt64Index,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexing/interval/test_interval.py b/pandas/tests/indexing/interval/test_interval.py
index 95f5115a8c28b..627306143788e 100644
--- a/pandas/tests/indexing/interval/test_interval.py
+++ b/pandas/tests/indexing/interval/test_interval.py
@@ -2,7 +2,11 @@
import pytest
import pandas as pd
-from pandas import DataFrame, IntervalIndex, Series
+from pandas import (
+ DataFrame,
+ IntervalIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexing/interval/test_interval_new.py b/pandas/tests/indexing/interval/test_interval_new.py
index 8935eb94c1c49..aea2cf42751db 100644
--- a/pandas/tests/indexing/interval/test_interval_new.py
+++ b/pandas/tests/indexing/interval/test_interval_new.py
@@ -3,7 +3,11 @@
import numpy as np
import pytest
-from pandas import Interval, IntervalIndex, Series
+from pandas import (
+ Interval,
+ IntervalIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexing/multiindex/test_chaining_and_caching.py b/pandas/tests/indexing/multiindex/test_chaining_and_caching.py
index 62c0171fe641f..f71b39d53d825 100644
--- a/pandas/tests/indexing/multiindex/test_chaining_and_caching.py
+++ b/pandas/tests/indexing/multiindex/test_chaining_and_caching.py
@@ -1,7 +1,11 @@
import numpy as np
import pytest
-from pandas import DataFrame, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
import pandas.core.common as com
diff --git a/pandas/tests/indexing/multiindex/test_getitem.py b/pandas/tests/indexing/multiindex/test_getitem.py
index d0ef95d2fa56c..954ef63bc2802 100644
--- a/pandas/tests/indexing/multiindex/test_getitem.py
+++ b/pandas/tests/indexing/multiindex/test_getitem.py
@@ -1,7 +1,12 @@
import numpy as np
import pytest
-from pandas import DataFrame, Index, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
from pandas.core.indexing import IndexingError
diff --git a/pandas/tests/indexing/multiindex/test_iloc.py b/pandas/tests/indexing/multiindex/test_iloc.py
index 9859c7235c380..1a7f93596773a 100644
--- a/pandas/tests/indexing/multiindex/test_iloc.py
+++ b/pandas/tests/indexing/multiindex/test_iloc.py
@@ -1,7 +1,11 @@
import numpy as np
import pytest
-from pandas import DataFrame, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexing/multiindex/test_indexing_slow.py b/pandas/tests/indexing/multiindex/test_indexing_slow.py
index eaa7029b118b1..cca31c1e81f84 100644
--- a/pandas/tests/indexing/multiindex/test_indexing_slow.py
+++ b/pandas/tests/indexing/multiindex/test_indexing_slow.py
@@ -4,7 +4,10 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
m = 50
diff --git a/pandas/tests/indexing/multiindex/test_insert.py b/pandas/tests/indexing/multiindex/test_insert.py
index 9f5ad90d36e03..b62f0be5a4f10 100644
--- a/pandas/tests/indexing/multiindex/test_insert.py
+++ b/pandas/tests/indexing/multiindex/test_insert.py
@@ -1,6 +1,10 @@
import numpy as np
-from pandas import DataFrame, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexing/multiindex/test_ix.py b/pandas/tests/indexing/multiindex/test_ix.py
index abf989324e4a5..b8d30337dbe16 100644
--- a/pandas/tests/indexing/multiindex/test_ix.py
+++ b/pandas/tests/indexing/multiindex/test_ix.py
@@ -3,7 +3,10 @@
from pandas.errors import PerformanceWarning
-from pandas import DataFrame, MultiIndex
+from pandas import (
+ DataFrame,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py
index 4c9912f1591c7..3e912eedb0232 100644
--- a/pandas/tests/indexing/multiindex/test_loc.py
+++ b/pandas/tests/indexing/multiindex/test_loc.py
@@ -2,7 +2,12 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
from pandas.core.indexing import IndexingError
diff --git a/pandas/tests/indexing/multiindex/test_multiindex.py b/pandas/tests/indexing/multiindex/test_multiindex.py
index 9a3039c28416c..e00b77003ebdc 100644
--- a/pandas/tests/indexing/multiindex/test_multiindex.py
+++ b/pandas/tests/indexing/multiindex/test_multiindex.py
@@ -4,7 +4,12 @@
from pandas.errors import PerformanceWarning
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexing/multiindex/test_setitem.py b/pandas/tests/indexing/multiindex/test_setitem.py
index e5d114d5a9b18..a360a53ca7672 100644
--- a/pandas/tests/indexing/multiindex/test_setitem.py
+++ b/pandas/tests/indexing/multiindex/test_setitem.py
@@ -2,7 +2,15 @@
import pytest
import pandas as pd
-from pandas import DataFrame, MultiIndex, Series, Timestamp, date_range, isna, notna
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+ Timestamp,
+ date_range,
+ isna,
+ notna,
+)
import pandas._testing as tm
import pandas.core.common as com
diff --git a/pandas/tests/indexing/multiindex/test_slice.py b/pandas/tests/indexing/multiindex/test_slice.py
index 6c7d5f06ac355..377a0f11b17d8 100644
--- a/pandas/tests/indexing/multiindex/test_slice.py
+++ b/pandas/tests/indexing/multiindex/test_slice.py
@@ -4,7 +4,13 @@
from pandas.errors import UnsortedIndexError
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series, Timestamp
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
from pandas.core.indexing import non_reducing_slice
from pandas.tests.indexing.common import _mklbl
diff --git a/pandas/tests/indexing/multiindex/test_sorted.py b/pandas/tests/indexing/multiindex/test_sorted.py
index b3e8c4a83b9fc..6ba083d65ac3f 100644
--- a/pandas/tests/indexing/multiindex/test_sorted.py
+++ b/pandas/tests/indexing/multiindex/test_sorted.py
@@ -1,7 +1,11 @@
import numpy as np
import pytest
-from pandas import DataFrame, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexing/test_at.py b/pandas/tests/indexing/test_at.py
index fbf33999386e6..f11f000bb79fd 100644
--- a/pandas/tests/indexing/test_at.py
+++ b/pandas/tests/indexing/test_at.py
@@ -1,9 +1,17 @@
-from datetime import datetime, timezone
+from datetime import (
+ datetime,
+ timezone,
+)
import numpy as np
import pytest
-from pandas import CategoricalDtype, DataFrame, Series, Timestamp
+from pandas import (
+ CategoricalDtype,
+ DataFrame,
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py
index 25d4692e4cd1d..4a66073d4f7a5 100644
--- a/pandas/tests/indexing/test_chaining_and_caching.py
+++ b/pandas/tests/indexing/test_chaining_and_caching.py
@@ -4,7 +4,13 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Series, Timestamp, date_range, option_context
+from pandas import (
+ DataFrame,
+ Series,
+ Timestamp,
+ date_range,
+ option_context,
+)
import pandas._testing as tm
import pandas.core.common as com
diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py
index f6f04e935ac52..2c962df30f1ff 100644
--- a/pandas/tests/indexing/test_coercion.py
+++ b/pandas/tests/indexing/test_coercion.py
@@ -1,11 +1,17 @@
from datetime import timedelta
import itertools
-from typing import Dict, List
+from typing import (
+ Dict,
+ List,
+)
import numpy as np
import pytest
-from pandas.compat import IS64, is_platform_windows
+from pandas.compat import (
+ IS64,
+ is_platform_windows,
+)
import pandas as pd
import pandas._testing as tm
diff --git a/pandas/tests/indexing/test_datetime.py b/pandas/tests/indexing/test_datetime.py
index 9f58f4af0ba55..7cad0f92b06a3 100644
--- a/pandas/tests/indexing/test_datetime.py
+++ b/pandas/tests/indexing/test_datetime.py
@@ -2,7 +2,13 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, Series, Timestamp, date_range
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexing/test_floats.py b/pandas/tests/indexing/test_floats.py
index 5eb3d9e9ec00e..d1f1db741509f 100644
--- a/pandas/tests/indexing/test_floats.py
+++ b/pandas/tests/indexing/test_floats.py
@@ -1,7 +1,14 @@
import numpy as np
import pytest
-from pandas import DataFrame, Float64Index, Index, Int64Index, RangeIndex, Series
+from pandas import (
+ DataFrame,
+ Float64Index,
+ Index,
+ Int64Index,
+ RangeIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexing/test_iat.py b/pandas/tests/indexing/test_iat.py
index 84bd1d63f6bbc..f1fe464ca0854 100644
--- a/pandas/tests/indexing/test_iat.py
+++ b/pandas/tests/indexing/test_iat.py
@@ -1,6 +1,10 @@
import numpy as np
-from pandas import DataFrame, Series, period_range
+from pandas import (
+ DataFrame,
+ Series,
+ period_range,
+)
def test_iat(float_frame):
diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py
index 1668123e782ff..881e47f4f5fe2 100644
--- a/pandas/tests/indexing/test_iloc.py
+++ b/pandas/tests/indexing/test_iloc.py
@@ -2,7 +2,10 @@
from datetime import datetime
import re
-from warnings import catch_warnings, simplefilter
+from warnings import (
+ catch_warnings,
+ simplefilter,
+)
import numpy as np
import pytest
diff --git a/pandas/tests/indexing/test_indexers.py b/pandas/tests/indexing/test_indexers.py
index 14b2b494d65fb..45dcaf95ffdd0 100644
--- a/pandas/tests/indexing/test_indexers.py
+++ b/pandas/tests/indexing/test_indexers.py
@@ -2,7 +2,11 @@
import numpy as np
import pytest
-from pandas.core.indexers import is_scalar_indexer, length_of_indexer, validate_indices
+from pandas.core.indexers import (
+ is_scalar_indexer,
+ length_of_indexer,
+ validate_indices,
+)
def test_length_of_indexer():
diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py
index 63313589d64f7..a4a7ef0860c15 100644
--- a/pandas/tests/indexing/test_indexing.py
+++ b/pandas/tests/indexing/test_indexing.py
@@ -7,12 +7,26 @@
import numpy as np
import pytest
-from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype
+from pandas.core.dtypes.common import (
+ is_float_dtype,
+ is_integer_dtype,
+)
import pandas as pd
-from pandas import DataFrame, Index, NaT, Series, date_range, offsets, timedelta_range
+from pandas import (
+ DataFrame,
+ Index,
+ NaT,
+ Series,
+ date_range,
+ offsets,
+ timedelta_range,
+)
import pandas._testing as tm
-from pandas.core.indexing import maybe_numeric_slice, non_reducing_slice
+from pandas.core.indexing import (
+ maybe_numeric_slice,
+ non_reducing_slice,
+)
from pandas.tests.indexing.common import _mklbl
from pandas.tests.indexing.test_floats import gen_obj
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index 1cd352e4e0899..55a979859a12a 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -1,5 +1,9 @@
""" test label based indexing with loc """
-from datetime import datetime, time, timedelta
+from datetime import (
+ datetime,
+ time,
+ timedelta,
+)
from io import StringIO
import re
diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py
index ad2d7250d9d6c..468e4cad742df 100644
--- a/pandas/tests/indexing/test_partial.py
+++ b/pandas/tests/indexing/test_partial.py
@@ -8,7 +8,15 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, Period, Series, Timestamp, date_range, period_range
+from pandas import (
+ DataFrame,
+ Index,
+ Period,
+ Series,
+ Timestamp,
+ date_range,
+ period_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/indexing/test_scalar.py b/pandas/tests/indexing/test_scalar.py
index ce48fd1e5c905..39611bce2b4fa 100644
--- a/pandas/tests/indexing/test_scalar.py
+++ b/pandas/tests/indexing/test_scalar.py
@@ -1,10 +1,19 @@
""" test scalar indexing, including at and iat """
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import numpy as np
import pytest
-from pandas import DataFrame, Series, Timedelta, Timestamp, date_range
+from pandas import (
+ DataFrame,
+ Series,
+ Timedelta,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
from pandas.tests.indexing.common import Base
diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py
index 3203b7fa1893d..a24c711df7b55 100644
--- a/pandas/tests/internals/test_internals.py
+++ b/pandas/tests/internals/test_internals.py
@@ -1,4 +1,7 @@
-from datetime import date, datetime
+from datetime import (
+ date,
+ datetime,
+)
import itertools
import re
@@ -23,8 +26,16 @@
)
import pandas._testing as tm
import pandas.core.algorithms as algos
-from pandas.core.arrays import DatetimeArray, SparseArray, TimedeltaArray
-from pandas.core.internals import BlockManager, SingleBlockManager, make_block
+from pandas.core.arrays import (
+ DatetimeArray,
+ SparseArray,
+ TimedeltaArray,
+)
+from pandas.core.internals import (
+ BlockManager,
+ SingleBlockManager,
+ make_block,
+)
@pytest.fixture
diff --git a/pandas/tests/internals/test_managers.py b/pandas/tests/internals/test_managers.py
index 333455875904a..4ca6e8b6598aa 100644
--- a/pandas/tests/internals/test_managers.py
+++ b/pandas/tests/internals/test_managers.py
@@ -5,7 +5,10 @@
import pandas as pd
import pandas._testing as tm
-from pandas.core.internals import ArrayManager, BlockManager
+from pandas.core.internals import (
+ ArrayManager,
+ BlockManager,
+)
def test_dataframe_creation():
diff --git a/pandas/tests/io/excel/__init__.py b/pandas/tests/io/excel/__init__.py
index b1038f0314f41..e1de03e1f306c 100644
--- a/pandas/tests/io/excel/__init__.py
+++ b/pandas/tests/io/excel/__init__.py
@@ -2,7 +2,10 @@
import pytest
-from pandas.compat._optional import get_version, import_optional_dependency
+from pandas.compat._optional import (
+ get_version,
+ import_optional_dependency,
+)
pytestmark = [
pytest.mark.filterwarnings(
diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py
index 8128e958141e2..9010f978d268d 100644
--- a/pandas/tests/io/excel/test_openpyxl.py
+++ b/pandas/tests/io/excel/test_openpyxl.py
@@ -7,7 +7,10 @@
from pandas import DataFrame
import pandas._testing as tm
-from pandas.io.excel import ExcelWriter, _OpenpyxlWriter
+from pandas.io.excel import (
+ ExcelWriter,
+ _OpenpyxlWriter,
+)
openpyxl = pytest.importorskip("openpyxl")
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
index a594718bd62d9..a9270c8dbf31f 100644
--- a/pandas/tests/io/excel/test_readers.py
+++ b/pandas/tests/io/excel/test_readers.py
@@ -1,4 +1,7 @@
-from datetime import datetime, time
+from datetime import (
+ datetime,
+ time,
+)
from functools import partial
import os
from urllib.error import URLError
@@ -10,7 +13,12 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
from pandas.tests.io.excel import xlrd_version
diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py
index 0aebcda83993d..c650f59a7da95 100644
--- a/pandas/tests/io/excel/test_writers.py
+++ b/pandas/tests/io/excel/test_writers.py
@@ -1,4 +1,8 @@
-from datetime import date, datetime, timedelta
+from datetime import (
+ date,
+ datetime,
+ timedelta,
+)
from functools import partial
from io import BytesIO
import os
@@ -9,7 +13,13 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, get_option, set_option
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ get_option,
+ set_option,
+)
import pandas._testing as tm
from pandas.io.excel import (
diff --git a/pandas/tests/io/excel/test_xlwt.py b/pandas/tests/io/excel/test_xlwt.py
index ac53a7d5aee69..7e1787d8c55d4 100644
--- a/pandas/tests/io/excel/test_xlwt.py
+++ b/pandas/tests/io/excel/test_xlwt.py
@@ -1,10 +1,17 @@
import numpy as np
import pytest
-from pandas import DataFrame, MultiIndex, options
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ options,
+)
import pandas._testing as tm
-from pandas.io.excel import ExcelWriter, _XlwtWriter
+from pandas.io.excel import (
+ ExcelWriter,
+ _XlwtWriter,
+)
xlwt = pytest.importorskip("xlwt")
diff --git a/pandas/tests/io/formats/test_css.py b/pandas/tests/io/formats/test_css.py
index 785904fafd31a..8465d116805c7 100644
--- a/pandas/tests/io/formats/test_css.py
+++ b/pandas/tests/io/formats/test_css.py
@@ -2,7 +2,10 @@
import pandas._testing as tm
-from pandas.io.formats.css import CSSResolver, CSSWarning
+from pandas.io.formats.css import (
+ CSSResolver,
+ CSSWarning,
+)
def assert_resolves(css, props, inherited=None):
diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py
index c0e4f01d3e5a5..41efb594fd8e4 100644
--- a/pandas/tests/io/formats/test_format.py
+++ b/pandas/tests/io/formats/test_format.py
@@ -18,7 +18,10 @@
import pytest
import pytz
-from pandas.compat import IS64, is_platform_windows
+from pandas.compat import (
+ IS64,
+ is_platform_windows,
+)
import pandas.util._test_decorators as td
import pandas as pd
@@ -2445,7 +2448,10 @@ def test_datetimeindex_highprecision(self, start_date):
def test_timedelta64(self):
- from datetime import datetime, timedelta
+ from datetime import (
+ datetime,
+ timedelta,
+ )
Series(np.array([1100, 20], dtype="timedelta64[ns]")).to_string()
diff --git a/pandas/tests/io/formats/test_info.py b/pandas/tests/io/formats/test_info.py
index 4990a14f302a6..5522631d222e1 100644
--- a/pandas/tests/io/formats/test_info.py
+++ b/pandas/tests/io/formats/test_info.py
@@ -7,7 +7,10 @@
import numpy as np
import pytest
-from pandas.compat import IS64, PYPY
+from pandas.compat import (
+ IS64,
+ PYPY,
+)
from pandas import (
CategoricalIndex,
diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py
index ef4de5961a696..8c634509bdc84 100644
--- a/pandas/tests/io/formats/test_to_csv.py
+++ b/pandas/tests/io/formats/test_to_csv.py
@@ -6,7 +6,10 @@
import pytest
import pandas as pd
-from pandas import DataFrame, compat
+from pandas import (
+ DataFrame,
+ compat,
+)
import pandas._testing as tm
diff --git a/pandas/tests/io/formats/test_to_html.py b/pandas/tests/io/formats/test_to_html.py
index a88dec84bd693..347e1fda3c79d 100644
--- a/pandas/tests/io/formats/test_to_html.py
+++ b/pandas/tests/io/formats/test_to_html.py
@@ -6,7 +6,12 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, option_context
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ option_context,
+)
import pandas._testing as tm
import pandas.io.formats.format as fmt
diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py
index ba6d7c010613b..53d6dc3cf0b17 100644
--- a/pandas/tests/io/formats/test_to_latex.py
+++ b/pandas/tests/io/formats/test_to_latex.py
@@ -5,7 +5,10 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
from pandas.io.formats.format import DataFrameFormatter
diff --git a/pandas/tests/io/formats/test_to_string.py b/pandas/tests/io/formats/test_to_string.py
index 5d7b4b417006a..551734f343dfa 100644
--- a/pandas/tests/io/formats/test_to_string.py
+++ b/pandas/tests/io/formats/test_to_string.py
@@ -5,7 +5,12 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series, option_context, to_datetime
+from pandas import (
+ DataFrame,
+ Series,
+ option_context,
+ to_datetime,
+)
def test_repr_embedded_ndarray():
diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py
index 94931f9635075..d967897e16676 100644
--- a/pandas/tests/io/json/test_json_table_schema.py
+++ b/pandas/tests/io/json/test_json_table_schema.py
@@ -8,7 +8,11 @@
import pandas.util._test_decorators as td
-from pandas.core.dtypes.dtypes import CategoricalDtype, DatetimeTZDtype, PeriodDtype
+from pandas.core.dtypes.dtypes import (
+ CategoricalDtype,
+ DatetimeTZDtype,
+ PeriodDtype,
+)
import pandas as pd
from pandas import DataFrame
diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py
index d7fc1257d8396..c01660ab5febe 100644
--- a/pandas/tests/io/json/test_normalize.py
+++ b/pandas/tests/io/json/test_normalize.py
@@ -5,7 +5,12 @@
import pandas.util._test_decorators as td
-from pandas import DataFrame, Index, Series, json_normalize
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ json_normalize,
+)
import pandas._testing as tm
from pandas.io.json._normalize import nested_to_record
diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py
index c3ada52eba5aa..bfce694637579 100644
--- a/pandas/tests/io/json/test_pandas.py
+++ b/pandas/tests/io/json/test_pandas.py
@@ -8,11 +8,22 @@
import numpy as np
import pytest
-from pandas.compat import IS64, PY38, is_platform_windows
+from pandas.compat import (
+ IS64,
+ PY38,
+ is_platform_windows,
+)
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import DataFrame, DatetimeIndex, Series, Timestamp, compat, read_json
+from pandas import (
+ DataFrame,
+ DatetimeIndex,
+ Series,
+ Timestamp,
+ compat,
+ read_json,
+)
import pandas._testing as tm
pytestmark = td.skip_array_manager_not_yet_implemented
diff --git a/pandas/tests/io/json/test_readlines.py b/pandas/tests/io/json/test_readlines.py
index 2484c12f42600..a8cf94421dbde 100644
--- a/pandas/tests/io/json/test_readlines.py
+++ b/pandas/tests/io/json/test_readlines.py
@@ -6,7 +6,10 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import DataFrame, read_json
+from pandas import (
+ DataFrame,
+ read_json,
+)
import pandas._testing as tm
from pandas.io.json._json import JsonReader
diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py
index dff506809ee4f..bfe8c7d6a4124 100644
--- a/pandas/tests/io/json/test_ujson.py
+++ b/pandas/tests/io/json/test_ujson.py
@@ -15,10 +15,21 @@
import pandas._libs.json as ujson
from pandas._libs.tslib import Timestamp
-from pandas.compat import IS64, is_platform_windows
+from pandas.compat import (
+ IS64,
+ is_platform_windows,
+)
import pandas.util._test_decorators as td
-from pandas import DataFrame, DatetimeIndex, Index, NaT, Series, Timedelta, date_range
+from pandas import (
+ DataFrame,
+ DatetimeIndex,
+ Index,
+ NaT,
+ Series,
+ Timedelta,
+ date_range,
+)
import pandas._testing as tm
pytestmark = td.skip_array_manager_not_yet_implemented
diff --git a/pandas/tests/io/parser/common/test_chunksize.py b/pandas/tests/io/parser/common/test_chunksize.py
index 8c1475025b442..3d9d780a1e878 100644
--- a/pandas/tests/io/parser/common/test_chunksize.py
+++ b/pandas/tests/io/parser/common/test_chunksize.py
@@ -9,7 +9,10 @@
from pandas.errors import DtypeWarning
-from pandas import DataFrame, concat
+from pandas import (
+ DataFrame,
+ concat,
+)
import pandas._testing as tm
diff --git a/pandas/tests/io/parser/common/test_common_basic.py b/pandas/tests/io/parser/common/test_common_basic.py
index 9fd6e48cf8689..6730d8cc46603 100644
--- a/pandas/tests/io/parser/common/test_common_basic.py
+++ b/pandas/tests/io/parser/common/test_common_basic.py
@@ -11,9 +11,17 @@
import pytest
from pandas._libs.tslib import Timestamp
-from pandas.errors import EmptyDataError, ParserError
+from pandas.errors import (
+ EmptyDataError,
+ ParserError,
+)
-from pandas import DataFrame, Index, Series, compat
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ compat,
+)
import pandas._testing as tm
from pandas.io.parsers import TextFileReader
diff --git a/pandas/tests/io/parser/common/test_file_buffer_url.py b/pandas/tests/io/parser/common/test_file_buffer_url.py
index 018f93f1eb06b..f09a1f7bcc492 100644
--- a/pandas/tests/io/parser/common/test_file_buffer_url.py
+++ b/pandas/tests/io/parser/common/test_file_buffer_url.py
@@ -2,14 +2,20 @@
Tests that work on both the Python and C engines but do not have a
specific classification into the other test modules.
"""
-from io import BytesIO, StringIO
+from io import (
+ BytesIO,
+ StringIO,
+)
import os
import platform
from urllib.error import URLError
import pytest
-from pandas.errors import EmptyDataError, ParserError
+from pandas.errors import (
+ EmptyDataError,
+ ParserError,
+)
import pandas.util._test_decorators as td
from pandas import DataFrame
diff --git a/pandas/tests/io/parser/common/test_index.py b/pandas/tests/io/parser/common/test_index.py
index a133e1be49946..6e7022cd87875 100644
--- a/pandas/tests/io/parser/common/test_index.py
+++ b/pandas/tests/io/parser/common/test_index.py
@@ -8,7 +8,11 @@
import pytest
-from pandas import DataFrame, Index, MultiIndex
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/io/parser/common/test_inf.py b/pandas/tests/io/parser/common/test_inf.py
index fca4aaaba6675..52fbdedd138fb 100644
--- a/pandas/tests/io/parser/common/test_inf.py
+++ b/pandas/tests/io/parser/common/test_inf.py
@@ -7,7 +7,10 @@
import numpy as np
import pytest
-from pandas import DataFrame, option_context
+from pandas import (
+ DataFrame,
+ option_context,
+)
import pandas._testing as tm
diff --git a/pandas/tests/io/parser/common/test_ints.py b/pandas/tests/io/parser/common/test_ints.py
index a8f5c43ea15c7..febeef695aafb 100644
--- a/pandas/tests/io/parser/common/test_ints.py
+++ b/pandas/tests/io/parser/common/test_ints.py
@@ -7,7 +7,10 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/io/parser/common/test_iterator.py b/pandas/tests/io/parser/common/test_iterator.py
index 3cc30b0ab4029..5ae1d80589df9 100644
--- a/pandas/tests/io/parser/common/test_iterator.py
+++ b/pandas/tests/io/parser/common/test_iterator.py
@@ -6,7 +6,11 @@
import pytest
-from pandas import DataFrame, Series, concat
+from pandas import (
+ DataFrame,
+ Series,
+ concat,
+)
import pandas._testing as tm
diff --git a/pandas/tests/io/parser/common/test_read_errors.py b/pandas/tests/io/parser/common/test_read_errors.py
index 57defb400b842..91b5e26efafa1 100644
--- a/pandas/tests/io/parser/common/test_read_errors.py
+++ b/pandas/tests/io/parser/common/test_read_errors.py
@@ -12,7 +12,10 @@
import numpy as np
import pytest
-from pandas.errors import EmptyDataError, ParserError
+from pandas.errors import (
+ EmptyDataError,
+ ParserError,
+)
import pandas.util._test_decorators as td
from pandas import DataFrame
diff --git a/pandas/tests/io/parser/conftest.py b/pandas/tests/io/parser/conftest.py
index 321678c36943a..1eb52ab78e1a0 100644
--- a/pandas/tests/io/parser/conftest.py
+++ b/pandas/tests/io/parser/conftest.py
@@ -1,9 +1,15 @@
import os
-from typing import List, Optional
+from typing import (
+ List,
+ Optional,
+)
import pytest
-from pandas import read_csv, read_table
+from pandas import (
+ read_csv,
+ read_table,
+)
class BaseParser:
diff --git a/pandas/tests/io/parser/dtypes/test_categorical.py b/pandas/tests/io/parser/dtypes/test_categorical.py
index 2f569424a82f5..f956403197cf5 100644
--- a/pandas/tests/io/parser/dtypes/test_categorical.py
+++ b/pandas/tests/io/parser/dtypes/test_categorical.py
@@ -11,7 +11,11 @@
from pandas.core.dtypes.dtypes import CategoricalDtype
import pandas as pd
-from pandas import Categorical, DataFrame, Timestamp
+from pandas import (
+ Categorical,
+ DataFrame,
+ Timestamp,
+)
import pandas._testing as tm
diff --git a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
index 5ffd909d316bf..e452159189d4a 100644
--- a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
+++ b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
@@ -10,7 +10,10 @@
from pandas.errors import ParserWarning
import pandas as pd
-from pandas import DataFrame, Timestamp
+from pandas import (
+ DataFrame,
+ Timestamp,
+)
import pandas._testing as tm
diff --git a/pandas/tests/io/parser/dtypes/test_empty.py b/pandas/tests/io/parser/dtypes/test_empty.py
index 57d729fb4b7fc..200d1b50bfced 100644
--- a/pandas/tests/io/parser/dtypes/test_empty.py
+++ b/pandas/tests/io/parser/dtypes/test_empty.py
@@ -7,7 +7,14 @@
import numpy as np
import pytest
-from pandas import Categorical, DataFrame, Index, MultiIndex, Series, concat
+from pandas import (
+ Categorical,
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ concat,
+)
import pandas._testing as tm
diff --git a/pandas/tests/io/parser/test_c_parser_only.py b/pandas/tests/io/parser/test_c_parser_only.py
index b23dfa6ef1548..f8aff3ad3696a 100644
--- a/pandas/tests/io/parser/test_c_parser_only.py
+++ b/pandas/tests/io/parser/test_c_parser_only.py
@@ -5,7 +5,11 @@
further arguments when parsing.
"""
-from io import BytesIO, StringIO, TextIOWrapper
+from io import (
+ BytesIO,
+ StringIO,
+ TextIOWrapper,
+)
import mmap
import os
import tarfile
@@ -17,7 +21,10 @@
from pandas.errors import ParserError
import pandas.util._test_decorators as td
-from pandas import DataFrame, concat
+from pandas import (
+ DataFrame,
+ concat,
+)
import pandas._testing as tm
diff --git a/pandas/tests/io/parser/test_converters.py b/pandas/tests/io/parser/test_converters.py
index 1d2fb7fddc9dd..ffa6c8259a59e 100644
--- a/pandas/tests/io/parser/test_converters.py
+++ b/pandas/tests/io/parser/test_converters.py
@@ -9,7 +9,10 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index
+from pandas import (
+ DataFrame,
+ Index,
+)
import pandas._testing as tm
diff --git a/pandas/tests/io/parser/test_encoding.py b/pandas/tests/io/parser/test_encoding.py
index 10386cf87b9c2..ba6bfe9d88a03 100644
--- a/pandas/tests/io/parser/test_encoding.py
+++ b/pandas/tests/io/parser/test_encoding.py
@@ -10,7 +10,10 @@
import numpy as np
import pytest
-from pandas import DataFrame, read_csv
+from pandas import (
+ DataFrame,
+ read_csv,
+)
import pandas._testing as tm
diff --git a/pandas/tests/io/parser/test_header.py b/pandas/tests/io/parser/test_header.py
index 0b8dc1900ebb4..f15fc16fbce38 100644
--- a/pandas/tests/io/parser/test_header.py
+++ b/pandas/tests/io/parser/test_header.py
@@ -11,7 +11,11 @@
from pandas.errors import ParserError
-from pandas import DataFrame, Index, MultiIndex
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/io/parser/test_index_col.py b/pandas/tests/io/parser/test_index_col.py
index a409751e261d6..2f876a28c56cd 100644
--- a/pandas/tests/io/parser/test_index_col.py
+++ b/pandas/tests/io/parser/test_index_col.py
@@ -8,7 +8,11 @@
import numpy as np
import pytest
-from pandas import DataFrame, Index, MultiIndex
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/io/parser/test_na_values.py b/pandas/tests/io/parser/test_na_values.py
index 4237a774261ca..fecba8bd81404 100644
--- a/pandas/tests/io/parser/test_na_values.py
+++ b/pandas/tests/io/parser/test_na_values.py
@@ -9,7 +9,11 @@
from pandas._libs.parsers import STR_NA_VALUES
-from pandas import DataFrame, Index, MultiIndex
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py
index 657793450df5b..d412f0f313ead 100644
--- a/pandas/tests/io/parser/test_network.py
+++ b/pandas/tests/io/parser/test_network.py
@@ -2,7 +2,10 @@
Tests parsers ability to read and parse non-local files
and hence require a network connection to be read.
"""
-from io import BytesIO, StringIO
+from io import (
+ BytesIO,
+ StringIO,
+)
import logging
import numpy as np
diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py
index a510286d5412e..9f94f3f8f8a8b 100644
--- a/pandas/tests/io/parser/test_parse_dates.py
+++ b/pandas/tests/io/parser/test_parse_dates.py
@@ -3,11 +3,18 @@
parsers defined in parsers.py
"""
-from datetime import date, datetime
+from datetime import (
+ date,
+ datetime,
+)
from io import StringIO
from dateutil.parser import parse as du_parse
-from hypothesis import given, settings, strategies as st
+from hypothesis import (
+ given,
+ settings,
+ strategies as st,
+)
import numpy as np
import pytest
import pytz
@@ -15,10 +22,19 @@
from pandas._libs.tslib import Timestamp
from pandas._libs.tslibs import parsing
from pandas._libs.tslibs.parsing import parse_datetime_string
-from pandas.compat import is_platform_windows, np_array_datetime64_compat
+from pandas.compat import (
+ is_platform_windows,
+ np_array_datetime64_compat,
+)
import pandas as pd
-from pandas import DataFrame, DatetimeIndex, Index, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ DatetimeIndex,
+ Index,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
from pandas.core.indexes.datetimes import date_range
diff --git a/pandas/tests/io/parser/test_python_parser_only.py b/pandas/tests/io/parser/test_python_parser_only.py
index d55a6361fc8d2..cf6866946ab76 100644
--- a/pandas/tests/io/parser/test_python_parser_only.py
+++ b/pandas/tests/io/parser/test_python_parser_only.py
@@ -6,13 +6,20 @@
"""
import csv
-from io import BytesIO, StringIO
+from io import (
+ BytesIO,
+ StringIO,
+)
import pytest
from pandas.errors import ParserError
-from pandas import DataFrame, Index, MultiIndex
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/io/parser/test_read_fwf.py b/pandas/tests/io/parser/test_read_fwf.py
index 5322c19a3ae50..5586b4915b6ea 100644
--- a/pandas/tests/io/parser/test_read_fwf.py
+++ b/pandas/tests/io/parser/test_read_fwf.py
@@ -5,7 +5,10 @@
"""
from datetime import datetime
-from io import BytesIO, StringIO
+from io import (
+ BytesIO,
+ StringIO,
+)
from pathlib import Path
import numpy as np
@@ -14,10 +17,16 @@
from pandas.errors import EmptyDataError
import pandas as pd
-from pandas import DataFrame, DatetimeIndex
+from pandas import (
+ DataFrame,
+ DatetimeIndex,
+)
import pandas._testing as tm
-from pandas.io.parsers import read_csv, read_fwf
+from pandas.io.parsers import (
+ read_csv,
+ read_fwf,
+)
def test_basic():
diff --git a/pandas/tests/io/parser/test_skiprows.py b/pandas/tests/io/parser/test_skiprows.py
index 35b155705ccee..0735f60fabbf6 100644
--- a/pandas/tests/io/parser/test_skiprows.py
+++ b/pandas/tests/io/parser/test_skiprows.py
@@ -11,7 +11,10 @@
from pandas.errors import EmptyDataError
-from pandas import DataFrame, Index
+from pandas import (
+ DataFrame,
+ Index,
+)
import pandas._testing as tm
diff --git a/pandas/tests/io/parser/test_textreader.py b/pandas/tests/io/parser/test_textreader.py
index 1af69785c7584..104cf56419bfd 100644
--- a/pandas/tests/io/parser/test_textreader.py
+++ b/pandas/tests/io/parser/test_textreader.py
@@ -2,7 +2,10 @@
Tests the TextReader class in parsers.pyx, which
is integral to the C engine in parsers.py
"""
-from io import BytesIO, StringIO
+from io import (
+ BytesIO,
+ StringIO,
+)
import os
import numpy as np
@@ -14,7 +17,10 @@
from pandas import DataFrame
import pandas._testing as tm
-from pandas.io.parsers import TextFileReader, read_csv
+from pandas.io.parsers import (
+ TextFileReader,
+ read_csv,
+)
class TestTextReader:
diff --git a/pandas/tests/io/parser/usecols/test_parse_dates.py b/pandas/tests/io/parser/usecols/test_parse_dates.py
index c6b700c0adfff..7f813b8733061 100644
--- a/pandas/tests/io/parser/usecols/test_parse_dates.py
+++ b/pandas/tests/io/parser/usecols/test_parse_dates.py
@@ -8,7 +8,10 @@
from pandas._libs.tslib import Timestamp
-from pandas import DataFrame, Index
+from pandas import (
+ DataFrame,
+ Index,
+)
import pandas._testing as tm
_msg_validate_usecols_arg = (
diff --git a/pandas/tests/io/parser/usecols/test_usecols_basic.py b/pandas/tests/io/parser/usecols/test_usecols_basic.py
index 7d81a88e09012..27bad29550d82 100644
--- a/pandas/tests/io/parser/usecols/test_usecols_basic.py
+++ b/pandas/tests/io/parser/usecols/test_usecols_basic.py
@@ -7,7 +7,10 @@
import numpy as np
import pytest
-from pandas import DataFrame, Index
+from pandas import (
+ DataFrame,
+ Index,
+)
import pandas._testing as tm
_msg_validate_usecols_arg = (
diff --git a/pandas/tests/io/pytables/test_categorical.py b/pandas/tests/io/pytables/test_categorical.py
index b873811de616c..858e38e40f017 100644
--- a/pandas/tests/io/pytables/test_categorical.py
+++ b/pandas/tests/io/pytables/test_categorical.py
@@ -1,7 +1,14 @@
import numpy as np
import pytest
-from pandas import Categorical, DataFrame, Series, _testing as tm, concat, read_hdf
+from pandas import (
+ Categorical,
+ DataFrame,
+ Series,
+ _testing as tm,
+ concat,
+ read_hdf,
+)
from pandas.tests.io.pytables.common import (
_maybe_remove,
ensure_clean_path,
diff --git a/pandas/tests/io/pytables/test_complex.py b/pandas/tests/io/pytables/test_complex.py
index 72e8b4aea5ede..8e1dee5873512 100644
--- a/pandas/tests/io/pytables/test_complex.py
+++ b/pandas/tests/io/pytables/test_complex.py
@@ -6,9 +6,15 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
-from pandas.tests.io.pytables.common import ensure_clean_path, ensure_clean_store
+from pandas.tests.io.pytables.common import (
+ ensure_clean_path,
+ ensure_clean_store,
+)
from pandas.io.pytables import read_hdf
diff --git a/pandas/tests/io/pytables/test_errors.py b/pandas/tests/io/pytables/test_errors.py
index 24bd573341dc4..11ee5e3564634 100644
--- a/pandas/tests/io/pytables/test_errors.py
+++ b/pandas/tests/io/pytables/test_errors.py
@@ -16,9 +16,15 @@
date_range,
read_hdf,
)
-from pandas.tests.io.pytables.common import ensure_clean_path, ensure_clean_store
+from pandas.tests.io.pytables.common import (
+ ensure_clean_path,
+ ensure_clean_store,
+)
-from pandas.io.pytables import Term, _maybe_adjust_name
+from pandas.io.pytables import (
+ Term,
+ _maybe_adjust_name,
+)
pytestmark = pytest.mark.single
diff --git a/pandas/tests/io/pytables/test_file_handling.py b/pandas/tests/io/pytables/test_file_handling.py
index e0e995e03064f..6340311b234f1 100644
--- a/pandas/tests/io/pytables/test_file_handling.py
+++ b/pandas/tests/io/pytables/test_file_handling.py
@@ -6,7 +6,13 @@
from pandas.compat import is_platform_little_endian
import pandas as pd
-from pandas import DataFrame, HDFStore, Series, _testing as tm, read_hdf
+from pandas import (
+ DataFrame,
+ HDFStore,
+ Series,
+ _testing as tm,
+ read_hdf,
+)
from pandas.tests.io.pytables.common import (
_maybe_remove,
ensure_clean_path,
@@ -15,7 +21,11 @@
)
from pandas.io import pytables as pytables
-from pandas.io.pytables import ClosedFileError, PossibleDataLossError, Term
+from pandas.io.pytables import (
+ ClosedFileError,
+ PossibleDataLossError,
+ Term,
+)
pytestmark = pytest.mark.single
diff --git a/pandas/tests/io/pytables/test_keys.py b/pandas/tests/io/pytables/test_keys.py
index 4f939adeb4138..02b79bd0fdbc1 100644
--- a/pandas/tests/io/pytables/test_keys.py
+++ b/pandas/tests/io/pytables/test_keys.py
@@ -1,6 +1,10 @@
import pytest
-from pandas import DataFrame, HDFStore, _testing as tm
+from pandas import (
+ DataFrame,
+ HDFStore,
+ _testing as tm,
+)
from pandas.tests.io.pytables.common import (
ensure_clean_path,
ensure_clean_store,
diff --git a/pandas/tests/io/pytables/test_put.py b/pandas/tests/io/pytables/test_put.py
index 5f6a39d46df97..4f8c7c84a9fcc 100644
--- a/pandas/tests/io/pytables/test_put.py
+++ b/pandas/tests/io/pytables/test_put.py
@@ -1,6 +1,9 @@
import datetime
import re
-from warnings import catch_warnings, simplefilter
+from warnings import (
+ catch_warnings,
+ simplefilter,
+)
import numpy as np
import pytest
diff --git a/pandas/tests/io/pytables/test_read.py b/pandas/tests/io/pytables/test_read.py
index 5ca8960ae5604..f8d302a0190f8 100644
--- a/pandas/tests/io/pytables/test_read.py
+++ b/pandas/tests/io/pytables/test_read.py
@@ -8,7 +8,14 @@
from pandas.compat import is_platform_windows
import pandas as pd
-from pandas import DataFrame, HDFStore, Index, Series, _testing as tm, read_hdf
+from pandas import (
+ DataFrame,
+ HDFStore,
+ Index,
+ Series,
+ _testing as tm,
+ read_hdf,
+)
from pandas.tests.io.pytables.common import (
_maybe_remove,
ensure_clean_path,
diff --git a/pandas/tests/io/pytables/test_retain_attributes.py b/pandas/tests/io/pytables/test_retain_attributes.py
index d301835632431..16772d03c6d26 100644
--- a/pandas/tests/io/pytables/test_retain_attributes.py
+++ b/pandas/tests/io/pytables/test_retain_attributes.py
@@ -4,7 +4,13 @@
from pandas._libs.tslibs import Timestamp
-from pandas import DataFrame, Series, _testing as tm, date_range, read_hdf
+from pandas import (
+ DataFrame,
+ Series,
+ _testing as tm,
+ date_range,
+ read_hdf,
+)
from pandas.tests.io.pytables.common import (
_maybe_remove,
ensure_clean_path,
diff --git a/pandas/tests/io/pytables/test_round_trip.py b/pandas/tests/io/pytables/test_round_trip.py
index 403c3766fe6ed..03d3d838a936c 100644
--- a/pandas/tests/io/pytables/test_round_trip.py
+++ b/pandas/tests/io/pytables/test_round_trip.py
@@ -1,6 +1,9 @@
import datetime
import re
-from warnings import catch_warnings, simplefilter
+from warnings import (
+ catch_warnings,
+ simplefilter,
+)
import numpy as np
import pytest
diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py
index cb281e7cafd1f..ef75c86190a25 100644
--- a/pandas/tests/io/pytables/test_store.py
+++ b/pandas/tests/io/pytables/test_store.py
@@ -2,7 +2,10 @@
import hashlib
import os
import time
-from warnings import catch_warnings, simplefilter
+from warnings import (
+ catch_warnings,
+ simplefilter,
+)
import numpy as np
import pytest
@@ -38,7 +41,10 @@
"ignore:object name:tables.exceptions.NaturalNameWarning"
)
-from pandas.io.pytables import HDFStore, read_hdf
+from pandas.io.pytables import (
+ HDFStore,
+ read_hdf,
+)
pytestmark = pytest.mark.single
diff --git a/pandas/tests/io/pytables/test_subclass.py b/pandas/tests/io/pytables/test_subclass.py
index 196f729cd6eb2..75b04f332e054 100644
--- a/pandas/tests/io/pytables/test_subclass.py
+++ b/pandas/tests/io/pytables/test_subclass.py
@@ -1,10 +1,16 @@
import numpy as np
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
from pandas.tests.io.pytables.common import ensure_clean_path
-from pandas.io.pytables import HDFStore, read_hdf
+from pandas.io.pytables import (
+ HDFStore,
+ read_hdf,
+)
class TestHDFStoreSubclass:
diff --git a/pandas/tests/io/pytables/test_time_series.py b/pandas/tests/io/pytables/test_time_series.py
index d98ae7c599c52..5e42dbde4b9f1 100644
--- a/pandas/tests/io/pytables/test_time_series.py
+++ b/pandas/tests/io/pytables/test_time_series.py
@@ -3,7 +3,11 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series, _testing as tm
+from pandas import (
+ DataFrame,
+ Series,
+ _testing as tm,
+)
from pandas.tests.io.pytables.common import ensure_clean_store
pytestmark = pytest.mark.single
diff --git a/pandas/tests/io/pytables/test_timezones.py b/pandas/tests/io/pytables/test_timezones.py
index a106a579d7e52..489352380b186 100644
--- a/pandas/tests/io/pytables/test_timezones.py
+++ b/pandas/tests/io/pytables/test_timezones.py
@@ -6,7 +6,13 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import DataFrame, DatetimeIndex, Series, Timestamp, date_range
+from pandas import (
+ DataFrame,
+ DatetimeIndex,
+ Series,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
from pandas.tests.io.pytables.common import (
_maybe_remove,
diff --git a/pandas/tests/io/sas/test_sas7bdat.py b/pandas/tests/io/sas/test_sas7bdat.py
index b23959a7d87a2..5d847f7b6f2bd 100644
--- a/pandas/tests/io/sas/test_sas7bdat.py
+++ b/pandas/tests/io/sas/test_sas7bdat.py
@@ -7,7 +7,10 @@
import numpy as np
import pytest
-from pandas.errors import EmptyDataError, PerformanceWarning
+from pandas.errors import (
+ EmptyDataError,
+ PerformanceWarning,
+)
import pandas.util._test_decorators as td
import pandas as pd
diff --git a/pandas/tests/io/test_clipboard.py b/pandas/tests/io/test_clipboard.py
index 440c370857eef..e60807db55f97 100644
--- a/pandas/tests/io/test_clipboard.py
+++ b/pandas/tests/io/test_clipboard.py
@@ -4,10 +4,17 @@
import pytest
import pandas as pd
-from pandas import DataFrame, get_option, read_clipboard
+from pandas import (
+ DataFrame,
+ get_option,
+ read_clipboard,
+)
import pandas._testing as tm
-from pandas.io.clipboard import clipboard_get, clipboard_set
+from pandas.io.clipboard import (
+ clipboard_get,
+ clipboard_set,
+)
def build_kwargs(sep, excel):
diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py
index 69a1427cec34f..db742fb69dd10 100644
--- a/pandas/tests/io/test_common.py
+++ b/pandas/tests/io/test_common.py
@@ -2,7 +2,10 @@
Tests for the pandas.io.common functionalities
"""
import codecs
-from io import BytesIO, StringIO
+from io import (
+ BytesIO,
+ StringIO,
+)
import mmap
import os
from pathlib import Path
diff --git a/pandas/tests/io/test_gcs.py b/pandas/tests/io/test_gcs.py
index ed6f3b7d21d43..bb2a042f9168b 100644
--- a/pandas/tests/io/test_gcs.py
+++ b/pandas/tests/io/test_gcs.py
@@ -4,7 +4,14 @@
import numpy as np
import pytest
-from pandas import DataFrame, date_range, read_csv, read_excel, read_json, read_parquet
+from pandas import (
+ DataFrame,
+ date_range,
+ read_csv,
+ read_excel,
+ read_json,
+ read_parquet,
+)
import pandas._testing as tm
from pandas.util import _test_decorators as td
@@ -12,7 +19,10 @@
@pytest.fixture
def gcs_buffer(monkeypatch):
"""Emulate GCS using a binary buffer."""
- from fsspec import AbstractFileSystem, registry
+ from fsspec import (
+ AbstractFileSystem,
+ registry,
+ )
registry.target.clear() # remove state
@@ -131,7 +141,10 @@ def test_to_csv_compression_encoding_gcs(gcs_buffer, compression_only, encoding)
@td.skip_if_no("gcsfs")
def test_to_parquet_gcs_new_file(monkeypatch, tmpdir):
"""Regression test for writing to a not-yet-existent GCS Parquet file."""
- from fsspec import AbstractFileSystem, registry
+ from fsspec import (
+ AbstractFileSystem,
+ registry,
+ )
registry.target.clear() # remove state
df1 = DataFrame(
diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py
index 7b762e4891c14..9f1df201ee0e6 100644
--- a/pandas/tests/io/test_html.py
+++ b/pandas/tests/io/test_html.py
@@ -1,6 +1,9 @@
from functools import partial
from importlib import reload
-from io import BytesIO, StringIO
+from io import (
+ BytesIO,
+ StringIO,
+)
import os
from pathlib import Path
import re
diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index c72363b088a5c..d5567f1208c8c 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -9,7 +9,10 @@
import numpy as np
import pytest
-from pandas.compat import PY38, is_platform_windows
+from pandas.compat import (
+ PY38,
+ is_platform_windows,
+)
import pandas.util._test_decorators as td
import pandas as pd
diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py
index 135f243eb867e..63dfbd59acd94 100644
--- a/pandas/tests/io/test_pickle.py
+++ b/pandas/tests/io/test_pickle.py
@@ -21,20 +21,35 @@
from pathlib import Path
import pickle
import shutil
-from warnings import catch_warnings, simplefilter
+from warnings import (
+ catch_warnings,
+ simplefilter,
+)
import zipfile
import numpy as np
import pytest
-from pandas.compat import PY38, get_lzma_file, import_lzma, is_platform_little_endian
+from pandas.compat import (
+ PY38,
+ get_lzma_file,
+ import_lzma,
+ is_platform_little_endian,
+)
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import Index, Series, period_range
+from pandas import (
+ Index,
+ Series,
+ period_range,
+)
import pandas._testing as tm
-from pandas.tseries.offsets import Day, MonthEnd
+from pandas.tseries.offsets import (
+ Day,
+ MonthEnd,
+)
lzma = import_lzma()
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index b70bc3c598702..0be26ab285079 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -18,7 +18,11 @@
"""
import csv
-from datetime import date, datetime, time
+from datetime import (
+ date,
+ datetime,
+ time,
+)
from io import StringIO
import sqlite3
import warnings
@@ -26,7 +30,10 @@
import numpy as np
import pytest
-from pandas.core.dtypes.common import is_datetime64_dtype, is_datetime64tz_dtype
+from pandas.core.dtypes.common import (
+ is_datetime64_dtype,
+ is_datetime64tz_dtype,
+)
import pandas as pd
from pandas import (
@@ -44,7 +51,10 @@
import pandas._testing as tm
import pandas.io.sql as sql
-from pandas.io.sql import read_sql_query, read_sql_table
+from pandas.io.sql import (
+ read_sql_query,
+ read_sql_table,
+)
try:
import sqlalchemy
diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py
index 058dc7659fc95..de1f3cf1e6338 100644
--- a/pandas/tests/io/test_stata.py
+++ b/pandas/tests/io/test_stata.py
@@ -18,7 +18,10 @@
import pandas as pd
import pandas._testing as tm
-from pandas.core.frame import DataFrame, Series
+from pandas.core.frame import (
+ DataFrame,
+ Series,
+)
from pandas.io.parsers import read_csv
from pandas.io.stata import (
diff --git a/pandas/tests/libs/test_join.py b/pandas/tests/libs/test_join.py
index f3f09d7a42204..0bdb7b0e71e2d 100644
--- a/pandas/tests/libs/test_join.py
+++ b/pandas/tests/libs/test_join.py
@@ -2,7 +2,10 @@
import pytest
from pandas._libs import join as libjoin
-from pandas._libs.join import inner_join, left_outer_join
+from pandas._libs.join import (
+ inner_join,
+ left_outer_join,
+)
import pandas._testing as tm
diff --git a/pandas/tests/libs/test_lib.py b/pandas/tests/libs/test_lib.py
index da3e18c8d9634..60c42878497c2 100644
--- a/pandas/tests/libs/test_lib.py
+++ b/pandas/tests/libs/test_lib.py
@@ -1,7 +1,11 @@
import numpy as np
import pytest
-from pandas._libs import Timestamp, lib, writers as libwriters
+from pandas._libs import (
+ Timestamp,
+ lib,
+ writers as libwriters,
+)
from pandas import Index
import pandas._testing as tm
diff --git a/pandas/tests/plotting/common.py b/pandas/tests/plotting/common.py
index 29c02916ec6e9..fa0a09a84a8f0 100644
--- a/pandas/tests/plotting/common.py
+++ b/pandas/tests/plotting/common.py
@@ -8,7 +8,11 @@
from __future__ import annotations
import os
-from typing import TYPE_CHECKING, Sequence, Union
+from typing import (
+ TYPE_CHECKING,
+ Sequence,
+ Union,
+)
import warnings
import numpy as np
@@ -19,7 +23,11 @@
from pandas.core.dtypes.api import is_list_like
import pandas as pd
-from pandas import DataFrame, Series, to_datetime
+from pandas import (
+ DataFrame,
+ Series,
+ to_datetime,
+)
import pandas._testing as tm
if TYPE_CHECKING:
@@ -228,7 +236,11 @@ def _check_colors(
Series used for color grouping key
used for andrew_curves, parallel_coordinates, radviz test
"""
- from matplotlib.collections import Collection, LineCollection, PolyCollection
+ from matplotlib.collections import (
+ Collection,
+ LineCollection,
+ PolyCollection,
+ )
from matplotlib.lines import Line2D
conv = self.colorconverter
diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py
index 41df9fb2e5af0..920350477bb20 100644
--- a/pandas/tests/plotting/frame/test_frame.py
+++ b/pandas/tests/plotting/frame/test_frame.py
@@ -1,5 +1,8 @@
""" Test cases for DataFrame.plot """
-from datetime import date, datetime
+from datetime import (
+ date,
+ datetime,
+)
import itertools
import re
import string
@@ -13,9 +16,19 @@
from pandas.core.dtypes.api import is_list_like
import pandas as pd
-from pandas import DataFrame, MultiIndex, PeriodIndex, Series, bdate_range, date_range
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ PeriodIndex,
+ Series,
+ bdate_range,
+ date_range,
+)
import pandas._testing as tm
-from pandas.tests.plotting.common import TestPlotBase, _check_plot_works
+from pandas.tests.plotting.common import (
+ TestPlotBase,
+ _check_plot_works,
+)
from pandas.io.formats.printing import pprint_thing
import pandas.plotting as plotting
diff --git a/pandas/tests/plotting/frame/test_frame_color.py b/pandas/tests/plotting/frame/test_frame_color.py
index 7eb12d3193b09..6844124d15f9d 100644
--- a/pandas/tests/plotting/frame/test_frame_color.py
+++ b/pandas/tests/plotting/frame/test_frame_color.py
@@ -10,7 +10,10 @@
import pandas as pd
from pandas import DataFrame
import pandas._testing as tm
-from pandas.tests.plotting.common import TestPlotBase, _check_plot_works
+from pandas.tests.plotting.common import (
+ TestPlotBase,
+ _check_plot_works,
+)
pytestmark = pytest.mark.slow
diff --git a/pandas/tests/plotting/frame/test_frame_subplots.py b/pandas/tests/plotting/frame/test_frame_subplots.py
index 049f357a4647f..0e25fb5f4c01f 100644
--- a/pandas/tests/plotting/frame/test_frame_subplots.py
+++ b/pandas/tests/plotting/frame/test_frame_subplots.py
@@ -9,7 +9,11 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import DataFrame, Series, date_range
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+)
import pandas._testing as tm
from pandas.tests.plotting.common import TestPlotBase
diff --git a/pandas/tests/plotting/test_boxplot_method.py b/pandas/tests/plotting/test_boxplot_method.py
index b7dab714961db..448679d562a4a 100644
--- a/pandas/tests/plotting/test_boxplot_method.py
+++ b/pandas/tests/plotting/test_boxplot_method.py
@@ -8,9 +8,18 @@
import pandas.util._test_decorators as td
-from pandas import DataFrame, MultiIndex, Series, date_range, timedelta_range
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+ date_range,
+ timedelta_range,
+)
import pandas._testing as tm
-from pandas.tests.plotting.common import TestPlotBase, _check_plot_works
+from pandas.tests.plotting.common import (
+ TestPlotBase,
+ _check_plot_works,
+)
import pandas.plotting as plotting
diff --git a/pandas/tests/plotting/test_converter.py b/pandas/tests/plotting/test_converter.py
index 4f332bfbac397..75f2dcacf244d 100644
--- a/pandas/tests/plotting/test_converter.py
+++ b/pandas/tests/plotting/test_converter.py
@@ -1,4 +1,7 @@
-from datetime import date, datetime
+from datetime import (
+ date,
+ datetime,
+)
import subprocess
import sys
@@ -7,17 +10,31 @@
import pandas._config.config as cf
-from pandas.compat import is_platform_windows, np_datetime64_compat
+from pandas.compat import (
+ is_platform_windows,
+ np_datetime64_compat,
+)
import pandas.util._test_decorators as td
-from pandas import Index, Period, Series, Timestamp, date_range
+from pandas import (
+ Index,
+ Period,
+ Series,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
from pandas.plotting import (
deregister_matplotlib_converters,
register_matplotlib_converters,
)
-from pandas.tseries.offsets import Day, Micro, Milli, Second
+from pandas.tseries.offsets import (
+ Day,
+ Micro,
+ Milli,
+ Second,
+)
try:
from pandas.plotting._matplotlib import converter
diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py
index e3fd404ec1906..6e71b56e8182b 100644
--- a/pandas/tests/plotting/test_datetimelike.py
+++ b/pandas/tests/plotting/test_datetimelike.py
@@ -1,18 +1,41 @@
""" Test cases for time series specific (freq conversion, etc) """
-from datetime import date, datetime, time, timedelta
+from datetime import (
+ date,
+ datetime,
+ time,
+ timedelta,
+)
import pickle
import sys
import numpy as np
import pytest
-from pandas._libs.tslibs import BaseOffset, to_offset
+from pandas._libs.tslibs import (
+ BaseOffset,
+ to_offset,
+)
import pandas.util._test_decorators as td
-from pandas import DataFrame, Index, NaT, Series, isna, to_datetime
+from pandas import (
+ DataFrame,
+ Index,
+ NaT,
+ Series,
+ isna,
+ to_datetime,
+)
import pandas._testing as tm
-from pandas.core.indexes.datetimes import DatetimeIndex, bdate_range, date_range
-from pandas.core.indexes.period import Period, PeriodIndex, period_range
+from pandas.core.indexes.datetimes import (
+ DatetimeIndex,
+ bdate_range,
+ date_range,
+)
+from pandas.core.indexes.period import (
+ Period,
+ PeriodIndex,
+ period_range,
+)
from pandas.core.indexes.timedeltas import timedelta_range
from pandas.tests.plotting.common import TestPlotBase
diff --git a/pandas/tests/plotting/test_groupby.py b/pandas/tests/plotting/test_groupby.py
index f73ceee577a18..76320767a6b01 100644
--- a/pandas/tests/plotting/test_groupby.py
+++ b/pandas/tests/plotting/test_groupby.py
@@ -7,7 +7,11 @@
from pandas.compat import is_platform_windows
import pandas.util._test_decorators as td
-from pandas import DataFrame, Index, Series
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+)
import pandas._testing as tm
from pandas.tests.plotting.common import TestPlotBase
diff --git a/pandas/tests/plotting/test_hist_method.py b/pandas/tests/plotting/test_hist_method.py
index d4901ba5576c9..a6e3ba71e94ab 100644
--- a/pandas/tests/plotting/test_hist_method.py
+++ b/pandas/tests/plotting/test_hist_method.py
@@ -6,9 +6,17 @@
import pandas.util._test_decorators as td
-from pandas import DataFrame, Index, Series, to_datetime
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ to_datetime,
+)
import pandas._testing as tm
-from pandas.tests.plotting.common import TestPlotBase, _check_plot_works
+from pandas.tests.plotting.common import (
+ TestPlotBase,
+ _check_plot_works,
+)
pytestmark = pytest.mark.slow
@@ -103,7 +111,10 @@ def test_hist_layout_with_by(self):
self._check_axes_shape(axes, axes_num=4, layout=(4, 2), figsize=(12, 7))
def test_hist_no_overlap(self):
- from matplotlib.pyplot import gcf, subplot
+ from matplotlib.pyplot import (
+ gcf,
+ subplot,
+ )
x = Series(np.random.randn(2))
y = Series(np.random.randn(2))
diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py
index 803c56b3b8eb3..7f0d1802580b9 100644
--- a/pandas/tests/plotting/test_misc.py
+++ b/pandas/tests/plotting/test_misc.py
@@ -5,9 +5,15 @@
import pandas.util._test_decorators as td
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
-from pandas.tests.plotting.common import TestPlotBase, _check_plot_works
+from pandas.tests.plotting.common import (
+ TestPlotBase,
+ _check_plot_works,
+)
import pandas.plotting as plotting
diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py
index b4848f80e9a2c..59b0cc99d94fb 100644
--- a/pandas/tests/plotting/test_series.py
+++ b/pandas/tests/plotting/test_series.py
@@ -10,9 +10,16 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import DataFrame, Series, date_range
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+)
import pandas._testing as tm
-from pandas.tests.plotting.common import TestPlotBase, _check_plot_works
+from pandas.tests.plotting.common import (
+ TestPlotBase,
+ _check_plot_works,
+)
import pandas.plotting as plotting
diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py
index cb64b2423696f..9de0422917e7b 100644
--- a/pandas/tests/reductions/test_reductions.py
+++ b/pandas/tests/reductions/test_reductions.py
@@ -1,4 +1,7 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import numpy as np
import pytest
diff --git a/pandas/tests/reductions/test_stat_reductions.py b/pandas/tests/reductions/test_stat_reductions.py
index ab13893901104..88f69d00447b1 100644
--- a/pandas/tests/reductions/test_stat_reductions.py
+++ b/pandas/tests/reductions/test_stat_reductions.py
@@ -9,9 +9,16 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
-from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray
+from pandas.core.arrays import (
+ DatetimeArray,
+ PeriodArray,
+ TimedeltaArray,
+)
class TestDatetimeLikeStatReductions:
diff --git a/pandas/tests/resample/conftest.py b/pandas/tests/resample/conftest.py
index cb62263b885aa..420c3028382fc 100644
--- a/pandas/tests/resample/conftest.py
+++ b/pandas/tests/resample/conftest.py
@@ -3,7 +3,10 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
from pandas.core.indexes.datetimes import date_range
from pandas.core.indexes.period import period_range
diff --git a/pandas/tests/resample/test_base.py b/pandas/tests/resample/test_base.py
index 1154bc3316ae8..2244f6eba9479 100644
--- a/pandas/tests/resample/test_base.py
+++ b/pandas/tests/resample/test_base.py
@@ -3,7 +3,12 @@
import numpy as np
import pytest
-from pandas import DataFrame, NaT, PeriodIndex, Series
+from pandas import (
+ DataFrame,
+ NaT,
+ PeriodIndex,
+ Series,
+)
import pandas._testing as tm
from pandas.core.groupby.groupby import DataError
from pandas.core.groupby.grouper import Grouper
diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py
index c23a22448fbb0..cbf69696d5801 100644
--- a/pandas/tests/resample/test_datetime_index.py
+++ b/pandas/tests/resample/test_datetime_index.py
@@ -10,12 +10,25 @@
from pandas.errors import UnsupportedFunctionCall
import pandas as pd
-from pandas import DataFrame, Series, Timedelta, Timestamp, isna, notna
+from pandas import (
+ DataFrame,
+ Series,
+ Timedelta,
+ Timestamp,
+ isna,
+ notna,
+)
import pandas._testing as tm
from pandas.core.groupby.grouper import Grouper
from pandas.core.indexes.datetimes import date_range
-from pandas.core.indexes.period import Period, period_range
-from pandas.core.resample import DatetimeIndex, _get_timestamp_range_edges
+from pandas.core.indexes.period import (
+ Period,
+ period_range,
+)
+from pandas.core.resample import (
+ DatetimeIndex,
+ _get_timestamp_range_edges,
+)
import pandas.tseries.offsets as offsets
from pandas.tseries.offsets import Minute
diff --git a/pandas/tests/resample/test_deprecated.py b/pandas/tests/resample/test_deprecated.py
index b3d568678afb5..d3672b3d32be1 100644
--- a/pandas/tests/resample/test_deprecated.py
+++ b/pandas/tests/resample/test_deprecated.py
@@ -1,16 +1,28 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import numpy as np
import pytest
import pandas as pd
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
from pandas.core.indexes.datetimes import date_range
-from pandas.core.indexes.period import PeriodIndex, period_range
+from pandas.core.indexes.period import (
+ PeriodIndex,
+ period_range,
+)
from pandas.core.indexes.timedeltas import timedelta_range
-from pandas.tseries.offsets import BDay, Minute
+from pandas.tseries.offsets import (
+ BDay,
+ Minute,
+)
DATE_RANGE = (date_range, "dti", datetime(2005, 1, 1), datetime(2005, 1, 10))
PERIOD_RANGE = (period_range, "pi", datetime(2005, 1, 1), datetime(2005, 1, 10))
diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py
index 2fe3fb91768e6..5dab0cbafbc59 100644
--- a/pandas/tests/resample/test_period_index.py
+++ b/pandas/tests/resample/test_period_index.py
@@ -5,15 +5,26 @@
import pytest
import pytz
-from pandas._libs.tslibs.ccalendar import DAYS, MONTHS
+from pandas._libs.tslibs.ccalendar import (
+ DAYS,
+ MONTHS,
+)
from pandas._libs.tslibs.period import IncompatibleFrequency
from pandas.errors import InvalidIndexError
import pandas as pd
-from pandas import DataFrame, Series, Timestamp
+from pandas import (
+ DataFrame,
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
from pandas.core.indexes.datetimes import date_range
-from pandas.core.indexes.period import Period, PeriodIndex, period_range
+from pandas.core.indexes.period import (
+ Period,
+ PeriodIndex,
+ period_range,
+)
from pandas.core.resample import _get_period_range_edges
import pandas.tseries.offsets as offsets
diff --git a/pandas/tests/resample/test_resample_api.py b/pandas/tests/resample/test_resample_api.py
index d217957cbe08a..48c068be843a9 100644
--- a/pandas/tests/resample/test_resample_api.py
+++ b/pandas/tests/resample/test_resample_api.py
@@ -4,7 +4,10 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
from pandas.core.indexes.datetimes import date_range
diff --git a/pandas/tests/resample/test_resampler_grouper.py b/pandas/tests/resample/test_resampler_grouper.py
index 39d4533ca08dc..a17ed44c4011a 100644
--- a/pandas/tests/resample/test_resampler_grouper.py
+++ b/pandas/tests/resample/test_resampler_grouper.py
@@ -7,7 +7,11 @@
from pandas.util._test_decorators import async_mark
import pandas as pd
-from pandas import DataFrame, Series, Timestamp
+from pandas import (
+ DataFrame,
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
from pandas.core.indexes.datetimes import date_range
diff --git a/pandas/tests/resample/test_time_grouper.py b/pandas/tests/resample/test_time_grouper.py
index c669cf39c9a61..e62c907032938 100644
--- a/pandas/tests/resample/test_time_grouper.py
+++ b/pandas/tests/resample/test_time_grouper.py
@@ -5,7 +5,11 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Series, Timestamp
+from pandas import (
+ DataFrame,
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
from pandas.core.groupby.grouper import Grouper
from pandas.core.indexes.datetimes import date_range
diff --git a/pandas/tests/resample/test_timedelta.py b/pandas/tests/resample/test_timedelta.py
index 1c440b889b146..ee08dac09695b 100644
--- a/pandas/tests/resample/test_timedelta.py
+++ b/pandas/tests/resample/test_timedelta.py
@@ -4,7 +4,10 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
from pandas.core.indexes.timedeltas import timedelta_range
diff --git a/pandas/tests/reshape/concat/test_append.py b/pandas/tests/reshape/concat/test_append.py
index 81d5526f5bd15..7b9f8d1c2879e 100644
--- a/pandas/tests/reshape/concat/test_append.py
+++ b/pandas/tests/reshape/concat/test_append.py
@@ -7,7 +7,14 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, Series, Timestamp, concat, isna
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ Timestamp,
+ concat,
+ isna,
+)
import pandas._testing as tm
diff --git a/pandas/tests/reshape/concat/test_append_common.py b/pandas/tests/reshape/concat/test_append_common.py
index 8b7fb69f7ee05..9bd098a9e4e72 100644
--- a/pandas/tests/reshape/concat/test_append_common.py
+++ b/pandas/tests/reshape/concat/test_append_common.py
@@ -2,7 +2,12 @@
import pytest
import pandas as pd
-from pandas import Categorical, DataFrame, Index, Series
+from pandas import (
+ Categorical,
+ DataFrame,
+ Index,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/reshape/concat/test_categorical.py b/pandas/tests/reshape/concat/test_categorical.py
index 357274b66332f..a81085e083199 100644
--- a/pandas/tests/reshape/concat/test_categorical.py
+++ b/pandas/tests/reshape/concat/test_categorical.py
@@ -3,7 +3,11 @@
from pandas.core.dtypes.dtypes import CategoricalDtype
import pandas as pd
-from pandas import Categorical, DataFrame, Series
+from pandas import (
+ Categorical,
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/reshape/concat/test_concat.py b/pandas/tests/reshape/concat/test_concat.py
index 575903de8f946..8f18f87f2decc 100644
--- a/pandas/tests/reshape/concat/test_concat.py
+++ b/pandas/tests/reshape/concat/test_concat.py
@@ -1,4 +1,7 @@
-from collections import abc, deque
+from collections import (
+ abc,
+ deque,
+)
from decimal import Decimal
from warnings import catch_warnings
@@ -6,7 +9,14 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series, concat, date_range
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ concat,
+ date_range,
+)
import pandas._testing as tm
from pandas.core.arrays import SparseArray
from pandas.core.construction import create_series_with_explicit_dtype
diff --git a/pandas/tests/reshape/concat/test_dataframe.py b/pandas/tests/reshape/concat/test_dataframe.py
index 295846ee1b264..f5eb0ab8c9a17 100644
--- a/pandas/tests/reshape/concat/test_dataframe.py
+++ b/pandas/tests/reshape/concat/test_dataframe.py
@@ -2,7 +2,12 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, Series, concat
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ concat,
+)
import pandas._testing as tm
diff --git a/pandas/tests/reshape/concat/test_empty.py b/pandas/tests/reshape/concat/test_empty.py
index a97e9265b4f99..0e86cb0ae48c0 100644
--- a/pandas/tests/reshape/concat/test_empty.py
+++ b/pandas/tests/reshape/concat/test_empty.py
@@ -2,7 +2,13 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, Series, concat, date_range
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ concat,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/reshape/concat/test_index.py b/pandas/tests/reshape/concat/test_index.py
index 3fc886893b55a..c822dab9b8cfc 100644
--- a/pandas/tests/reshape/concat/test_index.py
+++ b/pandas/tests/reshape/concat/test_index.py
@@ -2,7 +2,13 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series, concat
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ concat,
+)
import pandas._testing as tm
diff --git a/pandas/tests/reshape/concat/test_invalid.py b/pandas/tests/reshape/concat/test_invalid.py
index cc9f09c16fb43..95a81ce61c785 100644
--- a/pandas/tests/reshape/concat/test_invalid.py
+++ b/pandas/tests/reshape/concat/test_invalid.py
@@ -3,7 +3,11 @@
import numpy as np
import pytest
-from pandas import DataFrame, concat, read_csv
+from pandas import (
+ DataFrame,
+ concat,
+ read_csv,
+)
import pandas._testing as tm
diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py
index 500d7000817af..e5499c44be7d7 100644
--- a/pandas/tests/reshape/merge/test_join.py
+++ b/pandas/tests/reshape/merge/test_join.py
@@ -13,7 +13,11 @@
merge,
)
import pandas._testing as tm
-from pandas.tests.reshape.merge.test_merge import NGROUPS, N, get_test_data
+from pandas.tests.reshape.merge.test_merge import (
+ NGROUPS,
+ N,
+ get_test_data,
+)
a_ = np.array
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index da3ac81c4aa17..d9af59382ae79 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -1,11 +1,18 @@
-from datetime import date, datetime, timedelta
+from datetime import (
+ date,
+ datetime,
+ timedelta,
+)
import random
import re
import numpy as np
import pytest
-from pandas.core.dtypes.common import is_categorical_dtype, is_object_dtype
+from pandas.core.dtypes.common import (
+ is_categorical_dtype,
+ is_object_dtype,
+)
from pandas.core.dtypes.dtypes import CategoricalDtype
import pandas as pd
@@ -27,7 +34,10 @@
import pandas._testing as tm
from pandas.api.types import CategoricalDtype as CDT
from pandas.core.reshape.concat import concat
-from pandas.core.reshape.merge import MergeError, merge
+from pandas.core.reshape.merge import (
+ MergeError,
+ merge,
+)
N = 50
NGROUPS = 8
diff --git a/pandas/tests/reshape/merge/test_merge_asof.py b/pandas/tests/reshape/merge/test_merge_asof.py
index ecff63b495fbb..5fa08904e3fcf 100644
--- a/pandas/tests/reshape/merge/test_merge_asof.py
+++ b/pandas/tests/reshape/merge/test_merge_asof.py
@@ -5,7 +5,12 @@
import pytz
import pandas as pd
-from pandas import Timedelta, merge_asof, read_csv, to_datetime
+from pandas import (
+ Timedelta,
+ merge_asof,
+ read_csv,
+ to_datetime,
+)
import pandas._testing as tm
from pandas.core.reshape.merge import MergeError
diff --git a/pandas/tests/reshape/merge/test_merge_cross.py b/pandas/tests/reshape/merge/test_merge_cross.py
index d6c29ea129027..7e14b515836cf 100644
--- a/pandas/tests/reshape/merge/test_merge_cross.py
+++ b/pandas/tests/reshape/merge/test_merge_cross.py
@@ -2,7 +2,10 @@
from pandas import DataFrame
import pandas._testing as tm
-from pandas.core.reshape.merge import MergeError, merge
+from pandas.core.reshape.merge import (
+ MergeError,
+ merge,
+)
@pytest.mark.parametrize(
diff --git a/pandas/tests/reshape/merge/test_merge_ordered.py b/pandas/tests/reshape/merge/test_merge_ordered.py
index 4a70719df5c57..4a4af789d540b 100644
--- a/pandas/tests/reshape/merge/test_merge_ordered.py
+++ b/pandas/tests/reshape/merge/test_merge_ordered.py
@@ -2,7 +2,10 @@
import pytest
import pandas as pd
-from pandas import DataFrame, merge_ordered
+from pandas import (
+ DataFrame,
+ merge_ordered,
+)
import pandas._testing as tm
diff --git a/pandas/tests/reshape/merge/test_multi.py b/pandas/tests/reshape/merge/test_multi.py
index f47f4e1577277..56ea3c9718a41 100644
--- a/pandas/tests/reshape/merge/test_multi.py
+++ b/pandas/tests/reshape/merge/test_multi.py
@@ -2,7 +2,13 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series, Timestamp
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
from pandas.core.reshape.concat import concat
from pandas.core.reshape.merge import merge
diff --git a/pandas/tests/reshape/test_crosstab.py b/pandas/tests/reshape/test_crosstab.py
index 6faf64789c687..86cde3eee874d 100644
--- a/pandas/tests/reshape/test_crosstab.py
+++ b/pandas/tests/reshape/test_crosstab.py
@@ -3,7 +3,14 @@
from pandas.core.dtypes.common import is_categorical_dtype
-from pandas import CategoricalIndex, DataFrame, Index, MultiIndex, Series, crosstab
+from pandas import (
+ CategoricalIndex,
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ crosstab,
+)
import pandas._testing as tm
diff --git a/pandas/tests/reshape/test_get_dummies.py b/pandas/tests/reshape/test_get_dummies.py
index 42907b3b4e23f..8af49ac20987a 100644
--- a/pandas/tests/reshape/test_get_dummies.py
+++ b/pandas/tests/reshape/test_get_dummies.py
@@ -6,9 +6,18 @@
from pandas.core.dtypes.common import is_integer_dtype
import pandas as pd
-from pandas import Categorical, CategoricalIndex, DataFrame, Series, get_dummies
+from pandas import (
+ Categorical,
+ CategoricalIndex,
+ DataFrame,
+ Series,
+ get_dummies,
+)
import pandas._testing as tm
-from pandas.core.arrays.sparse import SparseArray, SparseDtype
+from pandas.core.arrays.sparse import (
+ SparseArray,
+ SparseDtype,
+)
class TestGetDummies:
diff --git a/pandas/tests/reshape/test_melt.py b/pandas/tests/reshape/test_melt.py
index 1f39302845ae9..53244569d0432 100644
--- a/pandas/tests/reshape/test_melt.py
+++ b/pandas/tests/reshape/test_melt.py
@@ -2,7 +2,12 @@
import pytest
import pandas as pd
-from pandas import DataFrame, lreshape, melt, wide_to_long
+from pandas import (
+ DataFrame,
+ lreshape,
+ melt,
+ wide_to_long,
+)
import pandas._testing as tm
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
index f9b2a02920841..19eba4305fdf6 100644
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -1,4 +1,8 @@
-from datetime import date, datetime, timedelta
+from datetime import (
+ date,
+ datetime,
+ timedelta,
+)
from itertools import product
import numpy as np
diff --git a/pandas/tests/reshape/test_pivot_multilevel.py b/pandas/tests/reshape/test_pivot_multilevel.py
index f59a469c05d15..df2ae0d52c660 100644
--- a/pandas/tests/reshape/test_pivot_multilevel.py
+++ b/pandas/tests/reshape/test_pivot_multilevel.py
@@ -2,7 +2,11 @@
import pytest
import pandas as pd
-from pandas import Index, Int64Index, MultiIndex
+from pandas import (
+ Index,
+ Int64Index,
+ MultiIndex,
+)
import pandas._testing as tm
diff --git a/pandas/tests/reshape/test_qcut.py b/pandas/tests/reshape/test_qcut.py
index e7a04bafed8e3..d48fde35f8561 100644
--- a/pandas/tests/reshape/test_qcut.py
+++ b/pandas/tests/reshape/test_qcut.py
@@ -23,7 +23,10 @@
from pandas.api.types import CategoricalDtype as CDT
from pandas.core.algorithms import quantile
-from pandas.tseries.offsets import Day, Nano
+from pandas.tseries.offsets import (
+ Day,
+ Nano,
+)
def test_qcut():
diff --git a/pandas/tests/reshape/test_union_categoricals.py b/pandas/tests/reshape/test_union_categoricals.py
index 8c0c0a1f22760..f39b5de2478b0 100644
--- a/pandas/tests/reshape/test_union_categoricals.py
+++ b/pandas/tests/reshape/test_union_categoricals.py
@@ -4,7 +4,11 @@
from pandas.core.dtypes.concat import union_categoricals
import pandas as pd
-from pandas import Categorical, CategoricalIndex, Series
+from pandas import (
+ Categorical,
+ CategoricalIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/reshape/test_util.py b/pandas/tests/reshape/test_util.py
index 0acadc54cec0c..890562712f3b7 100644
--- a/pandas/tests/reshape/test_util.py
+++ b/pandas/tests/reshape/test_util.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import Index, date_range
+from pandas import (
+ Index,
+ date_range,
+)
import pandas._testing as tm
from pandas.core.reshape.util import cartesian_product
diff --git a/pandas/tests/scalar/interval/test_arithmetic.py b/pandas/tests/scalar/interval/test_arithmetic.py
index b4c2b448e252a..987f7d53afacc 100644
--- a/pandas/tests/scalar/interval/test_arithmetic.py
+++ b/pandas/tests/scalar/interval/test_arithmetic.py
@@ -3,7 +3,11 @@
import numpy as np
import pytest
-from pandas import Interval, Timedelta, Timestamp
+from pandas import (
+ Interval,
+ Timedelta,
+ Timestamp,
+)
@pytest.mark.parametrize("method", ["__add__", "__sub__"])
diff --git a/pandas/tests/scalar/interval/test_interval.py b/pandas/tests/scalar/interval/test_interval.py
index 5071c5cdec6c8..1f76a7df1e996 100644
--- a/pandas/tests/scalar/interval/test_interval.py
+++ b/pandas/tests/scalar/interval/test_interval.py
@@ -1,7 +1,12 @@
import numpy as np
import pytest
-from pandas import Interval, Period, Timedelta, Timestamp
+from pandas import (
+ Interval,
+ Period,
+ Timedelta,
+ Timestamp,
+)
import pandas._testing as tm
import pandas.core.common as com
diff --git a/pandas/tests/scalar/interval/test_ops.py b/pandas/tests/scalar/interval/test_ops.py
index 2d9f0954af5a8..9fe40c208d880 100644
--- a/pandas/tests/scalar/interval/test_ops.py
+++ b/pandas/tests/scalar/interval/test_ops.py
@@ -1,7 +1,11 @@
"""Tests for Interval-Interval operations, such as overlaps, contains, etc."""
import pytest
-from pandas import Interval, Timedelta, Timestamp
+from pandas import (
+ Interval,
+ Timedelta,
+ Timestamp,
+)
@pytest.fixture(
diff --git a/pandas/tests/scalar/period/test_asfreq.py b/pandas/tests/scalar/period/test_asfreq.py
index 56281521deb90..9110352d33c26 100644
--- a/pandas/tests/scalar/period/test_asfreq.py
+++ b/pandas/tests/scalar/period/test_asfreq.py
@@ -4,7 +4,11 @@
from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG
from pandas.errors import OutOfBoundsDatetime
-from pandas import Period, Timestamp, offsets
+from pandas import (
+ Period,
+ Timestamp,
+ offsets,
+)
class TestFreqConversion:
diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py
index 285bf37176af6..7dcd4dc979eb2 100644
--- a/pandas/tests/scalar/period/test_period.py
+++ b/pandas/tests/scalar/period/test_period.py
@@ -1,19 +1,41 @@
-from datetime import date, datetime, timedelta
+from datetime import (
+ date,
+ datetime,
+ timedelta,
+)
import numpy as np
import pytest
import pytz
-from pandas._libs.tslibs import iNaT, period as libperiod
-from pandas._libs.tslibs.ccalendar import DAYS, MONTHS
+from pandas._libs.tslibs import (
+ iNaT,
+ period as libperiod,
+)
+from pandas._libs.tslibs.ccalendar import (
+ DAYS,
+ MONTHS,
+)
from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime
from pandas._libs.tslibs.parsing import DateParseError
-from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG, IncompatibleFrequency
-from pandas._libs.tslibs.timezones import dateutil_gettz, maybe_get_tz
+from pandas._libs.tslibs.period import (
+ INVALID_FREQ_ERR_MSG,
+ IncompatibleFrequency,
+)
+from pandas._libs.tslibs.timezones import (
+ dateutil_gettz,
+ maybe_get_tz,
+)
from pandas.compat import np_datetime64_compat
import pandas as pd
-from pandas import NaT, Period, Timedelta, Timestamp, offsets
+from pandas import (
+ NaT,
+ Period,
+ Timedelta,
+ Timestamp,
+ offsets,
+)
import pandas._testing as tm
diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py
index ea867d8607d2e..9ccdd0261de0e 100644
--- a/pandas/tests/scalar/test_nat.py
+++ b/pandas/tests/scalar/test_nat.py
@@ -1,4 +1,7 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import operator
import numpy as np
@@ -24,7 +27,11 @@
offsets,
)
import pandas._testing as tm
-from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray
+from pandas.core.arrays import (
+ DatetimeArray,
+ PeriodArray,
+ TimedeltaArray,
+)
from pandas.core.ops import roperator
diff --git a/pandas/tests/scalar/timedelta/test_arithmetic.py b/pandas/tests/scalar/timedelta/test_arithmetic.py
index 41671343c2800..b9594a9c876c6 100644
--- a/pandas/tests/scalar/timedelta/test_arithmetic.py
+++ b/pandas/tests/scalar/timedelta/test_arithmetic.py
@@ -1,7 +1,10 @@
"""
Tests for scalar Timedelta arithmetic ops
"""
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import operator
import numpy as np
@@ -10,7 +13,13 @@
from pandas.compat import is_numpy_dev
import pandas as pd
-from pandas import NaT, Timedelta, Timestamp, compat, offsets
+from pandas import (
+ NaT,
+ Timedelta,
+ Timestamp,
+ compat,
+ offsets,
+)
import pandas._testing as tm
from pandas.core import ops
diff --git a/pandas/tests/scalar/timedelta/test_constructors.py b/pandas/tests/scalar/timedelta/test_constructors.py
index 9cbe165434369..47b09280854de 100644
--- a/pandas/tests/scalar/timedelta/test_constructors.py
+++ b/pandas/tests/scalar/timedelta/test_constructors.py
@@ -6,7 +6,11 @@
from pandas._libs.tslibs import OutOfBoundsTimedelta
-from pandas import Timedelta, offsets, to_timedelta
+from pandas import (
+ Timedelta,
+ offsets,
+ to_timedelta,
+)
def test_construction():
diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py
index 906ed038c4840..8b42bca8b8a0c 100644
--- a/pandas/tests/scalar/timedelta/test_timedelta.py
+++ b/pandas/tests/scalar/timedelta/test_timedelta.py
@@ -4,10 +4,18 @@
import numpy as np
import pytest
-from pandas._libs.tslibs import NaT, iNaT
+from pandas._libs.tslibs import (
+ NaT,
+ iNaT,
+)
import pandas as pd
-from pandas import Timedelta, TimedeltaIndex, offsets, to_timedelta
+from pandas import (
+ Timedelta,
+ TimedeltaIndex,
+ offsets,
+ to_timedelta,
+)
import pandas._testing as tm
diff --git a/pandas/tests/scalar/timestamp/test_arithmetic.py b/pandas/tests/scalar/timestamp/test_arithmetic.py
index 1e980b6e4559c..e178b31b9ae93 100644
--- a/pandas/tests/scalar/timestamp/test_arithmetic.py
+++ b/pandas/tests/scalar/timestamp/test_arithmetic.py
@@ -1,4 +1,7 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import numpy as np
import pytest
diff --git a/pandas/tests/scalar/timestamp/test_comparisons.py b/pandas/tests/scalar/timestamp/test_comparisons.py
index 9ee7cb1840e5b..555067f2aba1a 100644
--- a/pandas/tests/scalar/timestamp/test_comparisons.py
+++ b/pandas/tests/scalar/timestamp/test_comparisons.py
@@ -1,4 +1,7 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import operator
import numpy as np
diff --git a/pandas/tests/scalar/timestamp/test_constructors.py b/pandas/tests/scalar/timestamp/test_constructors.py
index 654c7d502610e..663892cefb5e6 100644
--- a/pandas/tests/scalar/timestamp/test_constructors.py
+++ b/pandas/tests/scalar/timestamp/test_constructors.py
@@ -1,5 +1,8 @@
import calendar
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import dateutil.tz
from dateutil.tz import tzutc
@@ -9,7 +12,12 @@
from pandas.errors import OutOfBoundsDatetime
-from pandas import Period, Timedelta, Timestamp, compat
+from pandas import (
+ Period,
+ Timedelta,
+ Timestamp,
+ compat,
+)
from pandas.tseries import offsets
diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py
index c94c16d1d603a..6bd794b1933a2 100644
--- a/pandas/tests/scalar/timestamp/test_timestamp.py
+++ b/pandas/tests/scalar/timestamp/test_timestamp.py
@@ -1,7 +1,10 @@
""" test the scalar Timestamp """
import calendar
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import locale
import unicodedata
@@ -9,13 +12,23 @@
import numpy as np
import pytest
import pytz
-from pytz import timezone, utc
+from pytz import (
+ timezone,
+ utc,
+)
-from pandas._libs.tslibs.timezones import dateutil_gettz as gettz, get_timezone
+from pandas._libs.tslibs.timezones import (
+ dateutil_gettz as gettz,
+ get_timezone,
+)
from pandas.compat import np_datetime64_compat
import pandas.util._test_decorators as td
-from pandas import NaT, Timedelta, Timestamp
+from pandas import (
+ NaT,
+ Timedelta,
+ Timestamp,
+)
import pandas._testing as tm
from pandas.tseries import offsets
diff --git a/pandas/tests/scalar/timestamp/test_timezones.py b/pandas/tests/scalar/timestamp/test_timezones.py
index f05f2054b2483..9ba4a2c1f77cd 100644
--- a/pandas/tests/scalar/timestamp/test_timezones.py
+++ b/pandas/tests/scalar/timestamp/test_timezones.py
@@ -1,19 +1,32 @@
"""
Tests for Timestamp timezone-related methods
"""
-from datetime import date, datetime, timedelta
+from datetime import (
+ date,
+ datetime,
+ timedelta,
+)
import dateutil
-from dateutil.tz import gettz, tzoffset
+from dateutil.tz import (
+ gettz,
+ tzoffset,
+)
import pytest
import pytz
-from pytz.exceptions import AmbiguousTimeError, NonExistentTimeError
+from pytz.exceptions import (
+ AmbiguousTimeError,
+ NonExistentTimeError,
+)
from pandas._libs.tslibs import timezones
from pandas.errors import OutOfBoundsDatetime
import pandas.util._test_decorators as td
-from pandas import NaT, Timestamp
+from pandas import (
+ NaT,
+ Timestamp,
+)
class TestTimestampTZOperations:
diff --git a/pandas/tests/scalar/timestamp/test_unary_ops.py b/pandas/tests/scalar/timestamp/test_unary_ops.py
index 4278d185ea7dd..aab0b2e6d31ef 100644
--- a/pandas/tests/scalar/timestamp/test_unary_ops.py
+++ b/pandas/tests/scalar/timestamp/test_unary_ops.py
@@ -6,7 +6,13 @@
import pytz
from pytz import utc
-from pandas._libs.tslibs import NaT, Timedelta, Timestamp, conversion, to_offset
+from pandas._libs.tslibs import (
+ NaT,
+ Timedelta,
+ Timestamp,
+ conversion,
+ to_offset,
+)
from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG
import pandas.util._test_decorators as td
diff --git a/pandas/tests/series/accessors/test_dt_accessor.py b/pandas/tests/series/accessors/test_dt_accessor.py
index 7a84f642aebc2..6199e77e10166 100644
--- a/pandas/tests/series/accessors/test_dt_accessor.py
+++ b/pandas/tests/series/accessors/test_dt_accessor.py
@@ -1,5 +1,9 @@
import calendar
-from datetime import date, datetime, time
+from datetime import (
+ date,
+ datetime,
+ time,
+)
import locale
import unicodedata
@@ -9,7 +13,10 @@
from pandas._libs.tslibs.timezones import maybe_get_tz
-from pandas.core.dtypes.common import is_integer_dtype, is_list_like
+from pandas.core.dtypes.common import (
+ is_integer_dtype,
+ is_list_like,
+)
import pandas as pd
from pandas import (
@@ -573,7 +580,10 @@ def test_strftime_nat(self, data):
def test_valid_dt_with_missing_values(self):
- from datetime import date, time
+ from datetime import (
+ date,
+ time,
+ )
# GH 8689
s = Series(date_range("20130101", periods=5, freq="D"))
diff --git a/pandas/tests/series/indexing/test_datetime.py b/pandas/tests/series/indexing/test_datetime.py
index 6c595e1f0f19f..347aa8d66405c 100644
--- a/pandas/tests/series/indexing/test_datetime.py
+++ b/pandas/tests/series/indexing/test_datetime.py
@@ -1,10 +1,16 @@
"""
Also test support for datetime64[ns] in Series / DataFrame
"""
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import re
-from dateutil.tz import gettz, tzutc
+from dateutil.tz import (
+ gettz,
+ tzutc,
+)
import numpy as np
import pytest
import pytz
@@ -12,7 +18,13 @@
from pandas._libs import index as libindex
import pandas as pd
-from pandas import DataFrame, Series, Timestamp, date_range, period_range
+from pandas import (
+ DataFrame,
+ Series,
+ Timestamp,
+ date_range,
+ period_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/indexing/test_delitem.py b/pandas/tests/series/indexing/test_delitem.py
index 6c7e3f2b06983..019cb92d780ef 100644
--- a/pandas/tests/series/indexing/test_delitem.py
+++ b/pandas/tests/series/indexing/test_delitem.py
@@ -1,6 +1,9 @@
import pytest
-from pandas import Index, Series
+from pandas import (
+ Index,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/indexing/test_getitem.py b/pandas/tests/series/indexing/test_getitem.py
index 5a5e285bf719f..740d029effc94 100644
--- a/pandas/tests/series/indexing/test_getitem.py
+++ b/pandas/tests/series/indexing/test_getitem.py
@@ -1,12 +1,19 @@
"""
Series.__getitem__ test classes are organized by the type of key passed.
"""
-from datetime import date, datetime, time
+from datetime import (
+ date,
+ datetime,
+ time,
+)
import numpy as np
import pytest
-from pandas._libs.tslibs import conversion, timezones
+from pandas._libs.tslibs import (
+ conversion,
+ timezones,
+)
import pandas as pd
from pandas import (
diff --git a/pandas/tests/series/indexing/test_set_value.py b/pandas/tests/series/indexing/test_set_value.py
index 61b01720d1e40..cbe1a8bf296c8 100644
--- a/pandas/tests/series/indexing/test_set_value.py
+++ b/pandas/tests/series/indexing/test_set_value.py
@@ -2,7 +2,10 @@
import numpy as np
-from pandas import DatetimeIndex, Series
+from pandas import (
+ DatetimeIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py
index 36948c3dc05f3..f52aa340ef238 100644
--- a/pandas/tests/series/indexing/test_setitem.py
+++ b/pandas/tests/series/indexing/test_setitem.py
@@ -1,4 +1,7 @@
-from datetime import date, datetime
+from datetime import (
+ date,
+ datetime,
+)
import numpy as np
import pytest
diff --git a/pandas/tests/series/indexing/test_where.py b/pandas/tests/series/indexing/test_where.py
index edcec386cd8ba..1e50fef55b4ec 100644
--- a/pandas/tests/series/indexing/test_where.py
+++ b/pandas/tests/series/indexing/test_where.py
@@ -4,7 +4,12 @@
from pandas.core.dtypes.common import is_integer
import pandas as pd
-from pandas import Series, Timestamp, date_range, isna
+from pandas import (
+ Series,
+ Timestamp,
+ date_range,
+ isna,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/indexing/test_xs.py b/pandas/tests/series/indexing/test_xs.py
index 83cc6d4670423..b6351e970222f 100644
--- a/pandas/tests/series/indexing/test_xs.py
+++ b/pandas/tests/series/indexing/test_xs.py
@@ -1,6 +1,10 @@
import numpy as np
-from pandas import MultiIndex, Series, date_range
+from pandas import (
+ MultiIndex,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_align.py b/pandas/tests/series/methods/test_align.py
index ef2b07d592b95..8769ab048a136 100644
--- a/pandas/tests/series/methods/test_align.py
+++ b/pandas/tests/series/methods/test_align.py
@@ -3,7 +3,11 @@
import pytz
import pandas as pd
-from pandas import Series, date_range, period_range
+from pandas import (
+ Series,
+ date_range,
+ period_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_append.py b/pandas/tests/series/methods/test_append.py
index 069557cc65455..2081e244b4e6c 100644
--- a/pandas/tests/series/methods/test_append.py
+++ b/pandas/tests/series/methods/test_append.py
@@ -2,7 +2,14 @@
import pytest
import pandas as pd
-from pandas import DataFrame, DatetimeIndex, Index, Series, Timestamp, date_range
+from pandas import (
+ DataFrame,
+ DatetimeIndex,
+ Index,
+ Series,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_argsort.py b/pandas/tests/series/methods/test_argsort.py
index ec9ba468c996c..7a545378ef402 100644
--- a/pandas/tests/series/methods/test_argsort.py
+++ b/pandas/tests/series/methods/test_argsort.py
@@ -1,7 +1,11 @@
import numpy as np
import pytest
-from pandas import Series, Timestamp, isna
+from pandas import (
+ Series,
+ Timestamp,
+ isna,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_asfreq.py b/pandas/tests/series/methods/test_asfreq.py
index cd61c510c75f5..9a7f2343984d6 100644
--- a/pandas/tests/series/methods/test_asfreq.py
+++ b/pandas/tests/series/methods/test_asfreq.py
@@ -3,10 +3,19 @@
import numpy as np
import pytest
-from pandas import DataFrame, DatetimeIndex, Series, date_range, period_range
+from pandas import (
+ DataFrame,
+ DatetimeIndex,
+ Series,
+ date_range,
+ period_range,
+)
import pandas._testing as tm
-from pandas.tseries.offsets import BDay, BMonthEnd
+from pandas.tseries.offsets import (
+ BDay,
+ BMonthEnd,
+)
class TestAsFreq:
diff --git a/pandas/tests/series/methods/test_asof.py b/pandas/tests/series/methods/test_asof.py
index 43d40d53dcd21..7a3f68fd3d990 100644
--- a/pandas/tests/series/methods/test_asof.py
+++ b/pandas/tests/series/methods/test_asof.py
@@ -3,7 +3,14 @@
from pandas._libs.tslibs import IncompatibleFrequency
-from pandas import Series, Timestamp, date_range, isna, notna, offsets
+from pandas import (
+ Series,
+ Timestamp,
+ date_range,
+ isna,
+ notna,
+ offsets,
+)
import pandas._testing as tm
@@ -90,7 +97,10 @@ def test_with_nan(self):
tm.assert_series_equal(result, expected)
def test_periodindex(self):
- from pandas import PeriodIndex, period_range
+ from pandas import (
+ PeriodIndex,
+ period_range,
+ )
# array or list or dates
N = 50
diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py
index d683503f22f28..d14261fef67a6 100644
--- a/pandas/tests/series/methods/test_astype.py
+++ b/pandas/tests/series/methods/test_astype.py
@@ -1,4 +1,7 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
from importlib import reload
import string
import sys
diff --git a/pandas/tests/series/methods/test_between.py b/pandas/tests/series/methods/test_between.py
index 350a3fe6ff009..381c733619c6b 100644
--- a/pandas/tests/series/methods/test_between.py
+++ b/pandas/tests/series/methods/test_between.py
@@ -1,6 +1,11 @@
import numpy as np
-from pandas import Series, bdate_range, date_range, period_range
+from pandas import (
+ Series,
+ bdate_range,
+ date_range,
+ period_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_clip.py b/pandas/tests/series/methods/test_clip.py
index 5a5a397222b87..528e95f65c8f4 100644
--- a/pandas/tests/series/methods/test_clip.py
+++ b/pandas/tests/series/methods/test_clip.py
@@ -2,7 +2,12 @@
import pytest
import pandas as pd
-from pandas import Series, Timestamp, isna, notna
+from pandas import (
+ Series,
+ Timestamp,
+ isna,
+ notna,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_combine_first.py b/pandas/tests/series/methods/test_combine_first.py
index 94aa6b8d84cad..4c254c6db2a70 100644
--- a/pandas/tests/series/methods/test_combine_first.py
+++ b/pandas/tests/series/methods/test_combine_first.py
@@ -3,7 +3,13 @@
import numpy as np
import pandas as pd
-from pandas import Period, Series, date_range, period_range, to_datetime
+from pandas import (
+ Period,
+ Series,
+ date_range,
+ period_range,
+ to_datetime,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_convert.py b/pandas/tests/series/methods/test_convert.py
index f052f4423d32a..b658929dfd0d5 100644
--- a/pandas/tests/series/methods/test_convert.py
+++ b/pandas/tests/series/methods/test_convert.py
@@ -3,7 +3,10 @@
import numpy as np
import pytest
-from pandas import Series, Timestamp
+from pandas import (
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_copy.py b/pandas/tests/series/methods/test_copy.py
index 6201c0f5f7c29..8aa5c14812dc0 100644
--- a/pandas/tests/series/methods/test_copy.py
+++ b/pandas/tests/series/methods/test_copy.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import Series, Timestamp
+from pandas import (
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_count.py b/pandas/tests/series/methods/test_count.py
index 7fff87c7b55f4..937bb383dd35c 100644
--- a/pandas/tests/series/methods/test_count.py
+++ b/pandas/tests/series/methods/test_count.py
@@ -2,7 +2,11 @@
import pytest
import pandas as pd
-from pandas import Categorical, MultiIndex, Series
+from pandas import (
+ Categorical,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_cov_corr.py b/pandas/tests/series/methods/test_cov_corr.py
index f01ed73c0165f..58a332ace244f 100644
--- a/pandas/tests/series/methods/test_cov_corr.py
+++ b/pandas/tests/series/methods/test_cov_corr.py
@@ -6,7 +6,10 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import Series, isna
+from pandas import (
+ Series,
+ isna,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_describe.py b/pandas/tests/series/methods/test_describe.py
index e479e5c1416db..1113efc972e76 100644
--- a/pandas/tests/series/methods/test_describe.py
+++ b/pandas/tests/series/methods/test_describe.py
@@ -2,7 +2,13 @@
import pandas.util._test_decorators as td
-from pandas import Period, Series, Timedelta, Timestamp, date_range
+from pandas import (
+ Period,
+ Series,
+ Timedelta,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
# TODO(ArrayManager) quantile is needed for describe()
diff --git a/pandas/tests/series/methods/test_diff.py b/pandas/tests/series/methods/test_diff.py
index 033f75e95f11b..1fbce249af6d2 100644
--- a/pandas/tests/series/methods/test_diff.py
+++ b/pandas/tests/series/methods/test_diff.py
@@ -1,7 +1,11 @@
import numpy as np
import pytest
-from pandas import Series, TimedeltaIndex, date_range
+from pandas import (
+ Series,
+ TimedeltaIndex,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_drop_duplicates.py b/pandas/tests/series/methods/test_drop_duplicates.py
index fe4bcb44d5e61..dae1bbcd86e81 100644
--- a/pandas/tests/series/methods/test_drop_duplicates.py
+++ b/pandas/tests/series/methods/test_drop_duplicates.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import Categorical, Series
+from pandas import (
+ Categorical,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_dropna.py b/pandas/tests/series/methods/test_dropna.py
index f56230daea190..1c7c52d228cfa 100644
--- a/pandas/tests/series/methods/test_dropna.py
+++ b/pandas/tests/series/methods/test_dropna.py
@@ -1,7 +1,14 @@
import numpy as np
import pytest
-from pandas import DatetimeIndex, IntervalIndex, NaT, Period, Series, Timestamp
+from pandas import (
+ DatetimeIndex,
+ IntervalIndex,
+ NaT,
+ Period,
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_equals.py b/pandas/tests/series/methods/test_equals.py
index 85d74196e59b4..0b3689afac764 100644
--- a/pandas/tests/series/methods/test_equals.py
+++ b/pandas/tests/series/methods/test_equals.py
@@ -8,7 +8,11 @@
from pandas.core.dtypes.common import is_float
-from pandas import Index, MultiIndex, Series
+from pandas import (
+ Index,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py
index 7e33b766a1413..5b3a6c13af467 100644
--- a/pandas/tests/series/methods/test_fillna.py
+++ b/pandas/tests/series/methods/test_fillna.py
@@ -1,4 +1,8 @@
-from datetime import datetime, timedelta, timezone
+from datetime import (
+ datetime,
+ timedelta,
+ timezone,
+)
import numpy as np
import pytest
diff --git a/pandas/tests/series/methods/test_get_numeric_data.py b/pandas/tests/series/methods/test_get_numeric_data.py
index dc0becf46a24c..e386f4b5b1dec 100644
--- a/pandas/tests/series/methods/test_get_numeric_data.py
+++ b/pandas/tests/series/methods/test_get_numeric_data.py
@@ -1,4 +1,8 @@
-from pandas import Index, Series, date_range
+from pandas import (
+ Index,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_interpolate.py b/pandas/tests/series/methods/test_interpolate.py
index 8740a309eec13..cad5476d4861c 100644
--- a/pandas/tests/series/methods/test_interpolate.py
+++ b/pandas/tests/series/methods/test_interpolate.py
@@ -4,7 +4,13 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import Index, MultiIndex, Series, date_range, isna
+from pandas import (
+ Index,
+ MultiIndex,
+ Series,
+ date_range,
+ isna,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_is_monotonic.py b/pandas/tests/series/methods/test_is_monotonic.py
index b242b293cb59e..f02939374cc5b 100644
--- a/pandas/tests/series/methods/test_is_monotonic.py
+++ b/pandas/tests/series/methods/test_is_monotonic.py
@@ -1,6 +1,9 @@
import numpy as np
-from pandas import Series, date_range
+from pandas import (
+ Series,
+ date_range,
+)
class TestIsMonotonic:
diff --git a/pandas/tests/series/methods/test_isin.py b/pandas/tests/series/methods/test_isin.py
index 76a84aac786c8..320179c0a8b0a 100644
--- a/pandas/tests/series/methods/test_isin.py
+++ b/pandas/tests/series/methods/test_isin.py
@@ -2,7 +2,10 @@
import pytest
import pandas as pd
-from pandas import Series, date_range
+from pandas import (
+ Series,
+ date_range,
+)
import pandas._testing as tm
from pandas.core.arrays import PeriodArray
diff --git a/pandas/tests/series/methods/test_isna.py b/pandas/tests/series/methods/test_isna.py
index 1760b0b9726e0..7e324aa86a052 100644
--- a/pandas/tests/series/methods/test_isna.py
+++ b/pandas/tests/series/methods/test_isna.py
@@ -3,7 +3,10 @@
"""
import numpy as np
-from pandas import Period, Series
+from pandas import (
+ Period,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_item.py b/pandas/tests/series/methods/test_item.py
index 90e8f6d39c5cc..2bdeb4da5f70f 100644
--- a/pandas/tests/series/methods/test_item.py
+++ b/pandas/tests/series/methods/test_item.py
@@ -4,7 +4,12 @@
"""
import pytest
-from pandas import Series, Timedelta, Timestamp, date_range
+from pandas import (
+ Series,
+ Timedelta,
+ Timestamp,
+ date_range,
+)
class TestItem:
diff --git a/pandas/tests/series/methods/test_matmul.py b/pandas/tests/series/methods/test_matmul.py
index c311f1fd880a3..b944395bff29f 100644
--- a/pandas/tests/series/methods/test_matmul.py
+++ b/pandas/tests/series/methods/test_matmul.py
@@ -3,7 +3,10 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_nunique.py b/pandas/tests/series/methods/test_nunique.py
index d2d94183aa21b..50d3b9331b2b2 100644
--- a/pandas/tests/series/methods/test_nunique.py
+++ b/pandas/tests/series/methods/test_nunique.py
@@ -1,6 +1,9 @@
import numpy as np
-from pandas import Categorical, Series
+from pandas import (
+ Categorical,
+ Series,
+)
def test_nunique():
diff --git a/pandas/tests/series/methods/test_pct_change.py b/pandas/tests/series/methods/test_pct_change.py
index 1efb57894f986..017fef5fdb31f 100644
--- a/pandas/tests/series/methods/test_pct_change.py
+++ b/pandas/tests/series/methods/test_pct_change.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import Series, date_range
+from pandas import (
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_quantile.py b/pandas/tests/series/methods/test_quantile.py
index 5771d8e2b8a47..9001f95fe4299 100644
--- a/pandas/tests/series/methods/test_quantile.py
+++ b/pandas/tests/series/methods/test_quantile.py
@@ -6,7 +6,10 @@
from pandas.core.dtypes.common import is_integer
import pandas as pd
-from pandas import Index, Series
+from pandas import (
+ Index,
+ Series,
+)
import pandas._testing as tm
from pandas.core.indexes.datetimes import Timestamp
diff --git a/pandas/tests/series/methods/test_rank.py b/pandas/tests/series/methods/test_rank.py
index 9d052e2236aae..088e10b0ba070 100644
--- a/pandas/tests/series/methods/test_rank.py
+++ b/pandas/tests/series/methods/test_rank.py
@@ -1,12 +1,23 @@
-from itertools import chain, product
+from itertools import (
+ chain,
+ product,
+)
import numpy as np
import pytest
-from pandas._libs.algos import Infinity, NegInfinity
+from pandas._libs.algos import (
+ Infinity,
+ NegInfinity,
+)
import pandas.util._test_decorators as td
-from pandas import NaT, Series, Timestamp, date_range
+from pandas import (
+ NaT,
+ Series,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
from pandas.api.types import CategoricalDtype
diff --git a/pandas/tests/series/methods/test_rename.py b/pandas/tests/series/methods/test_rename.py
index ac07fed7c951a..eacafa9310384 100644
--- a/pandas/tests/series/methods/test_rename.py
+++ b/pandas/tests/series/methods/test_rename.py
@@ -2,7 +2,10 @@
import numpy as np
-from pandas import Index, Series
+from pandas import (
+ Index,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_rename_axis.py b/pandas/tests/series/methods/test_rename_axis.py
index b519dd1144493..58c095d697ede 100644
--- a/pandas/tests/series/methods/test_rename_axis.py
+++ b/pandas/tests/series/methods/test_rename_axis.py
@@ -1,6 +1,10 @@
import pytest
-from pandas import Index, MultiIndex, Series
+from pandas import (
+ Index,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_repeat.py b/pandas/tests/series/methods/test_repeat.py
index 32f7384d34ebd..e63317f685556 100644
--- a/pandas/tests/series/methods/test_repeat.py
+++ b/pandas/tests/series/methods/test_repeat.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import MultiIndex, Series
+from pandas import (
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_reset_index.py b/pandas/tests/series/methods/test_reset_index.py
index 40e567a8c33ca..70b9c9c9dc7d7 100644
--- a/pandas/tests/series/methods/test_reset_index.py
+++ b/pandas/tests/series/methods/test_reset_index.py
@@ -4,7 +4,14 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, RangeIndex, Series, date_range
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ RangeIndex,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_searchsorted.py b/pandas/tests/series/methods/test_searchsorted.py
index 5a6ec0039c7cd..5a7eb3f8cfc97 100644
--- a/pandas/tests/series/methods/test_searchsorted.py
+++ b/pandas/tests/series/methods/test_searchsorted.py
@@ -1,6 +1,10 @@
import numpy as np
-from pandas import Series, Timestamp, date_range
+from pandas import (
+ Series,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
from pandas.api.types import is_scalar
diff --git a/pandas/tests/series/methods/test_sort_index.py b/pandas/tests/series/methods/test_sort_index.py
index ccaa8a797e312..d70abe2311acd 100644
--- a/pandas/tests/series/methods/test_sort_index.py
+++ b/pandas/tests/series/methods/test_sort_index.py
@@ -3,7 +3,12 @@
import numpy as np
import pytest
-from pandas import DatetimeIndex, IntervalIndex, MultiIndex, Series
+from pandas import (
+ DatetimeIndex,
+ IntervalIndex,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_sort_values.py b/pandas/tests/series/methods/test_sort_values.py
index b49e39d4592ea..fe2046401f657 100644
--- a/pandas/tests/series/methods/test_sort_values.py
+++ b/pandas/tests/series/methods/test_sort_values.py
@@ -1,7 +1,11 @@
import numpy as np
import pytest
-from pandas import Categorical, DataFrame, Series
+from pandas import (
+ Categorical,
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_to_frame.py b/pandas/tests/series/methods/test_to_frame.py
index 6d52ab9da3f1b..66e44f1a0caf0 100644
--- a/pandas/tests/series/methods/test_to_frame.py
+++ b/pandas/tests/series/methods/test_to_frame.py
@@ -1,4 +1,7 @@
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_truncate.py b/pandas/tests/series/methods/test_truncate.py
index 21de593c0e2af..672faf1e0d541 100644
--- a/pandas/tests/series/methods/test_truncate.py
+++ b/pandas/tests/series/methods/test_truncate.py
@@ -1,7 +1,10 @@
from datetime import datetime
import pandas as pd
-from pandas import Series, date_range
+from pandas import (
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_tz_convert.py b/pandas/tests/series/methods/test_tz_convert.py
index 82ee5c8d756b1..d826dde646cfb 100644
--- a/pandas/tests/series/methods/test_tz_convert.py
+++ b/pandas/tests/series/methods/test_tz_convert.py
@@ -1,6 +1,9 @@
import numpy as np
-from pandas import DatetimeIndex, Series
+from pandas import (
+ DatetimeIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_tz_localize.py b/pandas/tests/series/methods/test_tz_localize.py
index 836dee3aa047d..4d7f26076e060 100644
--- a/pandas/tests/series/methods/test_tz_localize.py
+++ b/pandas/tests/series/methods/test_tz_localize.py
@@ -3,7 +3,13 @@
from pandas._libs.tslibs import timezones
-from pandas import DatetimeIndex, NaT, Series, Timestamp, date_range
+from pandas import (
+ DatetimeIndex,
+ NaT,
+ Series,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_unique.py b/pandas/tests/series/methods/test_unique.py
index b777d9ba1676a..856fe6e7c4f04 100644
--- a/pandas/tests/series/methods/test_unique.py
+++ b/pandas/tests/series/methods/test_unique.py
@@ -1,6 +1,9 @@
import numpy as np
-from pandas import Categorical, Series
+from pandas import (
+ Categorical,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_unstack.py b/pandas/tests/series/methods/test_unstack.py
index ded4500ba478a..6f8f6d638dd56 100644
--- a/pandas/tests/series/methods/test_unstack.py
+++ b/pandas/tests/series/methods/test_unstack.py
@@ -2,7 +2,11 @@
import pytest
import pandas as pd
-from pandas import DataFrame, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_update.py b/pandas/tests/series/methods/test_update.py
index 51760c451ebca..4f585a6ea029a 100644
--- a/pandas/tests/series/methods/test_update.py
+++ b/pandas/tests/series/methods/test_update.py
@@ -1,7 +1,13 @@
import numpy as np
import pytest
-from pandas import CategoricalDtype, DataFrame, NaT, Series, Timestamp
+from pandas import (
+ CategoricalDtype,
+ DataFrame,
+ NaT,
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_value_counts.py b/pandas/tests/series/methods/test_value_counts.py
index 505b879660ff1..e707c3f4023df 100644
--- a/pandas/tests/series/methods/test_value_counts.py
+++ b/pandas/tests/series/methods/test_value_counts.py
@@ -2,7 +2,11 @@
import pytest
import pandas as pd
-from pandas import Categorical, CategoricalIndex, Series
+from pandas import (
+ Categorical,
+ CategoricalIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_values.py b/pandas/tests/series/methods/test_values.py
index 2982dcd52991d..479c7033a3fb5 100644
--- a/pandas/tests/series/methods/test_values.py
+++ b/pandas/tests/series/methods/test_values.py
@@ -1,7 +1,11 @@
import numpy as np
import pytest
-from pandas import IntervalIndex, Series, period_range
+from pandas import (
+ IntervalIndex,
+ Series,
+ period_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/methods/test_view.py b/pandas/tests/series/methods/test_view.py
index ccf3aa0d90e6f..48f7b47f6d25a 100644
--- a/pandas/tests/series/methods/test_view.py
+++ b/pandas/tests/series/methods/test_view.py
@@ -1,4 +1,7 @@
-from pandas import Series, date_range
+from pandas import (
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py
index c09df52fb5df5..eddf57c1e88f3 100644
--- a/pandas/tests/series/test_api.py
+++ b/pandas/tests/series/test_api.py
@@ -7,7 +7,12 @@
from pandas.util._test_decorators import skip_if_no
import pandas as pd
-from pandas import DataFrame, Index, Series, date_range
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py
index 1593cbc987a12..0b6939a0997a4 100644
--- a/pandas/tests/series/test_arithmetic.py
+++ b/pandas/tests/series/test_arithmetic.py
@@ -7,7 +7,10 @@
from pandas._libs.tslibs import IncompatibleFrequency
-from pandas.core.dtypes.common import is_datetime64_dtype, is_datetime64tz_dtype
+from pandas.core.dtypes.common import (
+ is_datetime64_dtype,
+ is_datetime64tz_dtype,
+)
import pandas as pd
from pandas import (
@@ -21,7 +24,10 @@
isna,
)
import pandas._testing as tm
-from pandas.core import nanops, ops
+from pandas.core import (
+ nanops,
+ ops,
+)
def _permute(obj):
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index 780fd276cdceb..1daeee8645f2e 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -1,14 +1,23 @@
from collections import OrderedDict
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
from dateutil.tz import tzoffset
import numpy as np
import numpy.ma as ma
import pytest
-from pandas._libs import iNaT, lib
+from pandas._libs import (
+ iNaT,
+ lib,
+)
-from pandas.core.dtypes.common import is_categorical_dtype, is_datetime64tz_dtype
+from pandas.core.dtypes.common import (
+ is_categorical_dtype,
+ is_datetime64tz_dtype,
+)
from pandas.core.dtypes.dtypes import CategoricalDtype
import pandas as pd
@@ -31,7 +40,10 @@
timedelta_range,
)
import pandas._testing as tm
-from pandas.core.arrays import IntervalArray, period_array
+from pandas.core.arrays import (
+ IntervalArray,
+ period_array,
+)
from pandas.core.internals.blocks import NumericBlock
diff --git a/pandas/tests/series/test_dtypes.py b/pandas/tests/series/test_dtypes.py
index d455e434f38be..9121a5a5b6b82 100644
--- a/pandas/tests/series/test_dtypes.py
+++ b/pandas/tests/series/test_dtypes.py
@@ -4,7 +4,11 @@
from pandas.core.dtypes.dtypes import CategoricalDtype
import pandas as pd
-from pandas import Categorical, DataFrame, Series
+from pandas import (
+ Categorical,
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/test_logical_ops.py b/pandas/tests/series/test_logical_ops.py
index 23aa11bc9358a..87a86687fb9a0 100644
--- a/pandas/tests/series/test_logical_ops.py
+++ b/pandas/tests/series/test_logical_ops.py
@@ -4,7 +4,12 @@
import numpy as np
import pytest
-from pandas import DataFrame, Index, Series, bdate_range
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ bdate_range,
+)
import pandas._testing as tm
from pandas.core import ops
diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py
index 6fefeaa818a77..87a0e5cb680c8 100644
--- a/pandas/tests/series/test_missing.py
+++ b/pandas/tests/series/test_missing.py
@@ -5,7 +5,13 @@
from pandas._libs import iNaT
import pandas as pd
-from pandas import Categorical, Index, NaT, Series, isna
+from pandas import (
+ Categorical,
+ Index,
+ NaT,
+ Series,
+ isna,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/test_reductions.py b/pandas/tests/series/test_reductions.py
index c3c58f29fcbf6..12671bbf5ba98 100644
--- a/pandas/tests/series/test_reductions.py
+++ b/pandas/tests/series/test_reductions.py
@@ -2,7 +2,10 @@
import pytest
import pandas as pd
-from pandas import MultiIndex, Series
+from pandas import (
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/series/test_repr.py b/pandas/tests/series/test_repr.py
index 026f6bd2d453d..a91908f7fba52 100644
--- a/pandas/tests/series/test_repr.py
+++ b/pandas/tests/series/test_repr.py
@@ -1,4 +1,7 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import numpy as np
import pytest
diff --git a/pandas/tests/strings/test_api.py b/pandas/tests/strings/test_api.py
index 4e9ccbc4892e3..7f864a503486e 100644
--- a/pandas/tests/strings/test_api.py
+++ b/pandas/tests/strings/test_api.py
@@ -1,6 +1,12 @@
import pytest
-from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ _testing as tm,
+)
from pandas.core import strings as strings
diff --git a/pandas/tests/strings/test_case_justify.py b/pandas/tests/strings/test_case_justify.py
index 8aacf3d6d1d4b..b46f50e430b54 100644
--- a/pandas/tests/strings/test_case_justify.py
+++ b/pandas/tests/strings/test_case_justify.py
@@ -3,7 +3,10 @@
import numpy as np
import pytest
-from pandas import Series, _testing as tm
+from pandas import (
+ Series,
+ _testing as tm,
+)
def test_title():
diff --git a/pandas/tests/strings/test_cat.py b/pandas/tests/strings/test_cat.py
index 49091b1dd3858..cdaccf0dad8e6 100644
--- a/pandas/tests/strings/test_cat.py
+++ b/pandas/tests/strings/test_cat.py
@@ -2,7 +2,14 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm, concat
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ _testing as tm,
+ concat,
+)
from pandas.tests.strings.test_strings import assert_series_or_index_equal
diff --git a/pandas/tests/strings/test_extract.py b/pandas/tests/strings/test_extract.py
index f1d6049b1ac08..c1564a5c256a1 100644
--- a/pandas/tests/strings/test_extract.py
+++ b/pandas/tests/strings/test_extract.py
@@ -4,7 +4,13 @@
import numpy as np
import pytest
-from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ _testing as tm,
+)
def test_extract_expand_None():
diff --git a/pandas/tests/strings/test_find_replace.py b/pandas/tests/strings/test_find_replace.py
index 32ce89e64ef4b..ef27d582b4e0f 100644
--- a/pandas/tests/strings/test_find_replace.py
+++ b/pandas/tests/strings/test_find_replace.py
@@ -5,7 +5,11 @@
import pytest
import pandas as pd
-from pandas import Index, Series, _testing as tm
+from pandas import (
+ Index,
+ Series,
+ _testing as tm,
+)
def test_contains():
diff --git a/pandas/tests/strings/test_split_partition.py b/pandas/tests/strings/test_split_partition.py
index 3bea778587d82..6df8fa805955d 100644
--- a/pandas/tests/strings/test_split_partition.py
+++ b/pandas/tests/strings/test_split_partition.py
@@ -4,7 +4,13 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series, _testing as tm
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ _testing as tm,
+)
def test_split():
diff --git a/pandas/tests/strings/test_string_array.py b/pandas/tests/strings/test_string_array.py
index 4cf3c3d165e79..b51132caf7573 100644
--- a/pandas/tests/strings/test_string_array.py
+++ b/pandas/tests/strings/test_string_array.py
@@ -4,7 +4,11 @@
from pandas._libs import lib
import pandas as pd
-from pandas import DataFrame, Series, _testing as tm
+from pandas import (
+ DataFrame,
+ Series,
+ _testing as tm,
+)
def test_string_array(any_string_method):
diff --git a/pandas/tests/strings/test_strings.py b/pandas/tests/strings/test_strings.py
index 92e7bf258d2d7..95ac237597bc4 100644
--- a/pandas/tests/strings/test_strings.py
+++ b/pandas/tests/strings/test_strings.py
@@ -1,9 +1,19 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import numpy as np
import pytest
-from pandas import DataFrame, Index, MultiIndex, Series, isna, notna
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ isna,
+ notna,
+)
import pandas._testing as tm
diff --git a/pandas/tests/test_aggregation.py b/pandas/tests/test_aggregation.py
index 74ccebc8e2275..4534b8eaac03b 100644
--- a/pandas/tests/test_aggregation.py
+++ b/pandas/tests/test_aggregation.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas.core.aggregation import _make_unique_kwarg_list, maybe_mangle_lambdas
+from pandas.core.aggregation import (
+ _make_unique_kwarg_list,
+ maybe_mangle_lambdas,
+)
def test_maybe_mangle_lambdas_passthrough():
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index 88757b96085aa..27201055dfa5d 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -5,7 +5,10 @@
import numpy as np
import pytest
-from pandas._libs import algos as libalgos, hashtable as ht
+from pandas._libs import (
+ algos as libalgos,
+ hashtable as ht,
+)
from pandas.compat import np_array_datetime64_compat
import pandas.util._test_decorators as td
diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py
index 83016a08de90b..911f1c7ebe31c 100644
--- a/pandas/tests/test_downstream.py
+++ b/pandas/tests/test_downstream.py
@@ -89,7 +89,10 @@ def test_statsmodels():
def test_scikit_learn(df):
sklearn = import_module("sklearn") # noqa
- from sklearn import datasets, svm
+ from sklearn import (
+ datasets,
+ svm,
+ )
digits = datasets.load_digits()
clf = svm.SVC(gamma=0.001, C=100.0)
diff --git a/pandas/tests/test_expressions.py b/pandas/tests/test_expressions.py
index 2d862fda013d5..30f88ba5e76f6 100644
--- a/pandas/tests/test_expressions.py
+++ b/pandas/tests/test_expressions.py
@@ -5,7 +5,11 @@
import pytest
import pandas._testing as tm
-from pandas.core.api import DataFrame, Index, Series
+from pandas.core.api import (
+ DataFrame,
+ Index,
+ Series,
+)
from pandas.core.computation import expressions as expr
_frame = DataFrame(np.random.randn(10000, 4), columns=list("ABCD"), dtype="float64")
diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py
index 88fecc7635475..8e6a636a8f602 100644
--- a/pandas/tests/test_multilevel.py
+++ b/pandas/tests/test_multilevel.py
@@ -2,7 +2,11 @@
import pytest
import pandas as pd
-from pandas import DataFrame, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
AGG_FUNCTIONS = [
diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py
index 359a7eecf6f7b..7f8b941a9f115 100644
--- a/pandas/tests/test_nanops.py
+++ b/pandas/tests/test_nanops.py
@@ -10,7 +10,10 @@
from pandas.core.dtypes.common import is_integer_dtype
import pandas as pd
-from pandas import Series, isna
+from pandas import (
+ Series,
+ isna,
+)
import pandas._testing as tm
from pandas.core.arrays import DatetimeArray
import pandas.core.nanops as nanops
diff --git a/pandas/tests/test_optional_dependency.py b/pandas/tests/test_optional_dependency.py
index b9cab2428c0d1..f75ee0d0ddd95 100644
--- a/pandas/tests/test_optional_dependency.py
+++ b/pandas/tests/test_optional_dependency.py
@@ -3,7 +3,10 @@
import pytest
-from pandas.compat._optional import VERSIONS, import_optional_dependency
+from pandas.compat._optional import (
+ VERSIONS,
+ import_optional_dependency,
+)
import pandas._testing as tm
diff --git a/pandas/tests/test_sorting.py b/pandas/tests/test_sorting.py
index da1c91a1ad218..2fa3acf939c5b 100644
--- a/pandas/tests/test_sorting.py
+++ b/pandas/tests/test_sorting.py
@@ -5,7 +5,14 @@
import numpy as np
import pytest
-from pandas import DataFrame, MultiIndex, Series, array, concat, merge
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+ array,
+ concat,
+ merge,
+)
import pandas._testing as tm
from pandas.core.algorithms import safe_sort
import pandas.core.common as com
diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index 278a315a479bd..695aa4ca129d8 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -2,7 +2,10 @@
import calendar
from collections import deque
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import locale
from dateutil.parser import parse
@@ -12,7 +15,10 @@
import pytz
from pandas._libs import tslib
-from pandas._libs.tslibs import iNaT, parsing
+from pandas._libs.tslibs import (
+ iNaT,
+ parsing,
+)
from pandas.errors import OutOfBoundsDatetime
import pandas.util._test_decorators as td
diff --git a/pandas/tests/tools/test_to_numeric.py b/pandas/tests/tools/test_to_numeric.py
index d5b4bda35ca2b..15ee296be0908 100644
--- a/pandas/tests/tools/test_to_numeric.py
+++ b/pandas/tests/tools/test_to_numeric.py
@@ -5,7 +5,12 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, Series, to_numeric
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ to_numeric,
+)
import pandas._testing as tm
diff --git a/pandas/tests/tools/test_to_timedelta.py b/pandas/tests/tools/test_to_timedelta.py
index de3ff6e80ad66..6ff14087e6259 100644
--- a/pandas/tests/tools/test_to_timedelta.py
+++ b/pandas/tests/tools/test_to_timedelta.py
@@ -1,10 +1,18 @@
-from datetime import time, timedelta
+from datetime import (
+ time,
+ timedelta,
+)
import numpy as np
import pytest
import pandas as pd
-from pandas import Series, TimedeltaIndex, isna, to_timedelta
+from pandas import (
+ Series,
+ TimedeltaIndex,
+ isna,
+ to_timedelta,
+)
import pandas._testing as tm
diff --git a/pandas/tests/tseries/frequencies/test_freq_code.py b/pandas/tests/tseries/frequencies/test_freq_code.py
index 20cadde45e7a0..92795245103d0 100644
--- a/pandas/tests/tseries/frequencies/test_freq_code.py
+++ b/pandas/tests/tseries/frequencies/test_freq_code.py
@@ -1,6 +1,10 @@
import pytest
-from pandas._libs.tslibs import Period, Resolution, to_offset
+from pandas._libs.tslibs import (
+ Period,
+ Resolution,
+ to_offset,
+)
from pandas._libs.tslibs.dtypes import _attrname_to_abbrevs
diff --git a/pandas/tests/tseries/frequencies/test_frequencies.py b/pandas/tests/tseries/frequencies/test_frequencies.py
index 0479de8e8e7c3..f0af290b2fb69 100644
--- a/pandas/tests/tseries/frequencies/test_frequencies.py
+++ b/pandas/tests/tseries/frequencies/test_frequencies.py
@@ -2,7 +2,10 @@
from pandas._libs.tslibs import offsets
-from pandas.tseries.frequencies import is_subperiod, is_superperiod
+from pandas.tseries.frequencies import (
+ is_subperiod,
+ is_superperiod,
+)
@pytest.mark.parametrize(
diff --git a/pandas/tests/tseries/frequencies/test_inference.py b/pandas/tests/tseries/frequencies/test_inference.py
index 95edd038dab9b..a764ab8f03d9e 100644
--- a/pandas/tests/tseries/frequencies/test_inference.py
+++ b/pandas/tests/tseries/frequencies/test_inference.py
@@ -1,13 +1,26 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import numpy as np
import pytest
-from pandas._libs.tslibs.ccalendar import DAYS, MONTHS
+from pandas._libs.tslibs.ccalendar import (
+ DAYS,
+ MONTHS,
+)
from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG
from pandas.compat import is_platform_windows
-from pandas import DatetimeIndex, Index, Series, Timestamp, date_range, period_range
+from pandas import (
+ DatetimeIndex,
+ Index,
+ Series,
+ Timestamp,
+ date_range,
+ period_range,
+)
import pandas._testing as tm
from pandas.core.tools.datetimes import to_datetime
diff --git a/pandas/tests/tseries/holiday/test_calendar.py b/pandas/tests/tseries/holiday/test_calendar.py
index cd3b1aab33a2a..d9f54d9d80b2e 100644
--- a/pandas/tests/tseries/holiday/test_calendar.py
+++ b/pandas/tests/tseries/holiday/test_calendar.py
@@ -2,7 +2,11 @@
import pytest
-from pandas import DatetimeIndex, offsets, to_datetime
+from pandas import (
+ DatetimeIndex,
+ offsets,
+ to_datetime,
+)
import pandas._testing as tm
from pandas.tseries.holiday import (
diff --git a/pandas/tests/tseries/offsets/common.py b/pandas/tests/tseries/offsets/common.py
index 5edef896be537..db63785988977 100644
--- a/pandas/tests/tseries/offsets/common.py
+++ b/pandas/tests/tseries/offsets/common.py
@@ -2,12 +2,18 @@
Assertion helpers and base class for offsets tests
"""
from datetime import datetime
-from typing import Optional, Type
+from typing import (
+ Optional,
+ Type,
+)
from dateutil.tz.tz import tzlocal
import pytest
-from pandas._libs.tslibs import OutOfBoundsDatetime, Timestamp
+from pandas._libs.tslibs import (
+ OutOfBoundsDatetime,
+ Timestamp,
+)
from pandas._libs.tslibs.offsets import (
FY5253,
BusinessHour,
diff --git a/pandas/tests/tseries/offsets/test_business_day.py b/pandas/tests/tseries/offsets/test_business_day.py
index 9b3ded9844e24..26df051ef928f 100644
--- a/pandas/tests/tseries/offsets/test_business_day.py
+++ b/pandas/tests/tseries/offsets/test_business_day.py
@@ -1,15 +1,28 @@
"""
Tests for offsets.BDay
"""
-from datetime import date, datetime, timedelta
+from datetime import (
+ date,
+ datetime,
+ timedelta,
+)
import numpy as np
import pytest
-from pandas._libs.tslibs.offsets import ApplyTypeError, BDay, BMonthEnd, CDay
+from pandas._libs.tslibs.offsets import (
+ ApplyTypeError,
+ BDay,
+ BMonthEnd,
+ CDay,
+)
from pandas.compat import np_datetime64_compat
-from pandas import DatetimeIndex, _testing as tm, read_pickle
+from pandas import (
+ DatetimeIndex,
+ _testing as tm,
+ read_pickle,
+)
from pandas.tests.tseries.offsets.common import (
Base,
assert_is_on_offset,
diff --git a/pandas/tests/tseries/offsets/test_business_hour.py b/pandas/tests/tseries/offsets/test_business_hour.py
index 5f387b2edeb0b..72b939b79c321 100644
--- a/pandas/tests/tseries/offsets/test_business_hour.py
+++ b/pandas/tests/tseries/offsets/test_business_hour.py
@@ -1,15 +1,32 @@
"""
Tests for offsets.BusinessHour
"""
-from datetime import datetime, time as dt_time
+from datetime import (
+ datetime,
+ time as dt_time,
+)
import pytest
-from pandas._libs.tslibs import Timedelta, Timestamp
-from pandas._libs.tslibs.offsets import BDay, BusinessHour, Nano
-
-from pandas import DatetimeIndex, _testing as tm, date_range
-from pandas.tests.tseries.offsets.common import Base, assert_offset_equal
+from pandas._libs.tslibs import (
+ Timedelta,
+ Timestamp,
+)
+from pandas._libs.tslibs.offsets import (
+ BDay,
+ BusinessHour,
+ Nano,
+)
+
+from pandas import (
+ DatetimeIndex,
+ _testing as tm,
+ date_range,
+)
+from pandas.tests.tseries.offsets.common import (
+ Base,
+ assert_offset_equal,
+)
class TestBusinessHour(Base):
diff --git a/pandas/tests/tseries/offsets/test_custom_business_hour.py b/pandas/tests/tseries/offsets/test_custom_business_hour.py
index f05b286616572..07270008adbd2 100644
--- a/pandas/tests/tseries/offsets/test_custom_business_hour.py
+++ b/pandas/tests/tseries/offsets/test_custom_business_hour.py
@@ -7,10 +7,17 @@
import pytest
from pandas._libs.tslibs import Timestamp
-from pandas._libs.tslibs.offsets import BusinessHour, CustomBusinessHour, Nano
+from pandas._libs.tslibs.offsets import (
+ BusinessHour,
+ CustomBusinessHour,
+ Nano,
+)
import pandas._testing as tm
-from pandas.tests.tseries.offsets.common import Base, assert_offset_equal
+from pandas.tests.tseries.offsets.common import (
+ Base,
+ assert_offset_equal,
+)
class TestCustomBusinessHour(Base):
diff --git a/pandas/tests/tseries/offsets/test_fiscal.py b/pandas/tests/tseries/offsets/test_fiscal.py
index 14728314b8e20..1eee9e611e0f1 100644
--- a/pandas/tests/tseries/offsets/test_fiscal.py
+++ b/pandas/tests/tseries/offsets/test_fiscal.py
@@ -18,7 +18,10 @@
)
from pandas.tseries.frequencies import get_offset
-from pandas.tseries.offsets import FY5253, FY5253Quarter
+from pandas.tseries.offsets import (
+ FY5253,
+ FY5253Quarter,
+)
def makeFY5253LastOfMonthQuarter(*args, **kwds):
diff --git a/pandas/tests/tseries/offsets/test_month.py b/pandas/tests/tseries/offsets/test_month.py
index 578af79084e09..b9c0cfe75fe7e 100644
--- a/pandas/tests/tseries/offsets/test_month.py
+++ b/pandas/tests/tseries/offsets/test_month.py
@@ -1,7 +1,10 @@
"""
Tests for CBMonthEnd CBMonthBegin, SemiMonthEnd, and SemiMonthBegin in offsets
"""
-from datetime import date, datetime
+from datetime import (
+ date,
+ datetime,
+)
import numpy as np
import pytest
@@ -15,7 +18,12 @@
SemiMonthEnd,
)
-from pandas import DatetimeIndex, Series, _testing as tm, date_range
+from pandas import (
+ DatetimeIndex,
+ Series,
+ _testing as tm,
+ date_range,
+)
from pandas.tests.tseries.offsets.common import (
Base,
assert_is_on_offset,
diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py
index 8d718d055f02d..50bfc21637407 100644
--- a/pandas/tests/tseries/offsets/test_offsets.py
+++ b/pandas/tests/tseries/offsets/test_offsets.py
@@ -1,22 +1,41 @@
"""
Tests of pandas.tseries.offsets
"""
-from datetime import datetime, timedelta
-from typing import Dict, List, Tuple
+from datetime import (
+ datetime,
+ timedelta,
+)
+from typing import (
+ Dict,
+ List,
+ Tuple,
+)
import numpy as np
import pytest
-from pandas._libs.tslibs import NaT, Timestamp, conversion, timezones
+from pandas._libs.tslibs import (
+ NaT,
+ Timestamp,
+ conversion,
+ timezones,
+)
import pandas._libs.tslibs.offsets as liboffsets
-from pandas._libs.tslibs.offsets import _get_offset, _offset_map
+from pandas._libs.tslibs.offsets import (
+ _get_offset,
+ _offset_map,
+)
from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG
from pandas.compat import np_datetime64_compat
from pandas.errors import PerformanceWarning
from pandas import DatetimeIndex
import pandas._testing as tm
-from pandas.tests.tseries.offsets.common import Base, WeekDay, assert_offset_equal
+from pandas.tests.tseries.offsets.common import (
+ Base,
+ WeekDay,
+ assert_offset_equal,
+)
import pandas.tseries.offsets as offsets
from pandas.tseries.offsets import (
diff --git a/pandas/tests/tseries/offsets/test_offsets_properties.py b/pandas/tests/tseries/offsets/test_offsets_properties.py
index edb0f8c7dd662..8e0ace7775868 100644
--- a/pandas/tests/tseries/offsets/test_offsets_properties.py
+++ b/pandas/tests/tseries/offsets/test_offsets_properties.py
@@ -9,7 +9,11 @@
"""
import warnings
-from hypothesis import assume, given, strategies as st
+from hypothesis import (
+ assume,
+ given,
+ strategies as st,
+)
from hypothesis.errors import Flaky
from hypothesis.extra.dateutil import timezones as dateutil_timezones
from hypothesis.extra.pytz import timezones as pytz_timezones
diff --git a/pandas/tests/tseries/offsets/test_ticks.py b/pandas/tests/tseries/offsets/test_ticks.py
index 5f7f1b898877c..52a2f3aeee850 100644
--- a/pandas/tests/tseries/offsets/test_ticks.py
+++ b/pandas/tests/tseries/offsets/test_ticks.py
@@ -1,20 +1,39 @@
"""
Tests for offsets.Tick and subclasses
"""
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
-from hypothesis import assume, example, given, settings, strategies as st
+from hypothesis import (
+ assume,
+ example,
+ given,
+ settings,
+ strategies as st,
+)
import numpy as np
import pytest
from pandas._libs.tslibs.offsets import delta_to_tick
-from pandas import Timedelta, Timestamp
+from pandas import (
+ Timedelta,
+ Timestamp,
+)
import pandas._testing as tm
from pandas.tests.tseries.offsets.common import assert_offset_equal
from pandas.tseries import offsets
-from pandas.tseries.offsets import Hour, Micro, Milli, Minute, Nano, Second
+from pandas.tseries.offsets import (
+ Hour,
+ Micro,
+ Milli,
+ Minute,
+ Nano,
+ Second,
+)
# ---------------------------------------------------------------------
# Test Helpers
diff --git a/pandas/tests/tseries/offsets/test_week.py b/pandas/tests/tseries/offsets/test_week.py
index 54751a70b151d..b46a36e00f2da 100644
--- a/pandas/tests/tseries/offsets/test_week.py
+++ b/pandas/tests/tseries/offsets/test_week.py
@@ -1,12 +1,19 @@
"""
Tests for offset.Week, offset.WeekofMonth and offset.LastWeekofMonth
"""
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import pytest
from pandas._libs.tslibs import Timestamp
-from pandas._libs.tslibs.offsets import LastWeekOfMonth, Week, WeekOfMonth
+from pandas._libs.tslibs.offsets import (
+ LastWeekOfMonth,
+ Week,
+ WeekOfMonth,
+)
from pandas.tests.tseries.offsets.common import (
Base,
diff --git a/pandas/tests/tslibs/test_array_to_datetime.py b/pandas/tests/tslibs/test_array_to_datetime.py
index 24fdb3840bf52..8c2f0b09c461e 100644
--- a/pandas/tests/tslibs/test_array_to_datetime.py
+++ b/pandas/tests/tslibs/test_array_to_datetime.py
@@ -1,11 +1,17 @@
-from datetime import date, datetime
+from datetime import (
+ date,
+ datetime,
+)
from dateutil.tz.tz import tzoffset
import numpy as np
import pytest
import pytz
-from pandas._libs import iNaT, tslib
+from pandas._libs import (
+ iNaT,
+ tslib,
+)
from pandas.compat import np_array_datetime64_compat
from pandas import Timestamp
diff --git a/pandas/tests/tslibs/test_ccalendar.py b/pandas/tests/tslibs/test_ccalendar.py
index 1ff700fdc23a3..bba833abd3ad0 100644
--- a/pandas/tests/tslibs/test_ccalendar.py
+++ b/pandas/tests/tslibs/test_ccalendar.py
@@ -1,6 +1,12 @@
-from datetime import date, datetime
+from datetime import (
+ date,
+ datetime,
+)
-from hypothesis import given, strategies as st
+from hypothesis import (
+ given,
+ strategies as st,
+)
import numpy as np
import pytest
diff --git a/pandas/tests/tslibs/test_conversion.py b/pandas/tests/tslibs/test_conversion.py
index 87cd97f853f4d..41eb7ae85d032 100644
--- a/pandas/tests/tslibs/test_conversion.py
+++ b/pandas/tests/tslibs/test_conversion.py
@@ -12,7 +12,10 @@
tzconversion,
)
-from pandas import Timestamp, date_range
+from pandas import (
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/tslibs/test_liboffsets.py b/pandas/tests/tslibs/test_liboffsets.py
index 6a514d2cc8713..c189a431146a7 100644
--- a/pandas/tests/tslibs/test_liboffsets.py
+++ b/pandas/tests/tslibs/test_liboffsets.py
@@ -5,7 +5,10 @@
import pytest
-from pandas._libs.tslibs.ccalendar import get_firstbday, get_lastbday
+from pandas._libs.tslibs.ccalendar import (
+ get_firstbday,
+ get_lastbday,
+)
import pandas._libs.tslibs.offsets as liboffsets
from pandas._libs.tslibs.offsets import roll_qtrday
diff --git a/pandas/tests/tslibs/test_period_asfreq.py b/pandas/tests/tslibs/test_period_asfreq.py
index 63298b657e341..2592fdbb2d361 100644
--- a/pandas/tests/tslibs/test_period_asfreq.py
+++ b/pandas/tests/tslibs/test_period_asfreq.py
@@ -1,7 +1,10 @@
import pytest
from pandas._libs.tslibs import to_offset
-from pandas._libs.tslibs.period import period_asfreq, period_ordinal
+from pandas._libs.tslibs.period import (
+ period_asfreq,
+ period_ordinal,
+)
def get_freq_code(freqstr: str) -> int:
diff --git a/pandas/tests/tslibs/test_timedeltas.py b/pandas/tests/tslibs/test_timedeltas.py
index c87752ccf151e..25450bd64a298 100644
--- a/pandas/tests/tslibs/test_timedeltas.py
+++ b/pandas/tests/tslibs/test_timedeltas.py
@@ -3,7 +3,10 @@
from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds
-from pandas import Timedelta, offsets
+from pandas import (
+ Timedelta,
+ offsets,
+)
@pytest.mark.parametrize(
diff --git a/pandas/tests/tslibs/test_timezones.py b/pandas/tests/tslibs/test_timezones.py
index 33f83c3579c43..fbda5e8fda9dd 100644
--- a/pandas/tests/tslibs/test_timezones.py
+++ b/pandas/tests/tslibs/test_timezones.py
@@ -1,10 +1,17 @@
-from datetime import datetime, timedelta, timezone
+from datetime import (
+ datetime,
+ timedelta,
+ timezone,
+)
import dateutil.tz
import pytest
import pytz
-from pandas._libs.tslibs import conversion, timezones
+from pandas._libs.tslibs import (
+ conversion,
+ timezones,
+)
from pandas import Timestamp
diff --git a/pandas/tests/tslibs/test_to_offset.py b/pandas/tests/tslibs/test_to_offset.py
index 5b1134ee85e2c..27ddbb82f49a9 100644
--- a/pandas/tests/tslibs/test_to_offset.py
+++ b/pandas/tests/tslibs/test_to_offset.py
@@ -2,7 +2,11 @@
import pytest
-from pandas._libs.tslibs import Timedelta, offsets, to_offset
+from pandas._libs.tslibs import (
+ Timedelta,
+ offsets,
+ to_offset,
+)
@pytest.mark.parametrize(
diff --git a/pandas/tests/util/test_assert_almost_equal.py b/pandas/tests/util/test_assert_almost_equal.py
index ec8cb29c6dead..ab53707771be6 100644
--- a/pandas/tests/util/test_assert_almost_equal.py
+++ b/pandas/tests/util/test_assert_almost_equal.py
@@ -1,7 +1,12 @@
import numpy as np
import pytest
-from pandas import DataFrame, Index, Series, Timestamp
+from pandas import (
+ DataFrame,
+ Index,
+ Series,
+ Timestamp,
+)
import pandas._testing as tm
diff --git a/pandas/tests/util/test_assert_index_equal.py b/pandas/tests/util/test_assert_index_equal.py
index 42c6db3d0b684..82a3a223b442b 100644
--- a/pandas/tests/util/test_assert_index_equal.py
+++ b/pandas/tests/util/test_assert_index_equal.py
@@ -1,7 +1,12 @@
import numpy as np
import pytest
-from pandas import Categorical, Index, MultiIndex, NaT
+from pandas import (
+ Categorical,
+ Index,
+ MultiIndex,
+ NaT,
+)
import pandas._testing as tm
diff --git a/pandas/tests/util/test_assert_produces_warning.py b/pandas/tests/util/test_assert_produces_warning.py
index 296fa3b6cf537..45699fa1294d3 100644
--- a/pandas/tests/util/test_assert_produces_warning.py
+++ b/pandas/tests/util/test_assert_produces_warning.py
@@ -5,7 +5,10 @@
import pytest
-from pandas.errors import DtypeWarning, PerformanceWarning
+from pandas.errors import (
+ DtypeWarning,
+ PerformanceWarning,
+)
import pandas._testing as tm
diff --git a/pandas/tests/util/test_assert_series_equal.py b/pandas/tests/util/test_assert_series_equal.py
index df1853ffd26ae..e3384ce3caa06 100644
--- a/pandas/tests/util/test_assert_series_equal.py
+++ b/pandas/tests/util/test_assert_series_equal.py
@@ -1,7 +1,11 @@
import pytest
import pandas as pd
-from pandas import Categorical, DataFrame, Series
+from pandas import (
+ Categorical,
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/util/test_hashing.py b/pandas/tests/util/test_hashing.py
index 779d93eb14f24..94786292adb51 100644
--- a/pandas/tests/util/test_hashing.py
+++ b/pandas/tests/util/test_hashing.py
@@ -2,10 +2,18 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
from pandas.core.util.hashing import hash_tuples
-from pandas.util import hash_array, hash_pandas_object
+from pandas.util import (
+ hash_array,
+ hash_pandas_object,
+)
@pytest.fixture(
diff --git a/pandas/tests/util/test_validate_kwargs.py b/pandas/tests/util/test_validate_kwargs.py
index c357affb6203d..0e271ef42ca93 100644
--- a/pandas/tests/util/test_validate_kwargs.py
+++ b/pandas/tests/util/test_validate_kwargs.py
@@ -1,6 +1,9 @@
import pytest
-from pandas.util._validators import validate_bool_kwarg, validate_kwargs
+from pandas.util._validators import (
+ validate_bool_kwarg,
+ validate_kwargs,
+)
_fname = "func"
diff --git a/pandas/tests/window/conftest.py b/pandas/tests/window/conftest.py
index 7ac033244fae7..d394a4b2be548 100644
--- a/pandas/tests/window/conftest.py
+++ b/pandas/tests/window/conftest.py
@@ -1,11 +1,19 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import numpy as np
import pytest
import pandas.util._test_decorators as td
-from pandas import DataFrame, Series, bdate_range, notna
+from pandas import (
+ DataFrame,
+ Series,
+ bdate_range,
+ notna,
+)
@pytest.fixture(params=[True, False])
diff --git a/pandas/tests/window/moments/test_moments_consistency_ewm.py b/pandas/tests/window/moments/test_moments_consistency_ewm.py
index 57665b47dea7f..a36091ab8934e 100644
--- a/pandas/tests/window/moments/test_moments_consistency_ewm.py
+++ b/pandas/tests/window/moments/test_moments_consistency_ewm.py
@@ -1,7 +1,11 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series, concat
+from pandas import (
+ DataFrame,
+ Series,
+ concat,
+)
import pandas._testing as tm
diff --git a/pandas/tests/window/moments/test_moments_consistency_expanding.py b/pandas/tests/window/moments/test_moments_consistency_expanding.py
index 17f76bf824a5d..df3e79fb79eca 100644
--- a/pandas/tests/window/moments/test_moments_consistency_expanding.py
+++ b/pandas/tests/window/moments/test_moments_consistency_expanding.py
@@ -1,7 +1,14 @@
import numpy as np
import pytest
-from pandas import DataFrame, Index, MultiIndex, Series, isna, notna
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ isna,
+ notna,
+)
import pandas._testing as tm
diff --git a/pandas/tests/window/moments/test_moments_consistency_rolling.py b/pandas/tests/window/moments/test_moments_consistency_rolling.py
index 53e5354340dcc..28fd5633de02e 100644
--- a/pandas/tests/window/moments/test_moments_consistency_rolling.py
+++ b/pandas/tests/window/moments/test_moments_consistency_rolling.py
@@ -5,7 +5,13 @@
import pandas.util._test_decorators as td
-from pandas import DataFrame, DatetimeIndex, Index, MultiIndex, Series
+from pandas import (
+ DataFrame,
+ DatetimeIndex,
+ Index,
+ MultiIndex,
+ Series,
+)
import pandas._testing as tm
from pandas.core.window.common import flex_binary_moment
diff --git a/pandas/tests/window/moments/test_moments_ewm.py b/pandas/tests/window/moments/test_moments_ewm.py
index a365321101e81..a7b1d3fbca3fb 100644
--- a/pandas/tests/window/moments/test_moments_ewm.py
+++ b/pandas/tests/window/moments/test_moments_ewm.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
diff --git a/pandas/tests/window/moments/test_moments_rolling.py b/pandas/tests/window/moments/test_moments_rolling.py
index ac6dd0bad619a..b2e53a676b039 100644
--- a/pandas/tests/window/moments/test_moments_rolling.py
+++ b/pandas/tests/window/moments/test_moments_rolling.py
@@ -3,7 +3,11 @@
import pandas.util._test_decorators as td
-from pandas import DataFrame, Series, date_range
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/window/moments/test_moments_rolling_apply.py b/pandas/tests/window/moments/test_moments_rolling_apply.py
index e48d88b365d8d..d7ce1c92bcd83 100644
--- a/pandas/tests/window/moments/test_moments_rolling_apply.py
+++ b/pandas/tests/window/moments/test_moments_rolling_apply.py
@@ -3,7 +3,13 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series, concat, isna, notna
+from pandas import (
+ DataFrame,
+ Series,
+ concat,
+ isna,
+ notna,
+)
import pandas._testing as tm
import pandas.tseries.offsets as offsets
diff --git a/pandas/tests/window/moments/test_moments_rolling_functions.py b/pandas/tests/window/moments/test_moments_rolling_functions.py
index abe75c7289ed4..b25b3c3b17637 100644
--- a/pandas/tests/window/moments/test_moments_rolling_functions.py
+++ b/pandas/tests/window/moments/test_moments_rolling_functions.py
@@ -1,7 +1,13 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series, concat, isna, notna
+from pandas import (
+ DataFrame,
+ Series,
+ concat,
+ isna,
+ notna,
+)
import pandas._testing as tm
import pandas.tseries.offsets as offsets
diff --git a/pandas/tests/window/moments/test_moments_rolling_quantile.py b/pandas/tests/window/moments/test_moments_rolling_quantile.py
index e06a5faabe310..56681c2aaa57e 100644
--- a/pandas/tests/window/moments/test_moments_rolling_quantile.py
+++ b/pandas/tests/window/moments/test_moments_rolling_quantile.py
@@ -3,7 +3,13 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series, concat, isna, notna
+from pandas import (
+ DataFrame,
+ Series,
+ concat,
+ isna,
+ notna,
+)
import pandas._testing as tm
import pandas.tseries.offsets as offsets
diff --git a/pandas/tests/window/moments/test_moments_rolling_skew_kurt.py b/pandas/tests/window/moments/test_moments_rolling_skew_kurt.py
index cc67e602be12e..3cd4b115c90c7 100644
--- a/pandas/tests/window/moments/test_moments_rolling_skew_kurt.py
+++ b/pandas/tests/window/moments/test_moments_rolling_skew_kurt.py
@@ -5,7 +5,13 @@
import pandas.util._test_decorators as td
-from pandas import DataFrame, Series, concat, isna, notna
+from pandas import (
+ DataFrame,
+ Series,
+ concat,
+ isna,
+ notna,
+)
import pandas._testing as tm
import pandas.tseries.offsets as offsets
diff --git a/pandas/tests/window/test_apply.py b/pandas/tests/window/test_apply.py
index b47cd71beb6a8..baab562b4d177 100644
--- a/pandas/tests/window/test_apply.py
+++ b/pandas/tests/window/test_apply.py
@@ -1,7 +1,14 @@
import numpy as np
import pytest
-from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, date_range
+from pandas import (
+ DataFrame,
+ Index,
+ MultiIndex,
+ Series,
+ Timestamp,
+ date_range,
+)
import pandas._testing as tm
diff --git a/pandas/tests/window/test_base_indexer.py b/pandas/tests/window/test_base_indexer.py
index fd4dfa7b7ed2b..06867e80ee711 100644
--- a/pandas/tests/window/test_base_indexer.py
+++ b/pandas/tests/window/test_base_indexer.py
@@ -1,10 +1,20 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series, date_range
+from pandas import (
+ DataFrame,
+ Series,
+ date_range,
+)
import pandas._testing as tm
-from pandas.api.indexers import BaseIndexer, FixedForwardWindowIndexer
-from pandas.core.window.indexers import ExpandingIndexer, VariableOffsetWindowIndexer
+from pandas.api.indexers import (
+ BaseIndexer,
+ FixedForwardWindowIndexer,
+)
+from pandas.core.window.indexers import (
+ ExpandingIndexer,
+ VariableOffsetWindowIndexer,
+)
from pandas.tseries.offsets import BusinessDay
diff --git a/pandas/tests/window/test_dtypes.py b/pandas/tests/window/test_dtypes.py
index fc7a51834780f..7cd2bf4f1ca19 100644
--- a/pandas/tests/window/test_dtypes.py
+++ b/pandas/tests/window/test_dtypes.py
@@ -1,7 +1,10 @@
import numpy as np
import pytest
-from pandas import DataFrame, Series
+from pandas import (
+ DataFrame,
+ Series,
+)
import pandas._testing as tm
from pandas.core.base import DataError
diff --git a/pandas/tests/window/test_ewm.py b/pandas/tests/window/test_ewm.py
index 9c1d23fe6e7a6..fbd7a36a75bf0 100644
--- a/pandas/tests/window/test_ewm.py
+++ b/pandas/tests/window/test_ewm.py
@@ -3,7 +3,12 @@
from pandas.errors import UnsupportedFunctionCall
-from pandas import DataFrame, DatetimeIndex, Series, date_range
+from pandas import (
+ DataFrame,
+ DatetimeIndex,
+ Series,
+ date_range,
+)
import pandas._testing as tm
from pandas.core.window import ExponentialMovingWindow
diff --git a/pandas/tests/window/test_expanding.py b/pandas/tests/window/test_expanding.py
index 01804faad5a5e..c272544e6af9e 100644
--- a/pandas/tests/window/test_expanding.py
+++ b/pandas/tests/window/test_expanding.py
@@ -3,7 +3,11 @@
from pandas.errors import UnsupportedFunctionCall
-from pandas import DataFrame, DatetimeIndex, Series
+from pandas import (
+ DataFrame,
+ DatetimeIndex,
+ Series,
+)
import pandas._testing as tm
from pandas.core.window import Expanding
diff --git a/pandas/tests/window/test_numba.py b/pandas/tests/window/test_numba.py
index 173e39ef42908..f64d242a4e820 100644
--- a/pandas/tests/window/test_numba.py
+++ b/pandas/tests/window/test_numba.py
@@ -4,7 +4,11 @@
from pandas.errors import NumbaUtilError
import pandas.util._test_decorators as td
-from pandas import DataFrame, Series, option_context
+from pandas import (
+ DataFrame,
+ Series,
+ option_context,
+)
import pandas._testing as tm
from pandas.core.util.numba_ import NUMBA_FUNC_CACHE
diff --git a/pandas/tests/window/test_pairwise.py b/pandas/tests/window/test_pairwise.py
index b39d052a702c0..a0d24a061fc4a 100644
--- a/pandas/tests/window/test_pairwise.py
+++ b/pandas/tests/window/test_pairwise.py
@@ -3,7 +3,12 @@
import numpy as np
import pytest
-from pandas import DataFrame, MultiIndex, Series, date_range
+from pandas import (
+ DataFrame,
+ MultiIndex,
+ Series,
+ date_range,
+)
import pandas._testing as tm
from pandas.core.algorithms import safe_sort
diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py
index b275b64ff706b..4989e23ed7ba5 100644
--- a/pandas/tests/window/test_rolling.py
+++ b/pandas/tests/window/test_rolling.py
@@ -1,4 +1,7 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
import numpy as np
import pytest
diff --git a/pandas/tests/window/test_win_type.py b/pandas/tests/window/test_win_type.py
index 1cfba6f020018..a1f388b1eb5d9 100644
--- a/pandas/tests/window/test_win_type.py
+++ b/pandas/tests/window/test_win_type.py
@@ -4,7 +4,13 @@
from pandas.errors import UnsupportedFunctionCall
import pandas.util._test_decorators as td
-from pandas import DataFrame, Series, Timedelta, concat, date_range
+from pandas import (
+ DataFrame,
+ Series,
+ Timedelta,
+ concat,
+ date_range,
+)
import pandas._testing as tm
from pandas.api.indexers import BaseIndexer
diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py
index 0d5598fcaf890..b2e2ccfada2c3 100644
--- a/pandas/tseries/frequencies.py
+++ b/pandas/tseries/frequencies.py
@@ -4,7 +4,10 @@
import numpy as np
from pandas._libs.algos import unique_deltas
-from pandas._libs.tslibs import Timestamp, tzconversion
+from pandas._libs.tslibs import (
+ Timestamp,
+ tzconversion,
+)
from pandas._libs.tslibs.ccalendar import (
DAYS,
MONTH_ALIASES,
@@ -12,7 +15,10 @@
MONTHS,
int_to_weekday,
)
-from pandas._libs.tslibs.fields import build_field_sarray, month_position_check
+from pandas._libs.tslibs.fields import (
+ build_field_sarray,
+ month_position_check,
+)
from pandas._libs.tslibs.offsets import ( # noqa:F401
DateOffset,
Day,
diff --git a/pandas/tseries/holiday.py b/pandas/tseries/holiday.py
index d8a3040919e7b..ce303928dc8ee 100644
--- a/pandas/tseries/holiday.py
+++ b/pandas/tseries/holiday.py
@@ -1,15 +1,36 @@
-from datetime import datetime, timedelta
+from datetime import (
+ datetime,
+ timedelta,
+)
from typing import List
import warnings
-from dateutil.relativedelta import FR, MO, SA, SU, TH, TU, WE # noqa
+from dateutil.relativedelta import ( # noqa
+ FR,
+ MO,
+ SA,
+ SU,
+ TH,
+ TU,
+ WE,
+)
import numpy as np
from pandas.errors import PerformanceWarning
-from pandas import DateOffset, DatetimeIndex, Series, Timestamp, concat, date_range
+from pandas import (
+ DateOffset,
+ DatetimeIndex,
+ Series,
+ Timestamp,
+ concat,
+ date_range,
+)
-from pandas.tseries.offsets import Day, Easter
+from pandas.tseries.offsets import (
+ Day,
+ Easter,
+)
def next_monday(dt: datetime) -> datetime:
diff --git a/pandas/util/__init__.py b/pandas/util/__init__.py
index 9f2bf156b7e37..35a88a802003e 100644
--- a/pandas/util/__init__.py
+++ b/pandas/util/__init__.py
@@ -1,6 +1,13 @@
-from pandas.util._decorators import Appender, Substitution, cache_readonly # noqa
+from pandas.util._decorators import ( # noqa
+ Appender,
+ Substitution,
+ cache_readonly,
+)
-from pandas.core.util.hashing import hash_array, hash_pandas_object # noqa
+from pandas.core.util.hashing import ( # noqa
+ hash_array,
+ hash_pandas_object,
+)
def __getattr__(name):
diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py
index 268c636ab9353..ffc0255ca9de7 100644
--- a/pandas/util/_decorators.py
+++ b/pandas/util/_decorators.py
@@ -1,7 +1,17 @@
from functools import wraps
import inspect
from textwrap import dedent
-from typing import Any, Callable, List, Mapping, Optional, Tuple, Type, Union, cast
+from typing import (
+ Any,
+ Callable,
+ List,
+ Mapping,
+ Optional,
+ Tuple,
+ Type,
+ Union,
+ cast,
+)
import warnings
from pandas._libs.properties import cache_readonly # noqa
diff --git a/pandas/util/_doctools.py b/pandas/util/_doctools.py
index 256346d482248..d6689fcb8cd01 100644
--- a/pandas/util/_doctools.py
+++ b/pandas/util/_doctools.py
@@ -1,4 +1,7 @@
-from typing import Optional, Tuple
+from typing import (
+ Optional,
+ Tuple,
+)
import numpy as np
diff --git a/pandas/util/_print_versions.py b/pandas/util/_print_versions.py
index ae3c8c98f8dc1..b81ec70c34396 100644
--- a/pandas/util/_print_versions.py
+++ b/pandas/util/_print_versions.py
@@ -5,10 +5,18 @@
import platform
import struct
import sys
-from typing import Dict, Optional, Union
+from typing import (
+ Dict,
+ Optional,
+ Union,
+)
from pandas._typing import JSONSerializable
-from pandas.compat._optional import VERSIONS, get_version, import_optional_dependency
+from pandas.compat._optional import (
+ VERSIONS,
+ get_version,
+ import_optional_dependency,
+)
def _get_commit_hash() -> Optional[str]:
diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py
index 95ef2f6c00fe8..fd8f62331dc38 100644
--- a/pandas/util/_test_decorators.py
+++ b/pandas/util/_test_decorators.py
@@ -26,16 +26,25 @@ def test_foo():
from contextlib import contextmanager
from distutils.version import LooseVersion
import locale
-from typing import Callable, Optional
+from typing import (
+ Callable,
+ Optional,
+)
import warnings
import numpy as np
import pytest
-from pandas.compat import IS64, is_platform_windows
+from pandas.compat import (
+ IS64,
+ is_platform_windows,
+)
from pandas.compat._optional import import_optional_dependency
-from pandas.core.computation.expressions import NUMEXPR_INSTALLED, USE_NUMEXPR
+from pandas.core.computation.expressions import (
+ NUMEXPR_INSTALLED,
+ USE_NUMEXPR,
+)
def safe_import(mod_name: str, min_version: Optional[str] = None):
diff --git a/pandas/util/_validators.py b/pandas/util/_validators.py
index fa7201a5188a5..60a81ed63b005 100644
--- a/pandas/util/_validators.py
+++ b/pandas/util/_validators.py
@@ -2,7 +2,10 @@
Module that contains many useful utilities
for validating data or function arguments
"""
-from typing import Iterable, Union
+from typing import (
+ Iterable,
+ Union,
+)
import warnings
import numpy as np
diff --git a/scripts/check_for_inconsistent_pandas_namespace.py b/scripts/check_for_inconsistent_pandas_namespace.py
index b213d931e7f07..11cdba6e821d2 100644
--- a/scripts/check_for_inconsistent_pandas_namespace.py
+++ b/scripts/check_for_inconsistent_pandas_namespace.py
@@ -12,7 +12,10 @@
import argparse
from pathlib import Path
import re
-from typing import Optional, Sequence
+from typing import (
+ Optional,
+ Sequence,
+)
PATTERN = r"""
(
diff --git a/scripts/validate_docstrings.py b/scripts/validate_docstrings.py
index 8b15358834066..c6b998e3dbddf 100755
--- a/scripts/validate_docstrings.py
+++ b/scripts/validate_docstrings.py
@@ -21,7 +21,10 @@
import os
import sys
import tempfile
-from typing import List, Optional
+from typing import (
+ List,
+ Optional,
+)
import flake8.main.application
diff --git a/scripts/validate_rst_title_capitalization.py b/scripts/validate_rst_title_capitalization.py
index f991b16fea192..aa17afc4c33ea 100755
--- a/scripts/validate_rst_title_capitalization.py
+++ b/scripts/validate_rst_title_capitalization.py
@@ -14,7 +14,11 @@
import argparse
import re
import sys
-from typing import Iterable, List, Tuple
+from typing import (
+ Iterable,
+ List,
+ Tuple,
+)
CAPITALIZATION_EXCEPTIONS = {
"pandas",
diff --git a/scripts/validate_unwanted_patterns.py b/scripts/validate_unwanted_patterns.py
index 8f48d518a737b..b6b038ae9dd17 100755
--- a/scripts/validate_unwanted_patterns.py
+++ b/scripts/validate_unwanted_patterns.py
@@ -15,7 +15,14 @@
import sys
import token
import tokenize
-from typing import IO, Callable, Iterable, List, Set, Tuple
+from typing import (
+ IO,
+ Callable,
+ Iterable,
+ List,
+ Set,
+ Tuple,
+)
PRIVATE_IMPORTS_TO_IGNORE: Set[str] = {
"_extension_array_shared_docs",
diff --git a/setup.cfg b/setup.cfg
index 5093ff81ad17f..ce055f550a868 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -169,6 +169,7 @@ sections = FUTURE,STDLIB,THIRDPARTY,PRE_LIBS,PRE_CORE,DTYPES,FIRSTPARTY,POST_COR
profile = black
combine_as_imports = True
line_length = 88
+force_grid_wrap = True
force_sort_within_sections = True
skip_glob = env,
skip = pandas/__init__.py
diff --git a/setup.py b/setup.py
index 34c80925a80a8..45548fed68322 100755
--- a/setup.py
+++ b/setup.py
@@ -18,7 +18,11 @@
import sys
import numpy
-from setuptools import Command, Extension, setup
+from setuptools import (
+ Command,
+ Extension,
+ setup,
+)
from setuptools.command.build_ext import build_ext as _build_ext
import versioneer
@@ -37,7 +41,10 @@ def is_platform_mac():
min_cython_ver = "0.29.21" # note: sync with pyproject.toml
try:
- from Cython import Tempita, __version__ as _CYTHON_VERSION
+ from Cython import (
+ Tempita,
+ __version__ as _CYTHON_VERSION,
+ )
from Cython.Build import cythonize
_CYTHON_INSTALLED = _CYTHON_VERSION >= LooseVersion(min_cython_ver)
| - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
As discussed in the monthly dev meeting - motivation here is to reduce the number of merge conflicts, which single-line imports seem to be a major source of.
some examples of such conflicts (which `force_grid_wrap` would avoid):
#37467 :
```python
<<<<<<< GH37278
from typing import TYPE_CHECKING, Optional
=======
from __future__ import annotations
from typing import TYPE_CHECKING
>>>>>>> master
```
#34426 :
```python
<<<<<<< 8745-from_dummies
from typing import TYPE_CHECKING, Any, Dict, Hashable, List, Optional, Type, Union, cast
=======
from typing import (
TYPE_CHECKING,
Dict,
Hashable,
List,
Optional,
Sequence,
Type,
TypeVar,
Union,
cast,
)
>>>>>>> master
```
#29944 :
```python
<<<<<<< subplot_groups
from collections import Counter, Iterable
from typing import TYPE_CHECKING, Hashable, List, Optional, Sequence, Tuple, Union
=======
from __future__ import annotations
from typing import TYPE_CHECKING, Hashable, List, Optional, Tuple
>>>>>>> master
```
----
This changes a huge number of files in one go, but all I've done is
```
git reset --hard upstream/master
# add `force_grid_wrap` option to setup.cfg
pre-commit run isort -a
git commit -m 'force grid-wrap' -a
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/39780 | 2021-02-12T18:42:19Z | 2021-02-16T15:41:51Z | 2021-02-16T15:41:51Z | 2021-02-16T15:43:26Z |
STYLE, CI move validate_rst_title_capitalization check to pre-commit | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index e0df3434b2906..3a371c8249eba 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -180,6 +180,12 @@ repos:
language: pygrep
types: [python]
files: ^pandas/tests/
+ - id: title-capitalization
+ name: Validate correct capitalization among titles in documentation
+ entry: python scripts/validate_rst_title_capitalization.py
+ language: python
+ types: [rst]
+ files: ^doc/source/(development|reference)/
- repo: https://github.com/asottile/yesqa
rev: v1.2.2
hooks:
diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index 597aced96eb18..251f450840ea9 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -233,10 +233,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then
$BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=GL03,GL04,GL05,GL06,GL07,GL09,GL10,SS02,SS04,SS05,PR03,PR04,PR05,PR10,EX04,RT01,RT04,RT05,SA02,SA03
RET=$(($RET + $?)) ; echo $MSG "DONE"
- MSG='Validate correct capitalization among titles in documentation' ; echo $MSG
- $BASE_DIR/scripts/validate_rst_title_capitalization.py $BASE_DIR/doc/source/development $BASE_DIR/doc/source/reference
- RET=$(($RET + $?)) ; echo $MSG "DONE"
-
fi
### TYPING ###
diff --git a/scripts/validate_rst_title_capitalization.py b/scripts/validate_rst_title_capitalization.py
index d521f2ee421be..f991b16fea192 100755
--- a/scripts/validate_rst_title_capitalization.py
+++ b/scripts/validate_rst_title_capitalization.py
@@ -1,17 +1,17 @@
-#!/usr/bin/env python3
"""
Validate that the titles in the rst files follow the proper capitalization convention.
Print the titles that do not follow the convention.
Usage::
-./scripts/validate_rst_title_capitalization.py doc/source/development/contributing.rst
-./scripts/validate_rst_title_capitalization.py doc/source/
+As pre-commit hook (recommended):
+ pre-commit run title-capitalization --all-files
+
+From the command-line:
+ python scripts/validate_rst_title_capitalization.py <rst file>
"""
import argparse
-import glob
-import os
import re
import sys
from typing import Iterable, List, Tuple
@@ -233,36 +233,7 @@ def find_titles(rst_file: str) -> Iterable[Tuple[str, int]]:
previous_line = line
-def find_rst_files(source_paths: List[str]) -> Iterable[str]:
- """
- Given the command line arguments of directory paths, this method
- yields the strings of the .rst file directories that these paths contain.
-
- Parameters
- ----------
- source_paths : str
- List of directories to validate, provided through command line arguments.
-
- Yields
- -------
- str
- Directory address of a .rst files found in command line argument directories.
- """
-
- for directory_address in source_paths:
- if not os.path.exists(directory_address):
- raise ValueError(
- "Please enter a valid path, pointing to a valid file/directory."
- )
- elif directory_address.endswith(".rst"):
- yield directory_address
- else:
- yield from glob.glob(
- pathname=f"{directory_address}/**/*.rst", recursive=True
- )
-
-
-def main(source_paths: List[str], output_format: str) -> int:
+def main(source_paths: List[str]) -> int:
"""
The main method to print all headings with incorrect capitalization.
@@ -270,8 +241,6 @@ def main(source_paths: List[str], output_format: str) -> int:
----------
source_paths : str
List of directories to validate, provided through command line arguments.
- output_format : str
- Output format of the script.
Returns
-------
@@ -281,7 +250,7 @@ def main(source_paths: List[str], output_format: str) -> int:
number_of_errors: int = 0
- for filename in find_rst_files(source_paths):
+ for filename in source_paths:
for title, line_number in find_titles(filename):
if title != correct_title_capitalization(title):
print(
@@ -297,16 +266,9 @@ def main(source_paths: List[str], output_format: str) -> int:
parser = argparse.ArgumentParser(description="Validate heading capitalization")
parser.add_argument(
- "paths", nargs="+", default=".", help="Source paths of file/directory to check."
- )
-
- parser.add_argument(
- "--format",
- "-f",
- default="{source_path}:{line_number}:{msg}:{heading}:{correct_heading}",
- help="Output format of incorrectly capitalized titles",
+ "paths", nargs="*", help="Source paths of file/directory to check."
)
args = parser.parse_args()
- sys.exit(main(args.paths, args.format))
+ sys.exit(main(args.paths))
| - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
xref #39624 in which it took ~15 minutes for @rhshadrach to be told
```
Heading capitalization formatted incorrectly. Please correctly capitalize "pytest.xfail" to "Pytest.xfail"
```
, like this such feedback will be provided much faster | https://api.github.com/repos/pandas-dev/pandas/pulls/39779 | 2021-02-12T17:48:32Z | 2021-02-15T22:31:47Z | 2021-02-15T22:31:46Z | 2021-02-16T09:55:16Z |
REF: de-duplicate dt64/td64 putmask/setitem shims | diff --git a/pandas/core/array_algos/putmask.py b/pandas/core/array_algos/putmask.py
index ca83692ad7ca4..917aace233ee5 100644
--- a/pandas/core/array_algos/putmask.py
+++ b/pandas/core/array_algos/putmask.py
@@ -1,7 +1,7 @@
"""
EA-compatible analogue to to np.putmask
"""
-from typing import Any
+from typing import Any, Tuple
import warnings
import numpy as np
@@ -9,10 +9,16 @@
from pandas._libs import lib
from pandas._typing import ArrayLike
-from pandas.core.dtypes.cast import convert_scalar_for_putitemlike, find_common_type
+from pandas.core.dtypes.cast import (
+ convert_scalar_for_putitemlike,
+ find_common_type,
+ infer_dtype_from,
+)
from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype, is_list_like
from pandas.core.dtypes.missing import isna_compat
+from pandas.core.arrays import ExtensionArray
+
def putmask_inplace(values: ArrayLike, mask: np.ndarray, value: Any) -> None:
"""
@@ -22,7 +28,7 @@ def putmask_inplace(values: ArrayLike, mask: np.ndarray, value: Any) -> None:
Parameters
----------
mask : np.ndarray[bool]
- We assume _extract_bool_array has already been called.
+ We assume extract_bool_array has already been called.
value : Any
"""
@@ -152,3 +158,52 @@ def putmask_without_repeat(values: np.ndarray, mask: np.ndarray, new: Any) -> No
raise ValueError("cannot assign mismatch length to masked array")
else:
np.putmask(values, mask, new)
+
+
+def validate_putmask(values: ArrayLike, mask: np.ndarray) -> Tuple[np.ndarray, bool]:
+ """
+ Validate mask and check if this putmask operation is a no-op.
+ """
+ mask = extract_bool_array(mask)
+ if mask.shape != values.shape:
+ raise ValueError("putmask: mask and data must be the same size")
+
+ noop = not mask.any()
+ return mask, noop
+
+
+def extract_bool_array(mask: ArrayLike) -> np.ndarray:
+ """
+ If we have a SparseArray or BooleanArray, convert it to ndarray[bool].
+ """
+ if isinstance(mask, ExtensionArray):
+ # We could have BooleanArray, Sparse[bool], ...
+ # Except for BooleanArray, this is equivalent to just
+ # np.asarray(mask, dtype=bool)
+ mask = mask.to_numpy(dtype=bool, na_value=False)
+
+ mask = np.asarray(mask, dtype=bool)
+ return mask
+
+
+def setitem_datetimelike_compat(values: np.ndarray, num_set: int, other):
+ """
+ Parameters
+ ----------
+ values : np.ndarray
+ num_set : int
+ For putmask, this is mask.sum()
+ other : Any
+ """
+ if values.dtype == object:
+ dtype, _ = infer_dtype_from(other, pandas_dtype=True)
+
+ if isinstance(dtype, np.dtype) and dtype.kind in ["m", "M"]:
+ # https://github.com/numpy/numpy/issues/12550
+ # timedelta64 will incorrectly cast to int
+ if not is_list_like(other):
+ other = [other] * num_set
+ else:
+ other = list(other)
+
+ return other
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 23bb9947686f4..789ca04b894cd 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -93,6 +93,10 @@
from pandas.core import missing, ops
from pandas.core.accessor import CachedAccessor
import pandas.core.algorithms as algos
+from pandas.core.array_algos.putmask import (
+ setitem_datetimelike_compat,
+ validate_putmask,
+)
from pandas.core.arrays import Categorical, ExtensionArray
from pandas.core.arrays.datetimes import tz_to_dtype, validate_tz_from_dtype
from pandas.core.arrays.sparse import SparseDtype
@@ -4274,6 +4278,7 @@ def memory_usage(self, deep: bool = False) -> int:
result += self._engine.sizeof(deep=deep)
return result
+ @final
def where(self, cond, other=None):
"""
Replace values where the condition is False.
@@ -4306,6 +4311,10 @@ def where(self, cond, other=None):
>>> idx.where(idx.isin(['car', 'train']), 'other')
Index(['car', 'other', 'train', 'other'], dtype='object')
"""
+ if isinstance(self, ABCMultiIndex):
+ raise NotImplementedError(
+ ".where is not supported for MultiIndex operations"
+ )
cond = np.asarray(cond, dtype=bool)
return self.putmask(~cond, other)
@@ -4522,10 +4531,8 @@ def putmask(self, mask, value):
numpy.ndarray.putmask : Changes elements of an array
based on conditional and input values.
"""
- mask = np.asarray(mask, dtype=bool)
- if mask.shape != self.shape:
- raise ValueError("putmask: mask and data must be the same size")
- if not mask.any():
+ mask, noop = validate_putmask(self._values, mask)
+ if noop:
return self.copy()
if value is None and (self._is_numeric_dtype or self.dtype == object):
@@ -4540,18 +4547,8 @@ def putmask(self, mask, value):
return self.astype(dtype).putmask(mask, value)
values = self._values.copy()
- dtype, _ = infer_dtype_from(converted, pandas_dtype=True)
- if dtype.kind in ["m", "M"]:
- # https://github.com/numpy/numpy/issues/12550
- # timedelta64 will incorrectly cast to int
- if not is_list_like(converted):
- converted = [converted] * mask.sum()
- values[mask] = converted
- else:
- converted = list(converted)
- np.putmask(values, mask, converted)
- else:
- np.putmask(values, mask, converted)
+ converted = setitem_datetimelike_compat(values, mask.sum(), converted)
+ np.putmask(values, mask, converted)
return type(self)._simple_new(values, name=self.name)
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index 5b2d9ce15ac89..af353cf3fb5f7 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -43,6 +43,7 @@
from pandas.core.dtypes.dtypes import IntervalDtype
from pandas.core.algorithms import take_nd, unique
+from pandas.core.array_algos.putmask import validate_putmask
from pandas.core.arrays.interval import IntervalArray, _interval_shared_docs
import pandas.core.common as com
from pandas.core.indexers import is_valid_positional_slice
@@ -799,10 +800,8 @@ def length(self):
return Index(self._data.length, copy=False)
def putmask(self, mask, value):
- mask = np.asarray(mask, dtype=bool)
- if mask.shape != self.shape:
- raise ValueError("putmask: mask and data must be the same size")
- if not mask.any():
+ mask, noop = validate_putmask(self._data, mask)
+ if noop:
return self.copy()
try:
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 28b98f66b410f..26d59db1b08fd 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -2151,9 +2151,6 @@ def repeat(self, repeats: int, axis=None) -> MultiIndex:
verify_integrity=False,
)
- def where(self, cond, other=None):
- raise NotImplementedError(".where is not supported for MultiIndex operations")
-
def drop(self, codes, level=None, errors="raise"):
"""
Make new MultiIndex with passed list of codes deleted
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index e99caac9eaace..8ba6018e743bb 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -24,7 +24,6 @@
astype_dt64_to_dt64tz,
astype_nansafe,
can_hold_element,
- convert_scalar_for_putitemlike,
find_common_type,
infer_dtype_from,
maybe_downcast_numeric,
@@ -52,9 +51,12 @@
import pandas.core.algorithms as algos
from pandas.core.array_algos.putmask import (
+ extract_bool_array,
putmask_inplace,
putmask_smart,
putmask_without_repeat,
+ setitem_datetimelike_compat,
+ validate_putmask,
)
from pandas.core.array_algos.quantile import quantile_with_mask
from pandas.core.array_algos.replace import (
@@ -425,7 +427,8 @@ def fillna(
inplace = validate_bool_kwarg(inplace, "inplace")
mask = isna(self.values)
- mask = _extract_bool_array(mask)
+ mask, noop = validate_putmask(self.values, mask)
+
if limit is not None:
limit = libalgos.validate_limit(None, limit=limit)
mask[mask.cumsum(self.ndim - 1) > limit] = False
@@ -442,8 +445,8 @@ def fillna(
# TODO: should be nb._maybe_downcast?
return self._maybe_downcast([nb], downcast)
- # we can't process the value, but nothing to do
- if not mask.any():
+ if noop:
+ # we can't process the value, but nothing to do
return [self] if inplace else [self.copy()]
# operate column-by-column
@@ -846,7 +849,7 @@ def _replace_list(
# GH#38086 faster if we know we dont need to check for regex
masks = [missing.mask_missing(self.values, s[0]) for s in pairs]
- masks = [_extract_bool_array(x) for x in masks]
+ masks = [extract_bool_array(x) for x in masks]
rb = [self if inplace else self.copy()]
for i, (src, dest) in enumerate(pairs):
@@ -968,18 +971,8 @@ def setitem(self, indexer, value):
# TODO(EA2D): special case not needed with 2D EA
values[indexer] = value.to_numpy(values.dtype).reshape(-1, 1)
- elif self.is_object and not is_ea_value and arr_value.dtype.kind in ["m", "M"]:
- # https://github.com/numpy/numpy/issues/12550
- # numpy will incorrect cast to int if we're not careful
- if is_list_like(value):
- value = list(value)
- else:
- value = [value] * len(values[indexer])
-
- values[indexer] = value
-
else:
-
+ value = setitem_datetimelike_compat(values, len(values[indexer]), value)
values[indexer] = value
if transpose:
@@ -1004,7 +997,7 @@ def putmask(self, mask, new) -> List[Block]:
List[Block]
"""
transpose = self.ndim == 2
- mask = _extract_bool_array(mask)
+ mask, noop = validate_putmask(self.values.T, mask)
assert not isinstance(new, (ABCIndex, ABCSeries, ABCDataFrame))
new_values = self.values # delay copy if possible.
@@ -1020,7 +1013,7 @@ def putmask(self, mask, new) -> List[Block]:
putmask_without_repeat(new_values, mask, new)
return [self]
- elif not mask.any():
+ elif noop:
return [self]
dtype, _ = infer_dtype_from(new)
@@ -1296,12 +1289,13 @@ def where(self, other, cond, errors="raise", axis: int = 0) -> List[Block]:
if transpose:
values = values.T
- cond = _extract_bool_array(cond)
+ icond, noop = validate_putmask(values, ~cond)
if is_valid_na_for_dtype(other, self.dtype) and not self.is_object:
other = self.fill_value
- if cond.ravel("K").all():
+ if noop:
+ # TODO: avoid the downcasting at the end in this case?
result = values
else:
# see if we can operate on the entire block, or need item-by-item
@@ -1313,23 +1307,14 @@ def where(self, other, cond, errors="raise", axis: int = 0) -> List[Block]:
blocks = block.where(orig_other, cond, errors=errors, axis=axis)
return self._maybe_downcast(blocks, "infer")
- dtype, _ = infer_dtype_from(other, pandas_dtype=True)
- if dtype.kind in ["m", "M"] and dtype.kind != values.dtype.kind:
- # expressions.where would cast np.timedelta64 to int
- if not is_list_like(other):
- other = [other] * (~cond).sum()
- else:
- other = list(other)
+ alt = setitem_datetimelike_compat(values, icond.sum(), other)
+ if alt is not other:
result = values.copy()
- np.putmask(result, ~cond, other)
-
+ np.putmask(result, icond, alt)
else:
- # convert datetime to datetime64, timedelta to timedelta64
- other = convert_scalar_for_putitemlike(other, values.dtype)
-
# By the time we get here, we should have all Series/Index
# args extracted to ndarray
- result = expressions.where(cond, values, other)
+ result = expressions.where(~icond, values, other)
if self._can_hold_na or self.ndim == 1:
@@ -1339,6 +1324,7 @@ def where(self, other, cond, errors="raise", axis: int = 0) -> List[Block]:
return [self.make_block(result)]
# might need to separate out blocks
+ cond = ~icond
axis = cond.ndim - 1
cond = cond.swapaxes(axis, 0)
mask = np.array([cond[i].all() for i in range(cond.shape[0])], dtype=bool)
@@ -1545,7 +1531,7 @@ def putmask(self, mask, new) -> List[Block]:
"""
See Block.putmask.__doc__
"""
- mask = _extract_bool_array(mask)
+ mask = extract_bool_array(mask)
new_values = self.values
@@ -1775,7 +1761,7 @@ def shift(self, periods: int, axis: int = 0, fill_value: Any = None) -> List[Blo
def where(self, other, cond, errors="raise", axis: int = 0) -> List[Block]:
- cond = _extract_bool_array(cond)
+ cond = extract_bool_array(cond)
assert not isinstance(other, (ABCIndex, ABCSeries, ABCDataFrame))
if isinstance(other, np.ndarray) and other.ndim == 2:
@@ -2019,7 +2005,7 @@ def to_native_types(self, na_rep="NaT", **kwargs):
return self.make_block(result)
def putmask(self, mask, new) -> List[Block]:
- mask = _extract_bool_array(mask)
+ mask = extract_bool_array(mask)
if not self._can_hold_element(new):
return self.astype(object).putmask(mask, new)
@@ -2034,7 +2020,7 @@ def where(self, other, cond, errors="raise", axis: int = 0) -> List[Block]:
# TODO(EA2D): reshape unnecessary with 2D EAs
arr = self.array_values().reshape(self.shape)
- cond = _extract_bool_array(cond)
+ cond = extract_bool_array(cond)
try:
res_values = arr.T.where(cond, other).T
@@ -2513,18 +2499,3 @@ def safe_reshape(arr: ArrayLike, new_shape: Shape) -> ArrayLike:
# TODO(EA2D): special case will be unnecessary with 2D EAs
arr = np.asarray(arr).reshape(new_shape)
return arr
-
-
-def _extract_bool_array(mask: ArrayLike) -> np.ndarray:
- """
- If we have a SparseArray or BooleanArray, convert it to ndarray[bool].
- """
- if isinstance(mask, ExtensionArray):
- # We could have BooleanArray, Sparse[bool], ...
- # Except for BooleanArray, this is equivalent to just
- # np.asarray(mask, dtype=bool)
- mask = mask.to_numpy(dtype=bool, na_value=False)
-
- assert isinstance(mask, np.ndarray), type(mask)
- assert mask.dtype == bool, mask.dtype
- return mask
| https://api.github.com/repos/pandas-dev/pandas/pulls/39778 | 2021-02-12T16:01:10Z | 2021-02-12T17:40:26Z | 2021-02-12T17:40:26Z | 2021-02-12T17:43:34Z | |
ENH: 'encoding_errors' argument for read_csv/json | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 370ea28832758..b240dad32f0e1 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -141,6 +141,7 @@ Other enhancements
- Add support for parsing ``ISO 8601``-like timestamps with negative signs to :meth:`pandas.Timedelta` (:issue:`37172`)
- Add support for unary operators in :class:`FloatingArray` (:issue:`38749`)
- :meth:`round` being enabled for the nullable integer and floating dtypes (:issue:`38844`)
+- :meth:`pandas.read_csv` and :meth:`pandas.read_json` expose the argument ``encoding_errors`` to control how encoding errors are handled (:issue:`39450`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx
index c4d98ccb88ba5..031a567925a4d 100644
--- a/pandas/_libs/parsers.pyx
+++ b/pandas/_libs/parsers.pyx
@@ -20,13 +20,19 @@ from libc.string cimport (
import cython
from cython import Py_ssize_t
-from cpython.bytes cimport PyBytes_AsString
+from cpython.bytes cimport (
+ PyBytes_AsString,
+ PyBytes_FromString,
+)
from cpython.exc cimport (
PyErr_Fetch,
PyErr_Occurred,
)
from cpython.object cimport PyObject
-from cpython.ref cimport Py_XDECREF
+from cpython.ref cimport (
+ Py_INCREF,
+ Py_XDECREF,
+)
from cpython.unicode cimport (
PyUnicode_AsUTF8String,
PyUnicode_Decode,
@@ -143,7 +149,7 @@ cdef extern from "parser/tokenizer.h":
enum: ERROR_OVERFLOW
ctypedef void* (*io_callback)(void *src, size_t nbytes, size_t *bytes_read,
- int *status)
+ int *status, const char *encoding_errors)
ctypedef int (*io_cleanup)(void *src)
ctypedef struct parser_t:
@@ -255,8 +261,8 @@ cdef extern from "parser/tokenizer.h":
int parser_trim_buffers(parser_t *self)
- int tokenize_all_rows(parser_t *self) nogil
- int tokenize_nrows(parser_t *self, size_t nrows) nogil
+ int tokenize_all_rows(parser_t *self, const char *encoding_errors) nogil
+ int tokenize_nrows(parser_t *self, size_t nrows, const char *encoding_errors) nogil
int64_t str_to_int64(char *p_item, int64_t int_min,
int64_t int_max, int *error, char tsep) nogil
@@ -293,7 +299,7 @@ cdef extern from "parser/io.h":
size_t *bytes_read, int *status)
void* buffer_rd_bytes(void *source, size_t nbytes,
- size_t *bytes_read, int *status)
+ size_t *bytes_read, int *status, const char *encoding_errors)
cdef class TextReader:
@@ -316,6 +322,7 @@ cdef class TextReader:
uint64_t parser_start
list clocks
char *c_encoding
+ const char *encoding_errors
kh_str_starts_t *false_set
kh_str_starts_t *true_set
@@ -370,10 +377,15 @@ cdef class TextReader:
bint verbose=False,
bint mangle_dupe_cols=True,
float_precision=None,
- bint skip_blank_lines=True):
+ bint skip_blank_lines=True,
+ encoding_errors=b"strict"):
# set encoding for native Python and C library
self.c_encoding = NULL
+ if isinstance(encoding_errors, str):
+ encoding_errors = encoding_errors.encode("utf-8")
+ Py_INCREF(encoding_errors)
+ self.encoding_errors = PyBytes_AsString(encoding_errors)
self.parser = parser_new()
self.parser.chunksize = tokenize_chunksize
@@ -558,13 +570,7 @@ cdef class TextReader:
pass
def __dealloc__(self):
- parser_free(self.parser)
- if self.true_set:
- kh_destroy_str_starts(self.true_set)
- self.true_set = NULL
- if self.false_set:
- kh_destroy_str_starts(self.false_set)
- self.false_set = NULL
+ self.close()
parser_del(self.parser)
def close(self):
@@ -632,7 +638,6 @@ cdef class TextReader:
char *word
object name, old_name
uint64_t hr, data_line = 0
- char *errors = "strict"
StringPath path = _string_path(self.c_encoding)
list header = []
set unnamed_cols = set()
@@ -673,11 +678,8 @@ cdef class TextReader:
for i in range(field_count):
word = self.parser.words[start + i]
- if path == UTF8:
- name = PyUnicode_FromString(word)
- elif path == ENCODED:
- name = PyUnicode_Decode(word, strlen(word),
- self.c_encoding, errors)
+ name = PyUnicode_Decode(word, strlen(word),
+ self.c_encoding, self.encoding_errors)
# We use this later when collecting placeholder names.
old_name = name
@@ -831,7 +833,7 @@ cdef class TextReader:
int status
with nogil:
- status = tokenize_nrows(self.parser, nrows)
+ status = tokenize_nrows(self.parser, nrows, self.encoding_errors)
if self.parser.warn_msg != NULL:
print(self.parser.warn_msg, file=sys.stderr)
@@ -859,7 +861,7 @@ cdef class TextReader:
'the whole file')
else:
with nogil:
- status = tokenize_all_rows(self.parser)
+ status = tokenize_all_rows(self.parser, self.encoding_errors)
if self.parser.warn_msg != NULL:
print(self.parser.warn_msg, file=sys.stderr)
@@ -1201,7 +1203,7 @@ cdef class TextReader:
if path == UTF8:
return _string_box_utf8(self.parser, i, start, end, na_filter,
- na_hashset)
+ na_hashset, self.encoding_errors)
elif path == ENCODED:
return _string_box_decode(self.parser, i, start, end,
na_filter, na_hashset, self.c_encoding)
@@ -1352,7 +1354,8 @@ cdef inline StringPath _string_path(char *encoding):
cdef _string_box_utf8(parser_t *parser, int64_t col,
int64_t line_start, int64_t line_end,
- bint na_filter, kh_str_starts_t *na_hashset):
+ bint na_filter, kh_str_starts_t *na_hashset,
+ const char *encoding_errors):
cdef:
int error, na_count = 0
Py_ssize_t i, lines
@@ -1391,7 +1394,7 @@ cdef _string_box_utf8(parser_t *parser, int64_t col,
pyval = <object>table.vals[k]
else:
# box it. new ref?
- pyval = PyUnicode_FromString(word)
+ pyval = PyUnicode_Decode(word, strlen(word), "utf-8", encoding_errors)
k = kh_put_strbox(table, word, &ret)
table.vals[k] = <PyObject *>pyval
diff --git a/pandas/_libs/src/parser/io.c b/pandas/_libs/src/parser/io.c
index 51504527de5a2..449f0b55bff70 100644
--- a/pandas/_libs/src/parser/io.c
+++ b/pandas/_libs/src/parser/io.c
@@ -163,7 +163,7 @@ void *buffer_file_bytes(void *source, size_t nbytes, size_t *bytes_read,
}
void *buffer_rd_bytes(void *source, size_t nbytes, size_t *bytes_read,
- int *status) {
+ int *status, const char *encoding_errors) {
PyGILState_STATE state;
PyObject *result, *func, *args, *tmp;
@@ -191,7 +191,7 @@ void *buffer_rd_bytes(void *source, size_t nbytes, size_t *bytes_read,
*status = CALLING_READ_FAILED;
return NULL;
} else if (!PyBytes_Check(result)) {
- tmp = PyUnicode_AsUTF8String(result);
+ tmp = PyUnicode_AsEncodedString(result, "utf-8", encoding_errors);
Py_DECREF(result);
if (tmp == NULL) {
PyGILState_Release(state);
diff --git a/pandas/_libs/src/parser/io.h b/pandas/_libs/src/parser/io.h
index aac418457d3b6..dbe757b458c54 100644
--- a/pandas/_libs/src/parser/io.h
+++ b/pandas/_libs/src/parser/io.h
@@ -64,6 +64,6 @@ void *buffer_file_bytes(void *source, size_t nbytes, size_t *bytes_read,
int *status);
void *buffer_rd_bytes(void *source, size_t nbytes, size_t *bytes_read,
- int *status);
+ int *status, const char *encoding_errors);
#endif // PANDAS__LIBS_SRC_PARSER_IO_H_
diff --git a/pandas/_libs/src/parser/tokenizer.c b/pandas/_libs/src/parser/tokenizer.c
index 1b229171ea879..49eb1e7855098 100644
--- a/pandas/_libs/src/parser/tokenizer.c
+++ b/pandas/_libs/src/parser/tokenizer.c
@@ -553,13 +553,15 @@ int parser_set_skipfirstnrows(parser_t *self, int64_t nrows) {
return 0;
}
-static int parser_buffer_bytes(parser_t *self, size_t nbytes) {
+static int parser_buffer_bytes(parser_t *self, size_t nbytes,
+ const char *encoding_errors) {
int status;
size_t bytes_read;
status = 0;
self->datapos = 0;
- self->data = self->cb_io(self->source, nbytes, &bytes_read, &status);
+ self->data = self->cb_io(self->source, nbytes, &bytes_read, &status,
+ encoding_errors);
TRACE((
"parser_buffer_bytes self->cb_io: nbytes=%zu, datalen: %d, status=%d\n",
nbytes, bytes_read, status));
@@ -1334,7 +1336,8 @@ int parser_trim_buffers(parser_t *self) {
all : tokenize all the data vs. certain number of rows
*/
-int _tokenize_helper(parser_t *self, size_t nrows, int all) {
+int _tokenize_helper(parser_t *self, size_t nrows, int all,
+ const char *encoding_errors) {
int status = 0;
uint64_t start_lines = self->lines;
@@ -1350,7 +1353,8 @@ int _tokenize_helper(parser_t *self, size_t nrows, int all) {
if (!all && self->lines - start_lines >= nrows) break;
if (self->datapos == self->datalen) {
- status = parser_buffer_bytes(self, self->chunksize);
+ status = parser_buffer_bytes(self, self->chunksize,
+ encoding_errors);
if (status == REACHED_EOF) {
// close out last line
@@ -1383,13 +1387,13 @@ int _tokenize_helper(parser_t *self, size_t nrows, int all) {
return status;
}
-int tokenize_nrows(parser_t *self, size_t nrows) {
- int status = _tokenize_helper(self, nrows, 0);
+int tokenize_nrows(parser_t *self, size_t nrows, const char *encoding_errors) {
+ int status = _tokenize_helper(self, nrows, 0, encoding_errors);
return status;
}
-int tokenize_all_rows(parser_t *self) {
- int status = _tokenize_helper(self, -1, 1);
+int tokenize_all_rows(parser_t *self, const char *encoding_errors) {
+ int status = _tokenize_helper(self, -1, 1, encoding_errors);
return status;
}
diff --git a/pandas/_libs/src/parser/tokenizer.h b/pandas/_libs/src/parser/tokenizer.h
index 876e2267906ee..f69fee4993d34 100644
--- a/pandas/_libs/src/parser/tokenizer.h
+++ b/pandas/_libs/src/parser/tokenizer.h
@@ -85,7 +85,7 @@ typedef enum {
} QuoteStyle;
typedef void *(*io_callback)(void *src, size_t nbytes, size_t *bytes_read,
- int *status);
+ int *status, const char *encoding_errors);
typedef int (*io_cleanup)(void *src);
typedef struct parser_t {
@@ -196,9 +196,9 @@ void parser_del(parser_t *self);
void parser_set_default_options(parser_t *self);
-int tokenize_nrows(parser_t *self, size_t nrows);
+int tokenize_nrows(parser_t *self, size_t nrows, const char *encoding_errors);
-int tokenize_all_rows(parser_t *self);
+int tokenize_all_rows(parser_t *self, const char *encoding_errors);
// Have parsed / type-converted a chunk of data
// and want to free memory from the token stream
diff --git a/pandas/io/common.py b/pandas/io/common.py
index cf3b92ec93b1f..b87e8fcae1064 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -583,12 +583,32 @@ def get_handle(
Returns the dataclass IOHandles
"""
# Windows does not default to utf-8. Set to utf-8 for a consistent behavior
- encoding_passed, encoding = encoding, encoding or "utf-8"
+ encoding = encoding or "utf-8"
# read_csv does not know whether the buffer is opened in binary/text mode
if _is_binary_mode(path_or_buf, mode) and "b" not in mode:
mode += "b"
+ # valdiate errors
+ if isinstance(errors, str):
+ errors = errors.lower()
+ if errors not in (
+ None,
+ "strict",
+ "ignore",
+ "replace",
+ "xmlcharrefreplace",
+ "backslashreplace",
+ "namereplace",
+ "surrogateescape",
+ "surrogatepass",
+ ):
+ raise ValueError(
+ f"Invalid value for `encoding_errors` ({errors}). Please see "
+ + "https://docs.python.org/3/library/codecs.html#error-handlers "
+ + "for valid values."
+ )
+
# open URLs
ioargs = _get_filepath_or_buffer(
path_or_buf,
@@ -677,9 +697,6 @@ def get_handle(
# Check whether the filename is to be opened in binary mode.
# Binary mode does not support 'encoding' and 'newline'.
if ioargs.encoding and "b" not in ioargs.mode:
- if errors is None and encoding_passed is None:
- # ignore errors when no encoding is specified
- errors = "replace"
# Encoding
handle = open(
handle,
diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py
index f050a6a086584..aa654e971641f 100644
--- a/pandas/io/json/_json.py
+++ b/pandas/io/json/_json.py
@@ -334,6 +334,7 @@ def read_json(
precise_float: bool = False,
date_unit=None,
encoding=None,
+ encoding_errors: Optional[str] = "strict",
lines: bool = False,
chunksize: Optional[int] = None,
compression: CompressionOptions = "infer",
@@ -456,6 +457,12 @@ def read_json(
encoding : str, default is 'utf-8'
The encoding to use to decode py3 bytes.
+ encoding_errors : str, optional, default "strict"
+ How encoding errors are treated. `List of possible values
+ <https://docs.python.org/3/library/codecs.html#error-handlers>`_ .
+
+ .. versionadded:: 1.3
+
lines : bool, default False
Read the file as a json object per line.
@@ -584,6 +591,7 @@ def read_json(
compression=compression,
nrows=nrows,
storage_options=storage_options,
+ encoding_errors=encoding_errors,
)
if chunksize:
@@ -620,6 +628,7 @@ def __init__(
compression: CompressionOptions,
nrows: Optional[int],
storage_options: StorageOptions = None,
+ encoding_errors: Optional[str] = "strict",
):
self.orient = orient
@@ -638,6 +647,7 @@ def __init__(
self.chunksize = chunksize
self.nrows_seen = 0
self.nrows = nrows
+ self.encoding_errors = encoding_errors
self.handles: Optional[IOHandles] = None
if self.chunksize is not None:
@@ -661,8 +671,8 @@ def _preprocess_data(self, data):
Otherwise, we read it into memory for the `read` method.
"""
if hasattr(data, "read") and not (self.chunksize or self.nrows):
- data = data.read()
- self.close()
+ with self:
+ data = data.read()
if not hasattr(data, "read") and (self.chunksize or self.nrows):
data = StringIO(data)
@@ -692,6 +702,7 @@ def _get_data_from_filepath(self, filepath_or_buffer):
encoding=self.encoding,
compression=self.compression,
storage_options=self.storage_options,
+ errors=self.encoding_errors,
)
filepath_or_buffer = self.handles.handle
diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py
index 2d17978b60327..c05efe9e73c5a 100644
--- a/pandas/io/parsers/base_parser.py
+++ b/pandas/io/parsers/base_parser.py
@@ -109,6 +109,7 @@
"mangle_dupe_cols": True,
"infer_datetime_format": False,
"skip_blank_lines": True,
+ "encoding_errors": "strict",
}
@@ -212,6 +213,7 @@ def _open_handles(self, src: FilePathOrBuffer, kwds: Dict[str, Any]) -> None:
compression=kwds.get("compression", None),
memory_map=kwds.get("memory_map", False),
storage_options=kwds.get("storage_options", None),
+ errors=kwds.get("encoding_errors", "strict"),
)
def _validate_parse_dates_presence(self, columns: List[str]) -> None:
diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py
index edfc7ee0b6258..6adf1b20b769f 100644
--- a/pandas/io/parsers/readers.py
+++ b/pandas/io/parsers/readers.py
@@ -296,11 +296,24 @@
Encoding to use for UTF when reading/writing (ex. 'utf-8'). `List of Python
standard encodings
<https://docs.python.org/3/library/codecs.html#standard-encodings>`_ .
+
.. versionchanged:: 1.2
When ``encoding`` is ``None``, ``errors="replace"`` is passed to
``open()``. Otherwise, ``errors="strict"`` is passed to ``open()``.
This behavior was previously only the case for ``engine="python"``.
+
+ .. versionchanged:: 1.3
+
+ ``encoding_errors`` is a new argument. ``encoding`` has no longer an
+ influence on how encoding errors are handled.
+
+encoding_errors : str, optional, default "strict"
+ How encoding errors are treated. `List of possible values
+ <https://docs.python.org/3/library/codecs.html#error-handlers>`_ .
+
+ .. versionadded:: 1.3
+
dialect : str or csv.Dialect, optional
If provided, this parameter will override values (default or not) for the
following parameters: `delimiter`, `doublequote`, `escapechar`,
@@ -515,6 +528,7 @@ def read_csv(
escapechar=None,
comment=None,
encoding=None,
+ encoding_errors: Optional[str] = "strict",
dialect=None,
# Error Handling
error_bad_lines=True,
@@ -599,6 +613,7 @@ def read_table(
# Error Handling
error_bad_lines=True,
warn_bad_lines=True,
+ encoding_errors: Optional[str] = "strict",
# Internal
delim_whitespace=False,
low_memory=_c_parser_defaults["low_memory"],
diff --git a/pandas/tests/io/parser/common/test_common_basic.py b/pandas/tests/io/parser/common/test_common_basic.py
index 6730d8cc46603..7cf9470e3057d 100644
--- a/pandas/tests/io/parser/common/test_common_basic.py
+++ b/pandas/tests/io/parser/common/test_common_basic.py
@@ -6,6 +6,7 @@
from inspect import signature
from io import StringIO
import os
+from pathlib import Path
import numpy as np
import pytest
@@ -734,3 +735,21 @@ def test_dict_keys_as_names(all_parsers):
result = parser.read_csv(StringIO(data), names=keys)
expected = DataFrame({"a": [1], "b": [2]})
tm.assert_frame_equal(result, expected)
+
+
+def test_encoding_surrogatepass(all_parsers):
+ # GH39017
+ parser = all_parsers
+ content = b"\xed\xbd\xbf"
+ decoded = content.decode("utf-8", errors="surrogatepass")
+ expected = DataFrame({decoded: [decoded]}, index=[decoded * 2])
+ expected.index.name = decoded * 2
+
+ with tm.ensure_clean() as path:
+ Path(path).write_bytes(
+ content * 2 + b"," + content + b"\n" + content * 2 + b"," + content
+ )
+ df = parser.read_csv(path, encoding_errors="surrogatepass", index_col=0)
+ tm.assert_frame_equal(df, expected)
+ with pytest.raises(UnicodeDecodeError, match="'utf-8' codec can't decode byte"):
+ parser.read_csv(path)
diff --git a/pandas/tests/io/parser/common/test_read_errors.py b/pandas/tests/io/parser/common/test_read_errors.py
index 91b5e26efafa1..4e3d99af685ec 100644
--- a/pandas/tests/io/parser/common/test_read_errors.py
+++ b/pandas/tests/io/parser/common/test_read_errors.py
@@ -232,5 +232,5 @@ def test_open_file(all_parsers):
warnings.simplefilter("always", category=ResourceWarning)
with warnings.catch_warnings(record=True) as record:
with pytest.raises(csv.Error, match="Could not determine delimiter"):
- parser.read_csv(file, sep=None)
+ parser.read_csv(file, sep=None, encoding_errors="replace")
assert len(record) == 0, record[0].message
diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py
index e1dcec56913f9..e483b5b5a8abb 100644
--- a/pandas/tests/io/test_common.py
+++ b/pandas/tests/io/test_common.py
@@ -2,6 +2,7 @@
Tests for the pandas.io.common functionalities
"""
import codecs
+from functools import partial
from io import (
BytesIO,
StringIO,
@@ -429,14 +430,6 @@ def test_is_fsspec_url():
assert not icom.is_fsspec_url("relative/local/path")
-def test_default_errors():
- # GH 38989
- with tm.ensure_clean() as path:
- file = Path(path)
- file.write_bytes(b"\xe4\na\n1")
- tm.assert_frame_equal(pd.read_csv(file, skiprows=[0]), pd.DataFrame({"a": [1]}))
-
-
@pytest.mark.parametrize("encoding", [None, "utf-8"])
@pytest.mark.parametrize("format", ["csv", "json"])
def test_codecs_encoding(encoding, format):
@@ -481,3 +474,46 @@ def test_explicit_encoding(io_class, mode, msg):
with io_class() as buffer:
with pytest.raises(TypeError, match=msg):
expected.to_csv(buffer, mode=f"w{mode}")
+
+
+@pytest.mark.parametrize("encoding_errors", [None, "strict", "replace"])
+@pytest.mark.parametrize("format", ["csv", "json"])
+def test_encoding_errors(encoding_errors, format):
+ # GH39450
+ msg = "'utf-8' codec can't decode byte"
+ bad_encoding = b"\xe4"
+
+ if format == "csv":
+ return
+ content = bad_encoding + b"\n" + bad_encoding
+ reader = pd.read_csv
+ else:
+ content = (
+ b'{"'
+ + bad_encoding * 2
+ + b'": {"'
+ + bad_encoding
+ + b'":"'
+ + bad_encoding
+ + b'"}}'
+ )
+ reader = partial(pd.read_json, orient="index")
+ with tm.ensure_clean() as path:
+ file = Path(path)
+ file.write_bytes(content)
+
+ if encoding_errors != "replace":
+ with pytest.raises(UnicodeDecodeError, match=msg):
+ reader(path, encoding_errors=encoding_errors)
+ else:
+ df = reader(path, encoding_errors=encoding_errors)
+ decoded = bad_encoding.decode(errors=encoding_errors)
+ expected = pd.DataFrame({decoded: [decoded]}, index=[decoded * 2])
+ tm.assert_frame_equal(df, expected)
+
+
+def test_bad_encdoing_errors():
+ # GH 39777
+ with tm.ensure_clean() as path:
+ with pytest.raises(ValueError, match="Invalid value for `encoding_errors`"):
+ icom.get_handle(path, "w", errors="bad")
| - [x] closes #39450
- [x] closes #39017
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
Should `encoding_errors` be added to `to_csv` and should `errors` in `to_csv` show a `DeprecationWarning` (for consistent naming)? | https://api.github.com/repos/pandas-dev/pandas/pulls/39777 | 2021-02-12T14:06:32Z | 2021-03-09T22:03:54Z | 2021-03-09T22:03:54Z | 2021-03-09T22:55:44Z |
DOC: Remove repeated column assignment in visualization doc | diff --git a/doc/source/user_guide/visualization.rst b/doc/source/user_guide/visualization.rst
index 7911c58b9867e..8b41cc24829c5 100644
--- a/doc/source/user_guide/visualization.rst
+++ b/doc/source/user_guide/visualization.rst
@@ -665,7 +665,7 @@ given by column ``z``. The bins are aggregated with NumPy's ``max`` function.
.. ipython:: python
df = pd.DataFrame(np.random.randn(1000, 2), columns=["a", "b"])
- df["b"] = df["b"] = df["b"] + np.arange(1000)
+ df["b"] = df["b"] + np.arange(1000)
df["z"] = np.random.uniform(0, 3, 1000)
@savefig hexbin_plot_agg.png
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
The visualization doc had an example where a column in a DataFrame is repeatedly assigned.
```python
df["b"] = df["b"] = df["b"] + np.arange(1000)
```
The expression has been simplified.
---
Thanks for helping to maintain the library!
| https://api.github.com/repos/pandas-dev/pandas/pulls/39770 | 2021-02-12T06:12:32Z | 2021-02-12T12:04:21Z | 2021-02-12T12:04:21Z | 2021-02-12T12:04:30Z |
BUG: incorrectly accepting datetime64(nat) for dt64tz | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 99ae60859b68c..4fe033b2c4344 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -346,7 +346,9 @@ Indexing
- Bug in setting ``timedelta64`` or ``datetime64`` values into numeric :class:`Series` failing to cast to object dtype (:issue:`39086`, issue:`39619`)
- Bug in setting :class:`Interval` values into a :class:`Series` or :class:`DataFrame` with mismatched :class:`IntervalDtype` incorrectly casting the new values to the existing dtype (:issue:`39120`)
- Bug in setting ``datetime64`` values into a :class:`Series` with integer-dtype incorrect casting the datetime64 values to integers (:issue:`39266`)
+- Bug in setting ``np.datetime64("NaT")`` into a :class:`Series` with :class:`Datetime64TZDtype` incorrectly treating the timezone-naive value as timezone-aware (:issue:`39769`)
- Bug in :meth:`Index.get_loc` not raising ``KeyError`` when method is specified for ``NaN`` value when ``NaN`` is not in :class:`Index` (:issue:`39382`)
+- Bug in :meth:`DatetimeIndex.insert` when inserting ``np.datetime64("NaT")`` into a timezone-aware index incorrectly treating the timezone-naive value as timezone-aware (:issue:`39769`)
- Bug in incorrectly raising in :meth:`Index.insert`, when setting a new column that cannot be held in the existing ``frame.columns``, or in :meth:`Series.reset_index` or :meth:`DataFrame.reset_index` instead of casting to a compatible dtype (:issue:`39068`)
- Bug in :meth:`RangeIndex.append` where a single object of length 1 was concatenated incorrectly (:issue:`39401`)
- Bug in setting ``numpy.timedelta64`` values into an object-dtype :class:`Series` using a boolean indexer (:issue:`39488`)
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 162a69370bc61..c77b6c9a87fbb 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -562,6 +562,12 @@ def _validate_scalar(
# GH#18295
value = NaT
+ elif isna(value):
+ # if we are dt64tz and value is dt64("NaT"), dont cast to NaT,
+ # or else we'll fail to raise in _unbox_scalar
+ msg = self._validation_error_message(value, allow_listlike)
+ raise TypeError(msg)
+
elif isinstance(value, self._recognized_scalars):
# error: Too many arguments for "object" [call-arg]
value = self._scalar_type(value) # type: ignore[call-arg]
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index 144a7186f5826..70c2015c6d41c 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -464,10 +464,8 @@ def _generate_range(
def _unbox_scalar(self, value, setitem: bool = False) -> np.datetime64:
if not isinstance(value, self._scalar_type) and value is not NaT:
raise ValueError("'value' should be a Timestamp.")
- if not isna(value):
- self._check_compatible_with(value, setitem=setitem)
- return value.asm8
- return np.datetime64(value.value, "ns")
+ self._check_compatible_with(value, setitem=setitem)
+ return value.asm8
def _scalar_from_string(self, value):
return Timestamp(value, tz=self.tz)
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 0f3e028c34c05..d92c10a2a4a1b 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -9,6 +9,7 @@
from pandas._config import get_option
+from pandas._libs import NaT
from pandas._libs.interval import (
VALID_CLOSED,
Interval,
@@ -23,7 +24,8 @@
from pandas.core.dtypes.cast import maybe_convert_platform
from pandas.core.dtypes.common import (
is_categorical_dtype,
- is_datetime64_any_dtype,
+ is_datetime64_dtype,
+ is_datetime64tz_dtype,
is_dtype_equal,
is_float_dtype,
is_integer_dtype,
@@ -999,9 +1001,12 @@ def _validate_setitem_value(self, value):
if is_integer_dtype(self.dtype.subtype):
# can't set NaN on a numpy integer array
needs_float_conversion = True
- elif is_datetime64_any_dtype(self.dtype.subtype):
+ elif is_datetime64_dtype(self.dtype.subtype):
# need proper NaT to set directly on the numpy array
value = np.datetime64("NaT")
+ elif is_datetime64tz_dtype(self.dtype.subtype):
+ # need proper NaT to set directly on the DatetimeArray array
+ value = NaT
elif is_timedelta64_dtype(self.dtype.subtype):
# need proper NaT to set directly on the numpy array
value = np.timedelta64("NaT")
diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py
index ef645313de614..7ebbbdc9ce7f9 100644
--- a/pandas/core/dtypes/missing.py
+++ b/pandas/core/dtypes/missing.py
@@ -604,7 +604,11 @@ def is_valid_na_for_dtype(obj, dtype: DtypeObj) -> bool:
if not lib.is_scalar(obj) or not isna(obj):
return False
if dtype.kind == "M":
- return not isinstance(obj, np.timedelta64)
+ if isinstance(dtype, np.dtype):
+ # i.e. not tzaware
+ return not isinstance(obj, np.timedelta64)
+ # we have to rule out tznaive dt64("NaT")
+ return not isinstance(obj, (np.timedelta64, np.datetime64))
if dtype.kind == "m":
return not isinstance(obj, np.datetime64)
if dtype.kind in ["i", "u", "f", "c"]:
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 8ba6018e743bb..4104804ce710b 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -8,6 +8,7 @@
from pandas._libs import (
Interval,
+ NaT,
Period,
Timestamp,
algos as libalgos,
@@ -2088,7 +2089,7 @@ class DatetimeTZBlock(ExtensionBlock, DatetimeBlock):
_can_hold_element = DatetimeBlock._can_hold_element
to_native_types = DatetimeBlock.to_native_types
diff = DatetimeBlock.diff
- fill_value = np.datetime64("NaT", "ns")
+ fill_value = NaT
where = DatetimeBlock.where
putmask = DatetimeLikeBlockMixin.putmask
diff --git a/pandas/tests/indexes/datetimes/test_insert.py b/pandas/tests/indexes/datetimes/test_insert.py
index 684c6b813b48f..6dbd1287b7306 100644
--- a/pandas/tests/indexes/datetimes/test_insert.py
+++ b/pandas/tests/indexes/datetimes/test_insert.py
@@ -13,8 +13,12 @@ class TestInsert:
@pytest.mark.parametrize("tz", [None, "UTC", "US/Eastern"])
def test_insert_nat(self, tz, null):
# GH#16537, GH#18295 (test missing)
+
idx = DatetimeIndex(["2017-01-01"], tz=tz)
expected = DatetimeIndex(["NaT", "2017-01-01"], tz=tz)
+ if tz is not None and isinstance(null, np.datetime64):
+ expected = Index([null, idx[0]], dtype=object)
+
res = idx.insert(0, null)
tm.assert_index_equal(res, expected)
diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py
index d97410562083c..e047317acd24d 100644
--- a/pandas/tests/series/indexing/test_indexing.py
+++ b/pandas/tests/series/indexing/test_indexing.py
@@ -559,7 +559,7 @@ def test_dt64_series_assign_nat(nat_val, tz, indexer_sli):
base = Series(dti)
expected = Series([pd.NaT] + list(dti[1:]), dtype=dti.dtype)
- should_cast = nat_val is pd.NaT or base.dtype.kind == nat_val.dtype.kind
+ should_cast = nat_val is pd.NaT or base.dtype == nat_val.dtype
if not should_cast:
expected = expected.astype(object)
diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py
index 3a9ec0948b29a..36948c3dc05f3 100644
--- a/pandas/tests/series/indexing/test_setitem.py
+++ b/pandas/tests/series/indexing/test_setitem.py
@@ -671,6 +671,43 @@ def key(self):
return 0
+class TestSetitemNADatetime64Dtype(SetitemCastingEquivalents):
+ # some nat-like values should be cast to datetime64 when inserting
+ # into a datetime64 series. Others should coerce to object
+ # and retain their dtypes.
+
+ @pytest.fixture(params=[None, "UTC", "US/Central"])
+ def obj(self, request):
+ tz = request.param
+ dti = date_range("2016-01-01", periods=3, tz=tz)
+ return Series(dti)
+
+ @pytest.fixture(
+ params=[NaT, np.timedelta64("NaT", "ns"), np.datetime64("NaT", "ns")]
+ )
+ def val(self, request):
+ return request.param
+
+ @pytest.fixture
+ def is_inplace(self, val, obj):
+ if obj._values.tz is None:
+ # cast to object iff val is timedelta64("NaT")
+ return val is NaT or val.dtype.kind == "M"
+
+ # otherwise we have to exclude tznaive dt64("NaT")
+ return val is NaT
+
+ @pytest.fixture
+ def expected(self, obj, val, is_inplace):
+ dtype = obj.dtype if is_inplace else object
+ expected = Series([val] + list(obj[1:]), dtype=dtype)
+ return expected
+
+ @pytest.fixture
+ def key(self):
+ return 0
+
+
class TestSetitemMismatchedTZCastsToObject(SetitemCastingEquivalents):
# GH#24024
@pytest.fixture
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39769 | 2021-02-12T04:01:33Z | 2021-02-16T00:19:50Z | 2021-02-16T00:19:50Z | 2021-02-16T01:23:59Z |
TST: split large tests | diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py
index 1b9b6452b2e33..3b6bc42544c51 100644
--- a/pandas/tests/indexing/test_categorical.py
+++ b/pandas/tests/indexing/test_categorical.py
@@ -322,6 +322,7 @@ def test_loc_listlike_dtypes(self):
with pytest.raises(KeyError, match=re.escape(msg)):
df.loc[["a", "x"]]
+ def test_loc_listlike_dtypes_duplicated_categories_and_codes(self):
# duplicated categories and codes
index = CategoricalIndex(["a", "b", "a"])
df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=index)
@@ -341,9 +342,11 @@ def test_loc_listlike_dtypes(self):
)
tm.assert_frame_equal(res, exp, check_index_type=True)
+ msg = "The following labels were missing: Index(['x'], dtype='object')"
with pytest.raises(KeyError, match=re.escape(msg)):
df.loc[["a", "x"]]
+ def test_loc_listlike_dtypes_unused_category(self):
# contains unused category
index = CategoricalIndex(["a", "b", "a", "c"], categories=list("abcde"))
df = DataFrame({"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]}, index=index)
@@ -363,6 +366,7 @@ def test_loc_listlike_dtypes(self):
)
tm.assert_frame_equal(res, exp, check_index_type=True)
+ msg = "The following labels were missing: Index(['x'], dtype='object')"
with pytest.raises(KeyError, match=re.escape(msg)):
df.loc[["a", "x"]]
@@ -405,6 +409,8 @@ def test_ix_categorical_index(self):
expect = DataFrame(df.loc[:, ["X", "Y"]], index=cdf.index, columns=exp_columns)
tm.assert_frame_equal(cdf.loc[:, ["X", "Y"]], expect)
+ def test_ix_categorical_index_non_unique(self):
+
# non-unique
df = DataFrame(np.random.randn(3, 3), index=list("ABA"), columns=list("XYX"))
cdf = df.copy()
diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py
index 1ac2a16660f93..25d4692e4cd1d 100644
--- a/pandas/tests/indexing/test_chaining_and_caching.py
+++ b/pandas/tests/indexing/test_chaining_and_caching.py
@@ -373,6 +373,7 @@ def test_setting_with_copy_bug(self):
with pytest.raises(com.SettingWithCopyError, match=msg):
df[["c"]][mask] = df[["b"]][mask]
+ def test_setting_with_copy_bug_no_warning(self):
# invalid warning as we are returning a new object
# GH 8730
df1 = DataFrame({"x": Series(["a", "b", "c"]), "y": Series(["d", "e", "f"])})
diff --git a/pandas/tests/indexing/test_datetime.py b/pandas/tests/indexing/test_datetime.py
index 44a5e2ae6d9e9..9f58f4af0ba55 100644
--- a/pandas/tests/indexing/test_datetime.py
+++ b/pandas/tests/indexing/test_datetime.py
@@ -37,6 +37,7 @@ def test_indexing_with_datetime_tz(self):
)
tm.assert_series_equal(result, expected)
+ def test_indexing_fast_xs(self):
# indexing - fast_xs
df = DataFrame({"a": date_range("2014-01-01", periods=10, tz="UTC")})
result = df.iloc[5]
@@ -53,6 +54,7 @@ def test_indexing_with_datetime_tz(self):
expected = df.iloc[4:]
tm.assert_frame_equal(result, expected)
+ def test_setitem_with_expansion(self):
# indexing - setting an element
df = DataFrame(
data=pd.to_datetime(["2015-03-30 20:12:32", "2015-03-12 00:11:11"]),
@@ -234,21 +236,23 @@ def test_loc_setitem_with_existing_dst(self):
def test_getitem_millisecond_resolution(self, frame_or_series):
# GH#33589
+
+ keys = [
+ "2017-10-25T16:25:04.151",
+ "2017-10-25T16:25:04.252",
+ "2017-10-25T16:50:05.237",
+ "2017-10-25T16:50:05.238",
+ ]
obj = frame_or_series(
[1, 2, 3, 4],
- index=[
- Timestamp("2017-10-25T16:25:04.151"),
- Timestamp("2017-10-25T16:25:04.252"),
- Timestamp("2017-10-25T16:50:05.237"),
- Timestamp("2017-10-25T16:50:05.238"),
- ],
+ index=[Timestamp(x) for x in keys],
)
- result = obj["2017-10-25T16:25:04.252":"2017-10-25T16:50:05.237"]
+ result = obj[keys[1] : keys[2]]
expected = frame_or_series(
[2, 3],
index=[
- Timestamp("2017-10-25T16:25:04.252"),
- Timestamp("2017-10-25T16:50:05.237"),
+ Timestamp(keys[1]),
+ Timestamp(keys[2]),
],
)
tm.assert_equal(result, expected)
diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py
index dcd073681cecf..63313589d64f7 100644
--- a/pandas/tests/indexing/test_indexing.py
+++ b/pandas/tests/indexing/test_indexing.py
@@ -125,6 +125,7 @@ def test_inf_upcast(self):
expected = pd.Float64Index([1, 2, np.inf])
tm.assert_index_equal(result, expected)
+ def test_inf_upcast_empty(self):
# Test with np.inf in columns
df = DataFrame()
df.loc[0, 0] = 1
@@ -148,6 +149,9 @@ def test_setitem_dtype_upcast(self):
)
tm.assert_frame_equal(df, expected)
+ @pytest.mark.parametrize("val", [3.14, "wxyz"])
+ def test_setitem_dtype_upcast2(self, val):
+
# GH10280
df = DataFrame(
np.arange(6, dtype="int64").reshape(2, 3),
@@ -155,19 +159,19 @@ def test_setitem_dtype_upcast(self):
columns=["foo", "bar", "baz"],
)
- for val in [3.14, "wxyz"]:
- left = df.copy()
- left.loc["a", "bar"] = val
- right = DataFrame(
- [[0, val, 2], [3, 4, 5]],
- index=list("ab"),
- columns=["foo", "bar", "baz"],
- )
+ left = df.copy()
+ left.loc["a", "bar"] = val
+ right = DataFrame(
+ [[0, val, 2], [3, 4, 5]],
+ index=list("ab"),
+ columns=["foo", "bar", "baz"],
+ )
- tm.assert_frame_equal(left, right)
- assert is_integer_dtype(left["foo"])
- assert is_integer_dtype(left["baz"])
+ tm.assert_frame_equal(left, right)
+ assert is_integer_dtype(left["foo"])
+ assert is_integer_dtype(left["baz"])
+ def test_setitem_dtype_upcast3(self):
left = DataFrame(
np.arange(6, dtype="int64").reshape(2, 3) / 10.0,
index=list("ab"),
@@ -195,6 +199,8 @@ def test_dups_fancy_indexing(self):
expected = Index(["b", "a", "a"])
tm.assert_index_equal(result, expected)
+ def test_dups_fancy_indexing_across_dtypes(self):
+
# across dtypes
df = DataFrame([[1, 2, 1.0, 2.0, 3.0, "foo", "bar"]], columns=list("aaaaaaa"))
df.head()
@@ -208,6 +214,7 @@ def test_dups_fancy_indexing(self):
tm.assert_frame_equal(df, result)
+ def test_dups_fancy_indexing_not_in_order(self):
# GH 3561, dups not in selected order
df = DataFrame(
{"test": [5, 7, 9, 11], "test1": [4.0, 5, 6, 7], "other": list("abcd")},
@@ -232,6 +239,8 @@ def test_dups_fancy_indexing(self):
with pytest.raises(KeyError, match="with any missing labels"):
df.loc[rows]
+ def test_dups_fancy_indexing_only_missing_label(self):
+
# List containing only missing label
dfnu = DataFrame(np.random.randn(5, 3), index=list("AABCD"))
with pytest.raises(
@@ -244,6 +253,8 @@ def test_dups_fancy_indexing(self):
# ToDo: check_index_type can be True after GH 11497
+ def test_dups_fancy_indexing_missing_label(self):
+
# GH 4619; duplicate indexer with missing label
df = DataFrame({"A": [0, 1, 2]})
with pytest.raises(KeyError, match="with any missing labels"):
@@ -253,6 +264,8 @@ def test_dups_fancy_indexing(self):
with pytest.raises(KeyError, match="with any missing labels"):
df.loc[[0, 8, 0]]
+ def test_dups_fancy_indexing_non_unique(self):
+
# non unique with non unique selector
df = DataFrame({"test": [5, 7, 9, 11]}, index=["A", "A", "B", "C"])
with pytest.raises(KeyError, match="with any missing labels"):
@@ -447,6 +460,7 @@ def test_multi_assign(self):
df2.loc[mask, cols] = dft.loc[mask, cols].values
tm.assert_frame_equal(df2, expected)
+ def test_multi_assign_broadcasting_rhs(self):
# broadcasting on the rhs is required
df = DataFrame(
{
@@ -781,14 +795,16 @@ def test_non_reducing_slice(self, slc):
tslice_ = non_reducing_slice(slc)
assert isinstance(df.loc[tslice_], DataFrame)
- def test_list_slice(self):
+ @pytest.mark.parametrize("box", [list, Series, np.array])
+ def test_list_slice(self, box):
# like dataframe getitem
- slices = [["A"], Series(["A"]), np.array(["A"])]
+ subset = box(["A"])
+
df = DataFrame({"A": [1, 2], "B": [3, 4]}, index=["A", "B"])
expected = pd.IndexSlice[:, ["A"]]
- for subset in slices:
- result = non_reducing_slice(subset)
- tm.assert_frame_equal(df.loc[result], df.loc[expected])
+
+ result = non_reducing_slice(subset)
+ tm.assert_frame_equal(df.loc[result], df.loc[expected])
def test_maybe_numeric_slice(self):
df = DataFrame({"A": [1, 2], "B": ["c", "d"], "C": [True, False]})
| https://api.github.com/repos/pandas-dev/pandas/pulls/39768 | 2021-02-12T02:17:37Z | 2021-02-15T23:53:51Z | 2021-02-15T23:53:51Z | 2021-02-16T00:05:54Z | |
DEPR: casting date to dt64 in maybe_promote | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 99ae60859b68c..1a092d930029e 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -239,7 +239,7 @@ Deprecations
- Deprecated :attr:`Rolling.is_datetimelike` (:issue:`38963`)
- Deprecated :meth:`core.window.ewm.ExponentialMovingWindow.vol` (:issue:`39220`)
- Using ``.astype`` to convert between ``datetime64[ns]`` dtype and :class:`DatetimeTZDtype` is deprecated and will raise in a future version, use ``obj.tz_localize`` or ``obj.dt.tz_localize`` instead (:issue:`38622`)
--
+- Deprecated casting ``datetime.date`` objects to ``datetime64`` when used as ``fill_value`` in :meth:`DataFrame.unstack`, :meth:`DataFrame.shift`, :meth:`Series.shift`, and :meth:`DataFrame.reindex`, pass ``pd.Timestamp(dateobj)`` instead (:issue:`39767`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index e27c519304e2e..74d750288bdeb 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -5,7 +5,7 @@
from __future__ import annotations
from contextlib import suppress
-from datetime import datetime, timedelta
+from datetime import date, datetime, timedelta
from typing import (
TYPE_CHECKING,
Any,
@@ -549,16 +549,46 @@ def maybe_promote(dtype: np.dtype, fill_value=np.nan):
# returns tuple of (dtype, fill_value)
if issubclass(dtype.type, np.datetime64):
- if isinstance(fill_value, datetime) and fill_value.tzinfo is not None:
- # Trying to insert tzaware into tznaive, have to cast to object
- dtype = np.dtype(np.object_)
- elif is_integer(fill_value) or is_float(fill_value):
- dtype = np.dtype(np.object_)
- else:
+ inferred, fv = infer_dtype_from_scalar(fill_value, pandas_dtype=True)
+ if inferred == dtype:
+ return dtype, fv
+
+ # TODO(2.0): once this deprecation is enforced, this whole case
+ # becomes equivalent to:
+ # dta = DatetimeArray._from_sequence([], dtype="M8[ns]")
+ # try:
+ # fv = dta._validate_setitem_value(fill_value)
+ # return dta.dtype, fv
+ # except (ValueError, TypeError):
+ # return np.dtype(object), fill_value
+ if isinstance(fill_value, date) and not isinstance(fill_value, datetime):
+ # deprecate casting of date object to match infer_dtype_from_scalar
+ # and DatetimeArray._validate_setitem_value
try:
- fill_value = Timestamp(fill_value).to_datetime64()
- except (TypeError, ValueError):
- dtype = np.dtype(np.object_)
+ fv = Timestamp(fill_value).to_datetime64()
+ except OutOfBoundsDatetime:
+ pass
+ else:
+ warnings.warn(
+ "Using a `date` object for fill_value with `datetime64[ns]` "
+ "dtype is deprecated. In a future version, this will be cast "
+ "to object dtype. Pass `fill_value=Timestamp(date_obj)` instead.",
+ FutureWarning,
+ stacklevel=7,
+ )
+ return dtype, fv
+ elif isinstance(fill_value, str):
+ try:
+ # explicitly wrap in str to convert np.str_
+ fv = Timestamp(str(fill_value))
+ except (ValueError, TypeError):
+ pass
+ else:
+ if fv.tz is None:
+ return dtype, fv.asm8
+
+ return np.dtype(object), fill_value
+
elif issubclass(dtype.type, np.timedelta64):
if (
is_integer(fill_value)
@@ -723,13 +753,13 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> Tuple[DtypeObj,
if val is NaT or val.tz is None:
dtype = np.dtype("M8[ns]")
+ val = val.to_datetime64()
else:
if pandas_dtype:
dtype = DatetimeTZDtype(unit="ns", tz=val.tz)
else:
# return datetimetz as object
return np.dtype(object), val
- val = val.value
elif isinstance(val, (np.timedelta64, timedelta)):
try:
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index af353cf3fb5f7..70adcd841a57d 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -533,6 +533,10 @@ def _maybe_convert_i8(self, key):
key_dtype, key_i8 = infer_dtype_from_scalar(key, pandas_dtype=True)
if lib.is_period(key):
key_i8 = key.ordinal
+ elif isinstance(key_i8, Timestamp):
+ key_i8 = key_i8.value
+ elif isinstance(key_i8, (np.datetime64, np.timedelta64)):
+ key_i8 = key_i8.view("i8")
else:
# DatetimeIndex/TimedeltaIndex
key_dtype, key_i8 = key.dtype, Index(key.asi8)
diff --git a/pandas/tests/dtypes/cast/test_infer_dtype.py b/pandas/tests/dtypes/cast/test_infer_dtype.py
index a47c5555d3e9f..2b18d110346e4 100644
--- a/pandas/tests/dtypes/cast/test_infer_dtype.py
+++ b/pandas/tests/dtypes/cast/test_infer_dtype.py
@@ -105,13 +105,11 @@ def test_infer_from_scalar_tz(tz, pandas_dtype):
if pandas_dtype:
exp_dtype = f"datetime64[ns, {tz}]"
- exp_val = dt.value
else:
exp_dtype = np.object_
- exp_val = dt
assert dtype == exp_dtype
- assert val == exp_val
+ assert val == dt
@pytest.mark.parametrize(
diff --git a/pandas/tests/dtypes/cast/test_promote.py b/pandas/tests/dtypes/cast/test_promote.py
index 08303fc601b3e..786944816bcf6 100644
--- a/pandas/tests/dtypes/cast/test_promote.py
+++ b/pandas/tests/dtypes/cast/test_promote.py
@@ -24,6 +24,7 @@
from pandas.core.dtypes.missing import isna
import pandas as pd
+import pandas._testing as tm
@pytest.fixture(
@@ -403,7 +404,13 @@ def test_maybe_promote_any_with_datetime64(
expected_dtype = np.dtype(object)
exp_val_for_scalar = fill_value
- _check_promote(dtype, fill_value, expected_dtype, exp_val_for_scalar)
+ warn = None
+ if type(fill_value) is datetime.date and dtype.kind == "M":
+ # Casting date to dt64 is deprecated
+ warn = FutureWarning
+
+ with tm.assert_produces_warning(warn, check_stacklevel=False):
+ _check_promote(dtype, fill_value, expected_dtype, exp_val_for_scalar)
@pytest.mark.parametrize(
diff --git a/pandas/tests/frame/methods/test_reindex.py b/pandas/tests/frame/methods/test_reindex.py
index e4e2656f4337c..e9c17c9f8cc5d 100644
--- a/pandas/tests/frame/methods/test_reindex.py
+++ b/pandas/tests/frame/methods/test_reindex.py
@@ -25,6 +25,28 @@ class TestDataFrameSelectReindex:
# These are specific reindex-based tests; other indexing tests should go in
# test_indexing
+ def test_reindex_date_fill_value(self):
+ # passing date to dt64 is deprecated
+ arr = date_range("2016-01-01", periods=6).values.reshape(3, 2)
+ df = DataFrame(arr, columns=["A", "B"], index=range(3))
+
+ ts = df.iloc[0, 0]
+ fv = ts.date()
+
+ with tm.assert_produces_warning(FutureWarning):
+ res = df.reindex(index=range(4), columns=["A", "B", "C"], fill_value=fv)
+
+ expected = DataFrame(
+ {"A": df["A"].tolist() + [ts], "B": df["B"].tolist() + [ts], "C": [ts] * 4}
+ )
+ tm.assert_frame_equal(res, expected)
+
+ # same with a datetime-castable str
+ res = df.reindex(
+ index=range(4), columns=["A", "B", "C"], fill_value="2016-01-01"
+ )
+ tm.assert_frame_equal(res, expected)
+
def test_reindex_with_multi_index(self):
# https://github.com/pandas-dev/pandas/issues/29896
# tests for reindexing a multi-indexed DataFrame with a new MultiIndex
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
Once enforced, maybe_promote behavior will match DatetimeArray._validate_setitem_value and infer_dtype_from_scalar
sits on top of #39743 | https://api.github.com/repos/pandas-dev/pandas/pulls/39767 | 2021-02-12T02:07:52Z | 2021-02-15T23:52:40Z | 2021-02-15T23:52:40Z | 2021-02-16T00:20:08Z |
BUG: pd.show_versions: json.decoder.JSONDecodeError | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 388c5dbf6a7ee..11ee3e2717612 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -478,6 +478,7 @@ Other
- :class:`Styler` rendered HTML output minor alterations to support w3 good code standard (:issue:`39626`)
- Bug in :class:`Styler` where rendered HTML was missing a column class identifier for certain header cells (:issue:`39716`)
- Bug in :meth:`DataFrame.equals`, :meth:`Series.equals`, :meth:`Index.equals` with object-dtype containing ``np.datetime64("NaT")`` or ``np.timedelta64("NaT")`` (:issue:`39650`)
+- Bug in :func:`pandas.util.show_versions` where console JSON output was not proper JSON (:issue:`39701`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/tests/util/test_show_versions.py b/pandas/tests/util/test_show_versions.py
index b6a16d027db77..57cd2e1a144b6 100644
--- a/pandas/tests/util/test_show_versions.py
+++ b/pandas/tests/util/test_show_versions.py
@@ -1,7 +1,14 @@
+import json
+import os
import re
import pytest
+from pandas.util._print_versions import (
+ _get_dependency_info,
+ _get_sys_info,
+)
+
import pandas as pd
@@ -26,11 +33,47 @@
"ignore:Distutils:UserWarning"
)
@pytest.mark.filterwarnings("ignore:Setuptools is replacing distutils:UserWarning")
-def test_show_versions(capsys):
+def test_show_versions(tmpdir):
+ # GH39701
+ as_json = os.path.join(tmpdir, "test_output.json")
+
+ pd.show_versions(as_json=as_json)
+
+ with open(as_json) as fd:
+ # check if file output is valid JSON, will raise an exception if not
+ result = json.load(fd)
+
+ # Basic check that each version element is found in output
+ expected = {
+ "system": _get_sys_info(),
+ "dependencies": _get_dependency_info(),
+ }
+
+ assert result == expected
+
+
+def test_show_versions_console_json(capsys):
+ # GH39701
+ pd.show_versions(as_json=True)
+ stdout = capsys.readouterr().out
+
+ # check valid json is printed to the console if as_json is True
+ result = json.loads(stdout)
+
+ # Basic check that each version element is found in output
+ expected = {
+ "system": _get_sys_info(),
+ "dependencies": _get_dependency_info(),
+ }
+
+ assert result == expected
+
+
+def test_show_versions_console(capsys):
+ # gh-32041
# gh-32041
- pd.show_versions()
- captured = capsys.readouterr()
- result = captured.out
+ pd.show_versions(as_json=False)
+ result = capsys.readouterr().out
# check header
assert "INSTALLED VERSIONS" in result
@@ -44,3 +87,16 @@ def test_show_versions(capsys):
# check optional dependency
assert re.search(r"pyarrow\s*:\s([0-9\.]+|None)\n", result)
+
+
+def test_json_output_match(capsys, tmpdir):
+ # GH39701
+ pd.show_versions(as_json=True)
+ result_console = capsys.readouterr().out
+
+ out_path = os.path.join(tmpdir, "test_json.json")
+ pd.show_versions(as_json=out_path)
+ with open(out_path) as out_fd:
+ result_file = out_fd.read()
+
+ assert result_console == result_file
diff --git a/pandas/util/_print_versions.py b/pandas/util/_print_versions.py
index b81ec70c34396..cf5af0de5d3b5 100644
--- a/pandas/util/_print_versions.py
+++ b/pandas/util/_print_versions.py
@@ -115,7 +115,7 @@ def show_versions(as_json: Union[str, bool] = False) -> None:
j = {"system": sys_info, "dependencies": deps}
if as_json is True:
- print(j)
+ sys.stdout.writelines(json.dumps(j, indent=2))
else:
assert isinstance(as_json, str) # needed for mypy
with codecs.open(as_json, "wb", encoding="utf8") as f:
| - [ x] closes #39701
- [ x] tests added / passed
- [ x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39766 | 2021-02-12T01:18:28Z | 2021-02-22T18:18:09Z | 2021-02-22T18:18:09Z | 2021-02-22T18:31:59Z |
BUG/REF: Refactor BaseWindowIndex so groupby.apply has a consistent index output | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 535bc5f3bd7bf..1be72c44d1a55 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -443,6 +443,7 @@ Groupby/resample/rolling
- Bug in :meth:`.GroupBy.mean`, :meth:`.GroupBy.median` and :meth:`DataFrame.pivot_table` not propagating metadata (:issue:`28283`)
- Bug in :meth:`Series.rolling` and :meth:`DataFrame.rolling` not calculating window bounds correctly when window is an offset and dates are in descending order (:issue:`40002`)
- Bug in :class:`SeriesGroupBy` and :class:`DataFrameGroupBy` on an empty ``Series`` or ``DataFrame`` would lose index, columns, and/or data types when directly using the methods ``idxmax``, ``idxmin``, ``mad``, ``min``, ``max``, ``sum``, ``prod``, and ``skew`` or using them through ``apply``, ``aggregate``, or ``resample`` (:issue:`26411`)
+- Bug in :meth:`DataFrameGroupBy.apply` where a :class:`MultiIndex` would be created instead of an :class:`Index` if a :class:`:meth:`core.window.rolling.RollingGroupby` object was created (:issue:`39732`)
- Bug in :meth:`DataFrameGroupBy.sample` where error was raised when ``weights`` was specified and the index was an :class:`Int64Index` (:issue:`39927`)
- Bug in :meth:`DataFrameGroupBy.aggregate` and :meth:`.Resampler.aggregate` would sometimes raise ``SpecificationError`` when passed a dictionary and columns were missing; will now always raise a ``KeyError`` instead (:issue:`40004`)
-
diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py
index c169e29b74dbb..927eb8eed8454 100644
--- a/pandas/core/groupby/base.py
+++ b/pandas/core/groupby/base.py
@@ -5,7 +5,6 @@
"""
import collections
from typing import List
-import warnings
from pandas._typing import final
@@ -31,10 +30,7 @@ def _shallow_copy(self, obj, **kwargs):
obj = obj.obj
for attr in self._attributes:
if attr not in kwargs:
- # TODO: Remove once win_type deprecation is enforced
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", "win_type", FutureWarning)
- kwargs[attr] = getattr(self, attr)
+ kwargs[attr] = getattr(self, attr)
return self._constructor(obj, **kwargs)
@@ -65,10 +61,7 @@ def _gotitem(self, key, ndim, subset=None):
# we need to make a shallow copy of ourselves
# with the same groupby
- # TODO: Remove once win_type deprecation is enforced
- with warnings.catch_warnings():
- warnings.filterwarnings("ignore", "win_type", FutureWarning)
- kwargs = {attr: getattr(self, attr) for attr in self._attributes}
+ kwargs = {attr: getattr(self, attr) for attr in self._attributes}
# Try to select from a DataFrame, falling back to a Series
try:
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 7bcdb348b8a1e..bf9fdb5d0cff7 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1918,7 +1918,12 @@ def rolling(self, *args, **kwargs):
"""
from pandas.core.window import RollingGroupby
- return RollingGroupby(self, *args, **kwargs)
+ return RollingGroupby(
+ self._selected_obj,
+ *args,
+ _grouper=self.grouper,
+ **kwargs,
+ )
@final
@Substitution(name="groupby")
@@ -1930,7 +1935,12 @@ def expanding(self, *args, **kwargs):
"""
from pandas.core.window import ExpandingGroupby
- return ExpandingGroupby(self, *args, **kwargs)
+ return ExpandingGroupby(
+ self._selected_obj,
+ *args,
+ _grouper=self.grouper,
+ **kwargs,
+ )
@final
@Substitution(name="groupby")
@@ -1941,7 +1951,12 @@ def ewm(self, *args, **kwargs):
"""
from pandas.core.window import ExponentialMovingWindowGroupby
- return ExponentialMovingWindowGroupby(self, *args, **kwargs)
+ return ExponentialMovingWindowGroupby(
+ self._selected_obj,
+ *args,
+ _grouper=self.grouper,
+ **kwargs,
+ )
@final
def _fill(self, direction, limit=None):
diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py
index 518119b63209e..208b5ab0023eb 100644
--- a/pandas/core/window/ewm.py
+++ b/pandas/core/window/ewm.py
@@ -213,7 +213,15 @@ class ExponentialMovingWindow(BaseWindow):
4 3.233686
"""
- _attributes = ["com", "min_periods", "adjust", "ignore_na", "axis"]
+ _attributes = [
+ "com",
+ "min_periods",
+ "adjust",
+ "ignore_na",
+ "axis",
+ "halflife",
+ "times",
+ ]
def __init__(
self,
@@ -227,17 +235,18 @@ def __init__(
ignore_na: bool = False,
axis: int = 0,
times: Optional[Union[str, np.ndarray, FrameOrSeries]] = None,
- **kwargs,
):
- self.obj = obj
- self.min_periods = max(int(min_periods), 1)
+ super().__init__(
+ obj=obj,
+ min_periods=max(int(min_periods), 1),
+ on=None,
+ center=False,
+ closed=None,
+ method="single",
+ axis=axis,
+ )
self.adjust = adjust
self.ignore_na = ignore_na
- self.axis = axis
- self.on = None
- self.center = False
- self.closed = None
- self.method = "single"
if times is not None:
if isinstance(times, str):
times = self._selected_obj[times]
@@ -556,9 +565,7 @@ class ExponentialMovingWindowGroupby(BaseWindowGroupby, ExponentialMovingWindow)
Provide an exponential moving window groupby implementation.
"""
- @property
- def _constructor(self):
- return ExponentialMovingWindow
+ _attributes = ExponentialMovingWindow._attributes + BaseWindowGroupby._attributes
def _get_window_indexer(self) -> GroupbyIndexer:
"""
@@ -569,7 +576,7 @@ def _get_window_indexer(self) -> GroupbyIndexer:
GroupbyIndexer
"""
window_indexer = GroupbyIndexer(
- groupby_indicies=self._groupby.indices,
+ groupby_indicies=self._grouper.indices,
window_indexer=ExponentialMovingWindowIndexer,
)
return window_indexer
diff --git a/pandas/core/window/expanding.py b/pandas/core/window/expanding.py
index 64e092d853456..c201216a91ab1 100644
--- a/pandas/core/window/expanding.py
+++ b/pandas/core/window/expanding.py
@@ -94,9 +94,7 @@ class Expanding(RollingAndExpandingMixin):
_attributes = ["min_periods", "center", "axis", "method"]
- def __init__(
- self, obj, min_periods=1, center=None, axis=0, method="single", **kwargs
- ):
+ def __init__(self, obj, min_periods=1, center=None, axis=0, method="single"):
super().__init__(
obj=obj, min_periods=min_periods, center=center, axis=axis, method=method
)
@@ -629,9 +627,7 @@ class ExpandingGroupby(BaseWindowGroupby, Expanding):
Provide a expanding groupby implementation.
"""
- @property
- def _constructor(self):
- return Expanding
+ _attributes = Expanding._attributes + BaseWindowGroupby._attributes
def _get_window_indexer(self) -> GroupbyIndexer:
"""
@@ -642,7 +638,7 @@ def _get_window_indexer(self) -> GroupbyIndexer:
GroupbyIndexer
"""
window_indexer = GroupbyIndexer(
- groupby_indicies=self._groupby.indices,
+ groupby_indicies=self._grouper.indices,
window_indexer=ExpandingIndexer,
)
return window_indexer
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index 20bf0142b0855..844f04ab7c196 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -4,6 +4,7 @@
"""
from __future__ import annotations
+import copy
from datetime import timedelta
from functools import partial
import inspect
@@ -64,10 +65,6 @@
)
import pandas.core.common as common
from pandas.core.construction import extract_array
-from pandas.core.groupby.base import (
- GotItemMixin,
- ShallowMixin,
-)
from pandas.core.indexes.api import (
Index,
MultiIndex,
@@ -114,19 +111,10 @@
from pandas.core.internals import Block # noqa:F401
-class BaseWindow(ShallowMixin, SelectionMixin):
+class BaseWindow(SelectionMixin):
"""Provides utilities for performing windowing operations."""
- _attributes: List[str] = [
- "window",
- "min_periods",
- "center",
- "win_type",
- "axis",
- "on",
- "closed",
- "method",
- ]
+ _attributes: List[str] = []
exclusions: Set[str] = set()
def __init__(
@@ -140,10 +128,7 @@ def __init__(
on: Optional[Union[str, Index]] = None,
closed: Optional[str] = None,
method: str = "single",
- **kwargs,
):
-
- self.__dict__.update(kwargs)
self.obj = obj
self.on = on
self.closed = closed
@@ -262,8 +247,12 @@ def _gotitem(self, key, ndim, subset=None):
# create a new object to prevent aliasing
if subset is None:
subset = self.obj
- self = self._shallow_copy(subset)
- self._reset_cache()
+ # TODO: Remove once win_type deprecation is enforced
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "win_type", FutureWarning)
+ self = type(self)(
+ subset, **{attr: getattr(self, attr) for attr in self._attributes}
+ )
if subset.ndim == 2:
if is_scalar(key) and key in subset or is_list_like(key):
self._selection = key
@@ -289,7 +278,7 @@ def __repr__(self) -> str:
attrs_list = (
f"{attr_name}={getattr(self, attr_name)}"
for attr_name in self._attributes
- if getattr(self, attr_name, None) is not None
+ if getattr(self, attr_name, None) is not None and attr_name[0] != "_"
)
attrs = ",".join(attrs_list)
return f"{type(self).__name__} [{attrs}]"
@@ -544,19 +533,23 @@ def aggregate(self, func, *args, **kwargs):
agg = aggregate
-class BaseWindowGroupby(GotItemMixin, BaseWindow):
+class BaseWindowGroupby(BaseWindow):
"""
Provide the groupby windowing facilities.
"""
- def __init__(self, obj, *args, **kwargs):
- kwargs.pop("parent", None)
- groupby = kwargs.pop("groupby", None)
- if groupby is None:
- groupby, obj = obj, obj._selected_obj
- self._groupby = groupby
- self._groupby.mutated = True
- self._groupby.grouper.mutated = True
+ _attributes = ["_grouper"]
+
+ def __init__(
+ self,
+ obj,
+ *args,
+ _grouper=None,
+ **kwargs,
+ ):
+ if _grouper is None:
+ raise ValueError("Must pass a Grouper object.")
+ self._grouper = _grouper
super().__init__(obj, *args, **kwargs)
def _apply(
@@ -576,9 +569,7 @@ def _apply(
# 1st set of levels = group by labels
# 2nd set of levels = original index
# Ignore 2nd set of levels if a group by label include an index level
- result_index_names = [
- grouping.name for grouping in self._groupby.grouper._groupings
- ]
+ result_index_names = copy.copy(self._grouper.names)
grouped_object_index = None
column_keys = [
@@ -595,10 +586,10 @@ def _apply(
# Our result will have still kept the column in the result
result = result.drop(columns=column_keys, errors="ignore")
- codes = self._groupby.grouper.codes
- levels = self._groupby.grouper.levels
+ codes = self._grouper.codes
+ levels = copy.copy(self._grouper.levels)
- group_indices = self._groupby.grouper.indices.values()
+ group_indices = self._grouper.indices.values()
if group_indices:
indexer = np.concatenate(list(group_indices))
else:
@@ -632,7 +623,7 @@ def _apply_pairwise(
Apply the given pairwise function given 2 pandas objects (DataFrame/Series)
"""
# Manually drop the grouping column first
- target = target.drop(columns=self._groupby.grouper.names, errors="ignore")
+ target = target.drop(columns=self._grouper.names, errors="ignore")
result = super()._apply_pairwise(target, other, pairwise, func)
# 1) Determine the levels + codes of the groupby levels
if other is not None:
@@ -643,12 +634,12 @@ def _apply_pairwise(
result = concat(
[
result.take(gb_indices).reindex(result.index)
- for gb_indices in self._groupby.indices.values()
+ for gb_indices in self._grouper.indices.values()
]
)
gb_pairs = (
- common.maybe_make_list(pair) for pair in self._groupby.indices.keys()
+ common.maybe_make_list(pair) for pair in self._grouper.indices.keys()
)
groupby_codes = []
groupby_levels = []
@@ -662,10 +653,10 @@ def _apply_pairwise(
else:
# When we evaluate the pairwise=True result, repeat the groupby
# labels by the number of columns in the original object
- groupby_codes = self._groupby.grouper.codes
- groupby_levels = self._groupby.grouper.levels
+ groupby_codes = self._grouper.codes
+ groupby_levels = self._grouper.levels
- group_indices = self._groupby.grouper.indices.values()
+ group_indices = self._grouper.indices.values()
if group_indices:
indexer = np.concatenate(list(group_indices))
else:
@@ -692,7 +683,7 @@ def _apply_pairwise(
# 3) Create the resulting index by combining 1) + 2)
result_codes = groupby_codes + result_codes
result_levels = groupby_levels + result_levels
- result_names = self._groupby.grouper.names + result_names
+ result_names = self._grouper.names + result_names
result_index = MultiIndex(
result_levels, result_codes, names=result_names, verify_integrity=False
@@ -708,9 +699,9 @@ def _create_data(self, obj: FrameOrSeries) -> FrameOrSeries:
# to the groups
# GH 36197
if not obj.empty:
- groupby_order = np.concatenate(
- list(self._groupby.grouper.indices.values())
- ).astype(np.int64)
+ groupby_order = np.concatenate(list(self._grouper.indices.values())).astype(
+ np.int64
+ )
obj = obj.take(groupby_order)
return super()._create_data(obj)
@@ -900,6 +891,17 @@ class Window(BaseWindow):
2013-01-01 09:00:06 4.0
"""
+ _attributes = [
+ "window",
+ "min_periods",
+ "center",
+ "win_type",
+ "axis",
+ "on",
+ "closed",
+ "method",
+ ]
+
def validate(self):
super().validate()
@@ -1390,6 +1392,18 @@ def corr_func(x, y):
class Rolling(RollingAndExpandingMixin):
+
+ _attributes = [
+ "window",
+ "min_periods",
+ "center",
+ "win_type",
+ "axis",
+ "on",
+ "closed",
+ "method",
+ ]
+
def validate(self):
super().validate()
@@ -2168,9 +2182,7 @@ class RollingGroupby(BaseWindowGroupby, Rolling):
Provide a rolling groupby implementation.
"""
- @property
- def _constructor(self):
- return Rolling
+ _attributes = Rolling._attributes + BaseWindowGroupby._attributes
def _get_window_indexer(self) -> GroupbyIndexer:
"""
@@ -2200,7 +2212,7 @@ def _get_window_indexer(self) -> GroupbyIndexer:
window_indexer = GroupbyIndexer(
index_array=index_array,
window_size=window,
- groupby_indicies=self._groupby.indices,
+ groupby_indicies=self._grouper.indices,
window_indexer=rolling_indexer,
indexer_kwargs=indexer_kwargs,
)
diff --git a/pandas/tests/window/test_expanding.py b/pandas/tests/window/test_expanding.py
index c272544e6af9e..1b9259fd8240e 100644
--- a/pandas/tests/window/test_expanding.py
+++ b/pandas/tests/window/test_expanding.py
@@ -53,7 +53,7 @@ def test_constructor_invalid(frame_or_series, w):
@pytest.mark.parametrize("method", ["std", "mean", "sum", "max", "min", "var"])
def test_numpy_compat(method):
# see gh-12811
- e = Expanding(Series([2, 4, 6]), window=2)
+ e = Expanding(Series([2, 4, 6]))
msg = "numpy operations are not valid with window objects"
diff --git a/pandas/tests/window/test_groupby.py b/pandas/tests/window/test_groupby.py
index d3c2b5467e5bb..c3c5bbe460134 100644
--- a/pandas/tests/window/test_groupby.py
+++ b/pandas/tests/window/test_groupby.py
@@ -83,6 +83,9 @@ def test_rolling(self, f):
result = getattr(r, f)()
expected = g.apply(lambda x: getattr(x.rolling(4), f)())
+ # GH 39732
+ expected_index = MultiIndex.from_arrays([self.frame["A"], range(40)])
+ expected.index = expected_index
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("f", ["std", "var"])
@@ -92,6 +95,9 @@ def test_rolling_ddof(self, f):
result = getattr(r, f)(ddof=1)
expected = g.apply(lambda x: getattr(x.rolling(4), f)(ddof=1))
+ # GH 39732
+ expected_index = MultiIndex.from_arrays([self.frame["A"], range(40)])
+ expected.index = expected_index
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
@@ -100,10 +106,14 @@ def test_rolling_ddof(self, f):
def test_rolling_quantile(self, interpolation):
g = self.frame.groupby("A")
r = g.rolling(window=4)
+
result = r.quantile(0.4, interpolation=interpolation)
expected = g.apply(
lambda x: x.rolling(4).quantile(0.4, interpolation=interpolation)
)
+ # GH 39732
+ expected_index = MultiIndex.from_arrays([self.frame["A"], range(40)])
+ expected.index = expected_index
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("f", ["corr", "cov"])
@@ -137,6 +147,9 @@ def test_rolling_apply(self, raw):
# reduction
result = r.apply(lambda x: x.sum(), raw=raw)
expected = g.apply(lambda x: x.rolling(4).apply(lambda y: y.sum(), raw=raw))
+ # GH 39732
+ expected_index = MultiIndex.from_arrays([self.frame["A"], range(40)])
+ expected.index = expected_index
tm.assert_frame_equal(result, expected)
def test_rolling_apply_mutability(self):
@@ -643,6 +656,16 @@ def test_groupby_rolling_resulting_multiindex(self):
)
tm.assert_index_equal(result.index, expected_index)
+ def test_groupby_rolling_object_doesnt_affect_groupby_apply(self):
+ # GH 39732
+ g = self.frame.groupby("A")
+ expected = g.apply(lambda x: x.rolling(4).sum()).index
+ _ = g.rolling(window=4)
+ result = g.apply(lambda x: x.rolling(4).sum()).index
+ tm.assert_index_equal(result, expected)
+ assert not g.mutated
+ assert not g.grouper.mutated
+
class TestExpanding:
def setup_method(self):
@@ -657,6 +680,9 @@ def test_expanding(self, f):
result = getattr(r, f)()
expected = g.apply(lambda x: getattr(x.expanding(), f)())
+ # GH 39732
+ expected_index = MultiIndex.from_arrays([self.frame["A"], range(40)])
+ expected.index = expected_index
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("f", ["std", "var"])
@@ -666,6 +692,9 @@ def test_expanding_ddof(self, f):
result = getattr(r, f)(ddof=0)
expected = g.apply(lambda x: getattr(x.expanding(), f)(ddof=0))
+ # GH 39732
+ expected_index = MultiIndex.from_arrays([self.frame["A"], range(40)])
+ expected.index = expected_index
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
@@ -674,10 +703,14 @@ def test_expanding_ddof(self, f):
def test_expanding_quantile(self, interpolation):
g = self.frame.groupby("A")
r = g.expanding()
+
result = r.quantile(0.4, interpolation=interpolation)
expected = g.apply(
lambda x: x.expanding().quantile(0.4, interpolation=interpolation)
)
+ # GH 39732
+ expected_index = MultiIndex.from_arrays([self.frame["A"], range(40)])
+ expected.index = expected_index
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("f", ["corr", "cov"])
@@ -715,6 +748,9 @@ def test_expanding_apply(self, raw):
# reduction
result = r.apply(lambda x: x.sum(), raw=raw)
expected = g.apply(lambda x: x.expanding().apply(lambda y: y.sum(), raw=raw))
+ # GH 39732
+ expected_index = MultiIndex.from_arrays([self.frame["A"], range(40)])
+ expected.index = expected_index
tm.assert_frame_equal(result, expected)
| - [x] closes #39732
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39765 | 2021-02-12T01:09:55Z | 2021-02-25T06:05:05Z | 2021-02-25T06:05:05Z | 2021-02-25T06:05:35Z |
DOC: Ban mutation in UDF methods | diff --git a/doc/source/user_guide/gotchas.rst b/doc/source/user_guide/gotchas.rst
index 07c856c96426d..4089f9523724f 100644
--- a/doc/source/user_guide/gotchas.rst
+++ b/doc/source/user_guide/gotchas.rst
@@ -178,6 +178,75 @@ To test for membership in the values, use the method :meth:`~pandas.Series.isin`
For ``DataFrames``, likewise, ``in`` applies to the column axis,
testing for membership in the list of column names.
+.. _udf-mutation:
+
+Mutating with User Defined Function (UDF) methods
+-------------------------------------------------
+
+It is a general rule in programming that one should not mutate a container
+while it is being iterated over. Mutation will invalidate the iterator,
+causing unexpected behavior. Consider the example:
+
+.. ipython:: python
+
+ values = [0, 1, 2, 3, 4, 5]
+ n_removed = 0
+ for k, value in enumerate(values):
+ idx = k - n_removed
+ if value % 2 == 1:
+ del values[idx]
+ n_removed += 1
+ else:
+ values[idx] = value + 1
+ values
+
+One probably would have expected that the result would be ``[1, 3, 5]``.
+When using a pandas method that takes a UDF, internally pandas is often
+iterating over the
+``DataFrame`` or other pandas object. Therefore, if the UDF mutates (changes)
+the ``DataFrame``, unexpected behavior can arise.
+
+Here is a similar example with :meth:`DataFrame.apply`:
+
+.. ipython:: python
+
+ def f(s):
+ s.pop("a")
+ return s
+
+ df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ try:
+ df.apply(f, axis="columns")
+ except Exception as err:
+ print(repr(err))
+
+To resolve this issue, one can make a copy so that the mutation does
+not apply to the container being iterated over.
+
+.. ipython:: python
+
+ values = [0, 1, 2, 3, 4, 5]
+ n_removed = 0
+ for k, value in enumerate(values.copy()):
+ idx = k - n_removed
+ if value % 2 == 1:
+ del values[idx]
+ n_removed += 1
+ else:
+ values[idx] = value + 1
+ values
+
+.. ipython:: python
+
+ def f(s):
+ s = s.copy()
+ s.pop("a")
+ return s
+
+ df = pd.DataFrame({"a": [1, 2, 3], 'b': [4, 5, 6]})
+ df.apply(f, axis="columns")
+
+
``NaN``, Integer ``NA`` values and ``NA`` type promotions
---------------------------------------------------------
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 63d238da12101..2b09853fc2442 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -7814,6 +7814,12 @@ def apply(
DataFrame.aggregate: Only perform aggregating type operations.
DataFrame.transform: Only perform transforming type operations.
+ Notes
+ -----
+ Functions that mutate the passed object can produce unexpected
+ behavior or errors and are not supported. See :ref:`udf-mutation`
+ for more details.
+
Examples
--------
>>> df = pd.DataFrame([[4, 9]] * 3, columns=['A', 'B'])
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index a7297923f1034..a658dcf259a81 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -580,6 +580,12 @@ def filter(self, func, dropna=True, *args, **kwargs):
dropna : Drop groups that do not pass the filter. True by default;
if False, groups that evaluate False are filled with NaNs.
+ Notes
+ -----
+ Functions that mutate the passed object can produce unexpected
+ behavior or errors and are not supported. See :ref:`udf-mutation`
+ for more details.
+
Examples
--------
>>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
@@ -1506,6 +1512,10 @@ def filter(self, func, dropna=True, *args, **kwargs):
Each subframe is endowed the attribute 'name' in case you need to know
which group you are working on.
+ Functions that mutate the passed object can produce unexpected
+ behavior or errors and are not supported. See :ref:`udf-mutation`
+ for more details.
+
Examples
--------
>>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 5758762c13984..66e7bc78b2f81 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -344,7 +344,7 @@ class providing the base-class of operations.
in the subframe. If f also supports application to the entire subframe,
then a fast path is used starting from the second chunk.
* f must not mutate groups. Mutation is not supported and may
- produce unexpected results.
+ produce unexpected results. See :ref:`udf-mutation` for more details.
When using ``engine='numba'``, there will be no "fall back" behavior internally.
The group data and group index will be passed as numpy arrays to the JITed
@@ -447,6 +447,10 @@ class providing the base-class of operations.
The group data and group index will be passed as numpy arrays to the JITed
user defined function, and no alternative execution attempts will be tried.
{examples}
+
+Functions that mutate the passed object can produce unexpected
+behavior or errors and are not supported. See :ref:`udf-mutation`
+for more details.
"""
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 7d97c9f6189f3..4d2203ff5621a 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -4044,6 +4044,12 @@ def apply(
Series.agg: Only perform aggregating type operations.
Series.transform: Only perform transforming type operations.
+ Notes
+ -----
+ Functions that mutate the passed object can produce unexpected
+ behavior or errors and are not supported. See :ref:`udf-mutation`
+ for more details.
+
Examples
--------
Create a series with typical summer temperatures for each city.
diff --git a/pandas/core/shared_docs.py b/pandas/core/shared_docs.py
index ad2eafe7295b0..49eb87a3bc8ba 100644
--- a/pandas/core/shared_docs.py
+++ b/pandas/core/shared_docs.py
@@ -41,6 +41,10 @@
-----
`agg` is an alias for `aggregate`. Use the alias.
+Functions that mutate the passed object can produce unexpected
+behavior or errors and are not supported. See :ref:`udf-mutation`
+for more details.
+
A passed user-defined-function will be passed a Series for evaluation.
{examples}"""
@@ -296,6 +300,12 @@
{klass}.agg : Only perform aggregating type operations.
{klass}.apply : Invoke function on a {klass}.
+Notes
+-----
+Functions that mutate the passed object can produce unexpected
+behavior or errors and are not supported. See :ref:`udf-mutation`
+for more details.
+
Examples
--------
>>> df = pd.DataFrame({{'A': range(3), 'B': range(1, 4)}})
| - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
Ref: #12653. I added the message to apply, aggregate, transform, and groupby's filter. Not sure if this needs a whatsnew.
cc @jbrockmendel | https://api.github.com/repos/pandas-dev/pandas/pulls/39762 | 2021-02-12T00:18:55Z | 2021-02-15T23:20:47Z | 2021-02-15T23:20:47Z | 2021-02-23T19:37:16Z |
BUG: Series.where not casting None to nan | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 09e1853429d9f..86548d2d59f1b 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -450,6 +450,7 @@ Other
- Bug in constructing a :class:`Series` from a list and a :class:`PandasDtype` (:issue:`39357`)
- Bug in :class:`Styler` which caused CSS to duplicate on multiple renders. (:issue:`39395`)
- ``inspect.getmembers(Series)`` no longer raises an ``AbstractMethodError`` (:issue:`38782`)
+- Bug in :meth:`Series.where` with numeric dtype and ``other = None`` not casting to ``nan`` (:issue:`39761`)
- :meth:`Index.where` behavior now mirrors :meth:`Index.putmask` behavior, i.e. ``index.where(mask, other)`` matches ``index.putmask(~mask, other)`` (:issue:`39412`)
- Bug in :func:`pandas.testing.assert_series_equal`, :func:`pandas.testing.assert_frame_equal`, :func:`pandas.testing.assert_index_equal` and :func:`pandas.testing.assert_extension_array_equal` incorrectly raising when an attribute has an unrecognized NA type (:issue:`39461`)
- Bug in :class:`Styler` where ``subset`` arg in methods raised an error for some valid multiindex slices (:issue:`33562`)
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 30e94b99b53c9..2b09c283eed9f 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -48,7 +48,7 @@
)
from pandas.core.dtypes.dtypes import CategoricalDtype, ExtensionDtype, PandasDtype
from pandas.core.dtypes.generic import ABCDataFrame, ABCIndex, ABCPandasArray, ABCSeries
-from pandas.core.dtypes.missing import isna
+from pandas.core.dtypes.missing import is_valid_na_for_dtype, isna
import pandas.core.algorithms as algos
from pandas.core.array_algos.putmask import (
@@ -1298,6 +1298,9 @@ def where(self, other, cond, errors="raise", axis: int = 0) -> List[Block]:
cond = _extract_bool_array(cond)
+ if is_valid_na_for_dtype(other, self.dtype) and not self.is_object:
+ other = self.fill_value
+
if cond.ravel("K").all():
result = values
else:
diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py
index e9ae7bb056041..dcd073681cecf 100644
--- a/pandas/tests/indexing/test_indexing.py
+++ b/pandas/tests/indexing/test_indexing.py
@@ -837,53 +837,6 @@ def test_label_indexing_on_nan(self):
assert result2 == expected
-class TestSeriesNoneCoercion:
- EXPECTED_RESULTS = [
- # For numeric series, we should coerce to NaN.
- ([1, 2, 3], [np.nan, 2, 3]),
- ([1.0, 2.0, 3.0], [np.nan, 2.0, 3.0]),
- # For datetime series, we should coerce to NaT.
- (
- [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)],
- [NaT, datetime(2000, 1, 2), datetime(2000, 1, 3)],
- ),
- # For objects, we should preserve the None value.
- (["foo", "bar", "baz"], [None, "bar", "baz"]),
- ]
-
- @pytest.mark.parametrize("start_data,expected_result", EXPECTED_RESULTS)
- def test_coercion_with_setitem(self, start_data, expected_result):
- start_series = Series(start_data)
- start_series[0] = None
-
- expected_series = Series(expected_result)
- tm.assert_series_equal(start_series, expected_series)
-
- @pytest.mark.parametrize("start_data,expected_result", EXPECTED_RESULTS)
- def test_coercion_with_loc_setitem(self, start_data, expected_result):
- start_series = Series(start_data)
- start_series.loc[0] = None
-
- expected_series = Series(expected_result)
- tm.assert_series_equal(start_series, expected_series)
-
- @pytest.mark.parametrize("start_data,expected_result", EXPECTED_RESULTS)
- def test_coercion_with_setitem_and_series(self, start_data, expected_result):
- start_series = Series(start_data)
- start_series[start_series == start_series[0]] = None
-
- expected_series = Series(expected_result)
- tm.assert_series_equal(start_series, expected_series)
-
- @pytest.mark.parametrize("start_data,expected_result", EXPECTED_RESULTS)
- def test_coercion_with_loc_and_series(self, start_data, expected_result):
- start_series = Series(start_data)
- start_series.loc[start_series == start_series[0]] = None
-
- expected_series = Series(expected_result)
- tm.assert_series_equal(start_series, expected_series)
-
-
class TestDataframeNoneCoercion:
EXPECTED_SINGLE_ROW_RESULTS = [
# For numeric series, we should coerce to NaN.
diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py
index da78dec4915c9..3a9ec0948b29a 100644
--- a/pandas/tests/series/indexing/test_setitem.py
+++ b/pandas/tests/series/indexing/test_setitem.py
@@ -1,4 +1,4 @@
-from datetime import date
+from datetime import date, datetime
import numpy as np
import pytest
@@ -297,7 +297,12 @@ def _check_inplace(self, is_inplace, orig, arr, obj):
# We are not (yet) checking whether setting is inplace or not
pass
elif is_inplace:
- assert obj._values is arr
+ if arr.dtype.kind in ["m", "M"]:
+ # We may not have the same DTA/TDA, but will have the same
+ # underlying data
+ assert arr._data is obj._values._data
+ else:
+ assert obj._values is arr
else:
# otherwise original array should be unchanged
tm.assert_equal(arr, orig._values)
@@ -635,6 +640,37 @@ def is_inplace(self):
return True
+class TestSetitemNATimedelta64Dtype(SetitemCastingEquivalents):
+ # some nat-like values should be cast to timedelta64 when inserting
+ # into a timedelta64 series. Others should coerce to object
+ # and retain their dtypes.
+
+ @pytest.fixture
+ def obj(self):
+ return Series([0, 1, 2], dtype="m8[ns]")
+
+ @pytest.fixture(
+ params=[NaT, np.timedelta64("NaT", "ns"), np.datetime64("NaT", "ns")]
+ )
+ def val(self, request):
+ return request.param
+
+ @pytest.fixture
+ def is_inplace(self, val):
+ # cast to object iff val is datetime64("NaT")
+ return val is NaT or val.dtype.kind == "m"
+
+ @pytest.fixture
+ def expected(self, obj, val, is_inplace):
+ dtype = obj.dtype if is_inplace else object
+ expected = Series([val] + list(obj[1:]), dtype=dtype)
+ return expected
+
+ @pytest.fixture
+ def key(self):
+ return 0
+
+
class TestSetitemMismatchedTZCastsToObject(SetitemCastingEquivalents):
# GH#24024
@pytest.fixture
@@ -659,3 +695,33 @@ def expected(self):
dtype=object,
)
return expected
+
+
+@pytest.mark.parametrize(
+ "obj,expected",
+ [
+ # For numeric series, we should coerce to NaN.
+ (Series([1, 2, 3]), Series([np.nan, 2, 3])),
+ (Series([1.0, 2.0, 3.0]), Series([np.nan, 2.0, 3.0])),
+ # For datetime series, we should coerce to NaT.
+ (
+ Series([datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)]),
+ Series([NaT, datetime(2000, 1, 2), datetime(2000, 1, 3)]),
+ ),
+ # For objects, we should preserve the None value.
+ (Series(["foo", "bar", "baz"]), Series([None, "bar", "baz"])),
+ ],
+)
+class TestSeriesNoneCoercion(SetitemCastingEquivalents):
+ @pytest.fixture
+ def key(self):
+ return 0
+
+ @pytest.fixture
+ def val(self):
+ return None
+
+ @pytest.fixture
+ def is_inplace(self, obj):
+ # This is specific to the 4 cases currently implemented for this class.
+ return obj.dtype.kind != "i"
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
started off just moving more tests to use SetitemCastingEquivalents, found this in TestSeriesNoneCoercion | https://api.github.com/repos/pandas-dev/pandas/pulls/39761 | 2021-02-11T23:09:03Z | 2021-02-12T01:27:36Z | 2021-02-12T01:27:36Z | 2021-02-12T15:24:22Z |
CLN: maybe_promote doesnt need to support EA dtypes | diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 98069e73dfd0c..a61ef62959b14 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -1662,7 +1662,12 @@ def take(arr, indices, axis: int = 0, allow_fill: bool = False, fill_value=None)
def _take_preprocess_indexer_and_fill_value(
- arr, indexer, axis, out, fill_value, allow_fill
+ arr: np.ndarray,
+ indexer: Optional[np.ndarray],
+ axis: int,
+ out: Optional[np.ndarray],
+ fill_value,
+ allow_fill: bool,
):
mask_info = None
@@ -1783,7 +1788,9 @@ def take_nd(
return out
-def take_2d_multi(arr, indexer, fill_value=np.nan):
+def take_2d_multi(
+ arr: np.ndarray, indexer: np.ndarray, fill_value=np.nan
+) -> np.ndarray:
"""
Specialized Cython take which sets NaN values in one pass.
"""
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 5d9b51238c255..18f1bba6ebfb8 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -35,7 +35,6 @@
conversion,
iNaT,
ints_to_pydatetime,
- tz_compare,
)
from pandas._typing import AnyArrayLike, ArrayLike, Dtype, DtypeObj, Scalar
from pandas.util._exceptions import find_stack_level
@@ -499,13 +498,13 @@ def ensure_dtype_can_hold_na(dtype: DtypeObj) -> DtypeObj:
return dtype
-def maybe_promote(dtype: DtypeObj, fill_value=np.nan):
+def maybe_promote(dtype: np.dtype, fill_value=np.nan):
"""
Find the minimal dtype that can hold both the given dtype and fill_value.
Parameters
----------
- dtype : np.dtype or ExtensionDtype
+ dtype : np.dtype
fill_value : scalar, default np.nan
Returns
@@ -567,19 +566,6 @@ def maybe_promote(dtype: DtypeObj, fill_value=np.nan):
fill_value = np.timedelta64("NaT", "ns")
else:
fill_value = fv.to_timedelta64()
- elif isinstance(dtype, DatetimeTZDtype):
- if isna(fill_value):
- fill_value = NaT
- elif not isinstance(fill_value, datetime):
- dtype = np.dtype(np.object_)
- elif fill_value.tzinfo is None:
- dtype = np.dtype(np.object_)
- elif not tz_compare(fill_value.tzinfo, dtype.tz):
- # TODO: sure we want to cast here?
- dtype = np.dtype(np.object_)
-
- elif is_extension_array_dtype(dtype) and isna(fill_value):
- fill_value = dtype.na_value
elif is_float(fill_value):
if issubclass(dtype.type, np.bool_):
@@ -634,7 +620,7 @@ def maybe_promote(dtype: DtypeObj, fill_value=np.nan):
if is_float_dtype(dtype) or is_complex_dtype(dtype):
fill_value = np.nan
elif is_integer_dtype(dtype):
- dtype = np.float64
+ dtype = np.dtype(np.float64)
fill_value = np.nan
else:
dtype = np.dtype(np.object_)
@@ -644,9 +630,7 @@ def maybe_promote(dtype: DtypeObj, fill_value=np.nan):
dtype = np.dtype(np.object_)
# in case we have a string that looked like a number
- if is_extension_array_dtype(dtype):
- pass
- elif issubclass(np.dtype(dtype).type, (bytes, str)):
+ if issubclass(dtype.type, (bytes, str)):
dtype = np.dtype(np.object_)
fill_value = _ensure_dtype_type(fill_value, dtype)
diff --git a/pandas/tests/dtypes/cast/test_promote.py b/pandas/tests/dtypes/cast/test_promote.py
index 16caf935652cb..08303fc601b3e 100644
--- a/pandas/tests/dtypes/cast/test_promote.py
+++ b/pandas/tests/dtypes/cast/test_promote.py
@@ -7,7 +7,7 @@
import numpy as np
import pytest
-from pandas._libs.tslibs import NaT, tz_compare
+from pandas._libs.tslibs import NaT
from pandas.core.dtypes.cast import maybe_promote
from pandas.core.dtypes.common import (
@@ -406,50 +406,6 @@ def test_maybe_promote_any_with_datetime64(
_check_promote(dtype, fill_value, expected_dtype, exp_val_for_scalar)
-def test_maybe_promote_datetimetz_with_any_numpy_dtype(
- tz_aware_fixture, any_numpy_dtype_reduced
-):
- dtype = DatetimeTZDtype(tz=tz_aware_fixture)
- fill_dtype = np.dtype(any_numpy_dtype_reduced)
-
- # create array of given dtype; casts "1" to correct dtype
- fill_value = np.array([1], dtype=fill_dtype)[0]
-
- # filling datetimetz with any numpy dtype casts to object
- expected_dtype = np.dtype(object)
- exp_val_for_scalar = fill_value
-
- _check_promote(dtype, fill_value, expected_dtype, exp_val_for_scalar)
-
-
-def test_maybe_promote_datetimetz_with_datetimetz(tz_aware_fixture, tz_aware_fixture2):
- dtype = DatetimeTZDtype(tz=tz_aware_fixture)
- fill_dtype = DatetimeTZDtype(tz=tz_aware_fixture2)
-
- # create array of given dtype; casts "1" to correct dtype
- fill_value = pd.Series([10 ** 9], dtype=fill_dtype)[0]
-
- # filling datetimetz with datetimetz casts to object, unless tz matches
- exp_val_for_scalar = fill_value
- if tz_compare(dtype.tz, fill_dtype.tz):
- expected_dtype = dtype
- else:
- expected_dtype = np.dtype(object)
-
- _check_promote(dtype, fill_value, expected_dtype, exp_val_for_scalar)
-
-
-@pytest.mark.parametrize("fill_value", [None, np.nan, NaT])
-def test_maybe_promote_datetimetz_with_na(tz_aware_fixture, fill_value):
-
- dtype = DatetimeTZDtype(tz=tz_aware_fixture)
-
- expected_dtype = dtype
- exp_val_for_scalar = NaT
-
- _check_promote(dtype, fill_value, expected_dtype, exp_val_for_scalar)
-
-
@pytest.mark.parametrize(
"fill_value",
[
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39760 | 2021-02-11T23:06:21Z | 2021-02-12T01:22:32Z | 2021-02-12T01:22:32Z | 2021-02-12T01:39:54Z |
BUG: casting dt64/td64 in DataFrame.reindex | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 09e1853429d9f..0d28177fa30e4 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -335,6 +335,7 @@ Indexing
- Bug in :meth:`DataFrame.__setitem__` raising ``ValueError`` when setting multiple values to duplicate columns (:issue:`15695`)
- Bug in :meth:`DataFrame.loc`, :meth:`Series.loc`, :meth:`DataFrame.__getitem__` and :meth:`Series.__getitem__` returning incorrect elements for non-monotonic :class:`DatetimeIndex` for string slices (:issue:`33146`)
- Bug in :meth:`DataFrame.reindex` and :meth:`Series.reindex` with timezone aware indexes raising ``TypeError`` for ``method="ffill"`` and ``method="bfill"`` and specified ``tolerance`` (:issue:`38566`)
+- Bug in :meth:`DataFrame.reindex` with ``datetime64[ns]`` or ``timedelta64[ns]`` incorrectly casting to integers when the ``fill_value`` requires casting to object dtype (:issue:`39755`)
- Bug in :meth:`DataFrame.__setitem__` raising ``ValueError`` with empty :class:`DataFrame` and specified columns for string indexer and non empty :class:`DataFrame` to set (:issue:`38831`)
- Bug in :meth:`DataFrame.loc.__setitem__` raising ValueError when expanding unique column for :class:`DataFrame` with duplicate columns (:issue:`38521`)
- Bug in :meth:`DataFrame.iloc.__setitem__` and :meth:`DataFrame.loc.__setitem__` with mixed dtypes when setting with a dictionary value (:issue:`38335`)
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 98069e73dfd0c..a55f857dc2357 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -1388,6 +1388,9 @@ def wrapper(arr, indexer, out, fill_value=np.nan):
def _convert_wrapper(f, conv_dtype):
def wrapper(arr, indexer, out, fill_value=np.nan):
+ if conv_dtype == object:
+ # GH#39755 avoid casting dt64/td64 to integers
+ arr = ensure_wrapped_if_datetimelike(arr)
arr = arr.astype(conv_dtype)
f(arr, indexer, out, fill_value=fill_value)
diff --git a/pandas/tests/frame/methods/test_reindex.py b/pandas/tests/frame/methods/test_reindex.py
index 9116b1ff5ad65..e4e2656f4337c 100644
--- a/pandas/tests/frame/methods/test_reindex.py
+++ b/pandas/tests/frame/methods/test_reindex.py
@@ -933,3 +933,38 @@ def test_reindex_empty(self, src_idx, cat_idx):
result = df.reindex(columns=cat_idx)
expected = DataFrame(index=["K"], columns=cat_idx, dtype="f8")
tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("dtype", ["m8[ns]", "M8[ns]"])
+ def test_reindex_datetimelike_to_object(self, dtype):
+ # GH#39755 dont cast dt64/td64 to ints
+ mi = MultiIndex.from_product([list("ABCDE"), range(2)])
+
+ dti = date_range("2016-01-01", periods=10)
+ fv = np.timedelta64("NaT", "ns")
+ if dtype == "m8[ns]":
+ dti = dti - dti[0]
+ fv = np.datetime64("NaT", "ns")
+
+ ser = Series(dti, index=mi)
+ ser[::3] = pd.NaT
+
+ df = ser.unstack()
+
+ index = df.index.append(Index([1]))
+ columns = df.columns.append(Index(["foo"]))
+
+ res = df.reindex(index=index, columns=columns, fill_value=fv)
+
+ expected = DataFrame(
+ {
+ 0: df[0].tolist() + [fv],
+ 1: df[1].tolist() + [fv],
+ "foo": np.array(["NaT"] * 6, dtype=fv.dtype),
+ },
+ index=index,
+ )
+ assert (res.dtypes[[0, 1]] == object).all()
+ assert res.iloc[0, 0] is pd.NaT
+ assert res.iloc[-1, 0] is fv
+ assert res.iloc[-1, 1] is fv
+ tm.assert_frame_equal(res, expected)
| - [x] closes #39755
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39759 | 2021-02-11T21:43:11Z | 2021-02-12T01:21:37Z | 2021-02-12T01:21:36Z | 2021-02-12T01:43:43Z |
[ArrayManager] TST: arithmetic test | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index aec19e27a33e2..ec67b15c8ed00 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -153,6 +153,7 @@ jobs:
run: |
source activate pandas-dev
pytest pandas/tests/frame/methods --array-manager
+ pytest pandas/tests/arithmetic/ --array-manager
# indexing iset related (temporary since other tests don't pass yet)
pytest pandas/tests/frame/indexing/test_indexing.py::TestDataFrameIndexing::test_setitem_multi_index --array-manager
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py
index 97a152d9ade1e..77d59169e95b4 100644
--- a/pandas/_testing/__init__.py
+++ b/pandas/_testing/__init__.py
@@ -207,8 +207,10 @@ def box_expected(expected, box_cls, transpose=True):
if transpose:
# for vector operations, we need a DataFrame to be a single-row,
# not a single-column, in order to operate against non-DataFrame
- # vectors of the same length.
+ # vectors of the same length. But convert to two rows to avoid
+ # single-row special cases in datetime arithmetic
expected = expected.T
+ expected = pd.concat([expected] * 2, ignore_index=True)
elif box_cls is PeriodArray:
# the PeriodArray constructor is not as flexible as period_array
expected = period_array(expected)
diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py
index b2d88b3556388..538b23507f74f 100644
--- a/pandas/tests/arithmetic/test_datetime64.py
+++ b/pandas/tests/arithmetic/test_datetime64.py
@@ -318,40 +318,40 @@ def test_dt64arr_timestamp_equality(self, box_with_array):
box_with_array if box_with_array not in [pd.Index, pd.array] else np.ndarray
)
- ser = Series([Timestamp("2000-01-29 01:59:00"), "NaT"])
+ ser = Series([Timestamp("2000-01-29 01:59:00"), Timestamp("2000-01-30"), "NaT"])
ser = tm.box_expected(ser, box_with_array)
result = ser != ser
- expected = tm.box_expected([False, True], xbox)
+ expected = tm.box_expected([False, False, True], xbox)
tm.assert_equal(result, expected)
warn = FutureWarning if box_with_array is pd.DataFrame else None
with tm.assert_produces_warning(warn):
# alignment for frame vs series comparisons deprecated
result = ser != ser[0]
- expected = tm.box_expected([False, True], xbox)
+ expected = tm.box_expected([False, True, True], xbox)
tm.assert_equal(result, expected)
with tm.assert_produces_warning(warn):
# alignment for frame vs series comparisons deprecated
- result = ser != ser[1]
- expected = tm.box_expected([True, True], xbox)
+ result = ser != ser[2]
+ expected = tm.box_expected([True, True, True], xbox)
tm.assert_equal(result, expected)
result = ser == ser
- expected = tm.box_expected([True, False], xbox)
+ expected = tm.box_expected([True, True, False], xbox)
tm.assert_equal(result, expected)
with tm.assert_produces_warning(warn):
# alignment for frame vs series comparisons deprecated
result = ser == ser[0]
- expected = tm.box_expected([True, False], xbox)
+ expected = tm.box_expected([True, False, False], xbox)
tm.assert_equal(result, expected)
with tm.assert_produces_warning(warn):
# alignment for frame vs series comparisons deprecated
- result = ser == ser[1]
- expected = tm.box_expected([False, False], xbox)
+ result = ser == ser[2]
+ expected = tm.box_expected([False, False, False], xbox)
tm.assert_equal(result, expected)
@@ -1010,10 +1010,7 @@ def test_dt64arr_sub_dt64object_array(self, box_with_array, tz_naive_fixture):
obj = tm.box_expected(dti, box_with_array)
expected = tm.box_expected(expected, box_with_array)
- warn = None
- if box_with_array is not pd.DataFrame or tz_naive_fixture is None:
- warn = PerformanceWarning
- with tm.assert_produces_warning(warn):
+ with tm.assert_produces_warning(PerformanceWarning):
result = obj - obj.astype(object)
tm.assert_equal(result, expected)
@@ -1276,7 +1273,7 @@ def test_dt64arr_add_sub_relativedelta_offsets(self, box_with_array):
]
)
vec = tm.box_expected(vec, box_with_array)
- vec_items = vec.squeeze() if box_with_array is pd.DataFrame else vec
+ vec_items = vec.iloc[0] if box_with_array is pd.DataFrame else vec
# DateOffset relativedelta fastpath
relative_kwargs = [
@@ -1401,7 +1398,7 @@ def test_dt64arr_add_sub_DateOffsets(
]
)
vec = tm.box_expected(vec, box_with_array)
- vec_items = vec.squeeze() if box_with_array is pd.DataFrame else vec
+ vec_items = vec.iloc[0] if box_with_array is pd.DataFrame else vec
offset_cls = getattr(pd.offsets, cls_name)
@@ -1515,10 +1512,7 @@ def test_dt64arr_add_sub_offset_array(
if box_other:
other = tm.box_expected(other, box_with_array)
- warn = PerformanceWarning
- if box_with_array is pd.DataFrame and tz is not None:
- warn = None
- with tm.assert_produces_warning(warn):
+ with tm.assert_produces_warning(PerformanceWarning):
res = op(dtarr, other)
tm.assert_equal(res, expected)
@@ -2459,18 +2453,14 @@ def test_dti_addsub_object_arraylike(
expected = DatetimeIndex(["2017-01-31", "2017-01-06"], tz=tz_naive_fixture)
expected = tm.box_expected(expected, xbox)
- warn = PerformanceWarning
- if box_with_array is pd.DataFrame and tz is not None:
- warn = None
-
- with tm.assert_produces_warning(warn):
+ with tm.assert_produces_warning(PerformanceWarning):
result = dtarr + other
tm.assert_equal(result, expected)
expected = DatetimeIndex(["2016-12-31", "2016-12-29"], tz=tz_naive_fixture)
expected = tm.box_expected(expected, xbox)
- with tm.assert_produces_warning(warn):
+ with tm.assert_produces_warning(PerformanceWarning):
result = dtarr - other
tm.assert_equal(result, expected)
diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py
index f4f258b559939..9c01a6a4a524c 100644
--- a/pandas/tests/arithmetic/test_numeric.py
+++ b/pandas/tests/arithmetic/test_numeric.py
@@ -532,13 +532,17 @@ def test_df_div_zero_series_does_not_commute(self):
# ------------------------------------------------------------------
# Mod By Zero
- def test_df_mod_zero_df(self):
+ def test_df_mod_zero_df(self, using_array_manager):
# GH#3590, modulo as ints
df = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]})
# this is technically wrong, as the integer portion is coerced to float
- # ###
- first = Series([0, 0, 0, 0], dtype="float64")
+ first = Series([0, 0, 0, 0])
+ if not using_array_manager:
+ # INFO(ArrayManager) BlockManager doesn't preserve dtype per column
+ # while ArrayManager performs op column-wisedoes and thus preserves
+ # dtype if possible
+ first = first.astype("float64")
second = Series([np.nan, np.nan, np.nan, 0])
expected = pd.DataFrame({"first": first, "second": second})
result = df % df
diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py
index 740ec3be4a1c6..57b8980e568d8 100644
--- a/pandas/tests/arithmetic/test_timedelta64.py
+++ b/pandas/tests/arithmetic/test_timedelta64.py
@@ -1748,7 +1748,9 @@ def test_tdarr_div_length_mismatch(self, box_with_array):
# ------------------------------------------------------------------
# __floordiv__, __rfloordiv__
- def test_td64arr_floordiv_td64arr_with_nat(self, box_with_array):
+ def test_td64arr_floordiv_td64arr_with_nat(
+ self, box_with_array, using_array_manager
+ ):
# GH#35529
box = box_with_array
xbox = np.ndarray if box is pd.array else box
@@ -1761,6 +1763,11 @@ def test_td64arr_floordiv_td64arr_with_nat(self, box_with_array):
expected = np.array([1.0, 1.0, np.nan], dtype=np.float64)
expected = tm.box_expected(expected, xbox)
+ if box is DataFrame and using_array_manager:
+ # INFO(ArrayManager) floorfiv returns integer, and ArrayManager
+ # performs ops column-wise and thus preserves int64 dtype for
+ # columns without missing values
+ expected[[0, 1]] = expected[[0, 1]].astype("int64")
result = left // right
@@ -2040,7 +2047,9 @@ def test_td64arr_rmul_numeric_array(self, box_with_array, vector, any_real_dtype
[np.array([20, 30, 40]), pd.Index([20, 30, 40]), Series([20, 30, 40])],
ids=lambda x: type(x).__name__,
)
- def test_td64arr_div_numeric_array(self, box_with_array, vector, any_real_dtype):
+ def test_td64arr_div_numeric_array(
+ self, box_with_array, vector, any_real_dtype, using_array_manager
+ ):
# GH#4521
# divide/multiply by integers
xbox = get_upcast_box(box_with_array, vector)
@@ -2075,6 +2084,15 @@ def test_td64arr_div_numeric_array(self, box_with_array, vector, any_real_dtype)
expected = [tdser[n] / vector[n] for n in range(len(tdser))]
expected = pd.Index(expected) # do dtype inference
expected = tm.box_expected(expected, xbox)
+
+ if using_array_manager and box_with_array is pd.DataFrame:
+ # TODO the behaviour is buggy here (third column with all-NaT
+ # as result doesn't get preserved as timedelta64 dtype).
+ # Reported at https://github.com/pandas-dev/pandas/issues/39750
+ # Changing the expected instead of xfailing to continue to test
+ # the correct behaviour for the other columns
+ expected[2] = Series([pd.NaT, pd.NaT], dtype=object)
+
tm.assert_equal(result, expected)
with pytest.raises(TypeError, match=pattern):
| xref https://github.com/pandas-dev/pandas/issues/39146/ | https://api.github.com/repos/pandas-dev/pandas/pulls/39753 | 2021-02-11T12:28:59Z | 2021-02-17T09:37:19Z | 2021-02-17T09:37:19Z | 2021-02-17T09:38:14Z |
ENH: Implement rounding for floating dtype array #38844 | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index e99963c6ad56b..7d16288ecdd4c 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -139,6 +139,7 @@ Other enhancements
- :meth:`pandas.read_stata` and :class:`StataReader` support reading data from compressed files.
- Add support for parsing ``ISO 8601``-like timestamps with negative signs to :meth:`pandas.Timedelta` (:issue:`37172`)
- Add support for unary operators in :class:`FloatingArray` (:issue:`38749`)
+- :meth:`round` being enabled for the nullable integer and floating dtypes (:issue:`38844`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/arrays/numeric.py b/pandas/core/arrays/numeric.py
index 0dd98c5e3d3f2..f06099a642833 100644
--- a/pandas/core/arrays/numeric.py
+++ b/pandas/core/arrays/numeric.py
@@ -6,6 +6,7 @@
TYPE_CHECKING,
Any,
List,
+ TypeVar,
Union,
)
@@ -15,6 +16,7 @@
Timedelta,
missing as libmissing,
)
+from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
from pandas.core.dtypes.common import (
@@ -34,6 +36,8 @@
if TYPE_CHECKING:
import pyarrow
+T = TypeVar("T", bound="NumericArray")
+
class NumericDtype(BaseMaskedDtype):
def __from_arrow__(
@@ -208,3 +212,31 @@ def __pos__(self):
def __abs__(self):
return type(self)(abs(self._data), self._mask.copy())
+
+ def round(self: T, decimals: int = 0, *args, **kwargs) -> T:
+ """
+ Round each value in the array a to the given number of decimals.
+
+ Parameters
+ ----------
+ decimals : int, default 0
+ Number of decimal places to round to. If decimals is negative,
+ it specifies the number of positions to the left of the decimal point.
+ *args, **kwargs
+ Additional arguments and keywords have no effect but might be
+ accepted for compatibility with NumPy.
+
+ Returns
+ -------
+ NumericArray
+ Rounded values of the NumericArray.
+
+ See Also
+ --------
+ numpy.around : Round values of an np.array.
+ DataFrame.round : Round values of a DataFrame.
+ Series.round : Round values of a Series.
+ """
+ nv.validate_round(args, kwargs)
+ values = np.round(self._data, decimals=decimals, **kwargs)
+ return type(self)(values, self._mask.copy())
diff --git a/pandas/tests/arrays/masked/test_function.py b/pandas/tests/arrays/masked/test_function.py
new file mode 100644
index 0000000000000..1c0e0820f7dcc
--- /dev/null
+++ b/pandas/tests/arrays/masked/test_function.py
@@ -0,0 +1,44 @@
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.common import is_integer_dtype
+
+import pandas as pd
+import pandas._testing as tm
+
+arrays = [pd.array([1, 2, 3, None], dtype=dtype) for dtype in tm.ALL_EA_INT_DTYPES]
+arrays += [
+ pd.array([0.141, -0.268, 5.895, None], dtype=dtype) for dtype in tm.FLOAT_EA_DTYPES
+]
+
+
+@pytest.fixture(params=arrays, ids=[a.dtype.name for a in arrays])
+def data(request):
+ return request.param
+
+
+@pytest.fixture()
+def numpy_dtype(data):
+ # For integer dtype, the numpy conversion must be done to float
+ if is_integer_dtype(data):
+ numpy_dtype = float
+ else:
+ numpy_dtype = data.dtype.type
+ return numpy_dtype
+
+
+def test_round(data, numpy_dtype):
+ # No arguments
+ result = data.round()
+ expected = pd.array(
+ np.round(data.to_numpy(dtype=numpy_dtype, na_value=None)), dtype=data.dtype
+ )
+ tm.assert_extension_array_equal(result, expected)
+
+ # Decimals argument
+ result = data.round(decimals=2)
+ expected = pd.array(
+ np.round(data.to_numpy(dtype=numpy_dtype, na_value=None), decimals=2),
+ dtype=data.dtype,
+ )
+ tm.assert_extension_array_equal(result, expected)
diff --git a/pandas/tests/series/methods/test_round.py b/pandas/tests/series/methods/test_round.py
index 88d5c428712dc..7ab19a05159a4 100644
--- a/pandas/tests/series/methods/test_round.py
+++ b/pandas/tests/series/methods/test_round.py
@@ -16,33 +16,41 @@ def test_round(self, datetime_series):
tm.assert_series_equal(result, expected)
assert result.name == datetime_series.name
- def test_round_numpy(self):
+ def test_round_numpy(self, any_float_allowed_nullable_dtype):
# See GH#12600
- ser = Series([1.53, 1.36, 0.06])
+ ser = Series([1.53, 1.36, 0.06], dtype=any_float_allowed_nullable_dtype)
out = np.round(ser, decimals=0)
- expected = Series([2.0, 1.0, 0.0])
+ expected = Series([2.0, 1.0, 0.0], dtype=any_float_allowed_nullable_dtype)
tm.assert_series_equal(out, expected)
msg = "the 'out' parameter is not supported"
with pytest.raises(ValueError, match=msg):
np.round(ser, decimals=0, out=ser)
- def test_round_numpy_with_nan(self):
+ def test_round_numpy_with_nan(self, any_float_allowed_nullable_dtype):
# See GH#14197
- ser = Series([1.53, np.nan, 0.06])
+ ser = Series([1.53, np.nan, 0.06], dtype=any_float_allowed_nullable_dtype)
with tm.assert_produces_warning(None):
result = ser.round()
- expected = Series([2.0, np.nan, 0.0])
+ expected = Series([2.0, np.nan, 0.0], dtype=any_float_allowed_nullable_dtype)
tm.assert_series_equal(result, expected)
- def test_round_builtin(self):
- ser = Series([1.123, 2.123, 3.123], index=range(3))
+ def test_round_builtin(self, any_float_allowed_nullable_dtype):
+ ser = Series(
+ [1.123, 2.123, 3.123],
+ index=range(3),
+ dtype=any_float_allowed_nullable_dtype,
+ )
result = round(ser)
- expected_rounded0 = Series([1.0, 2.0, 3.0], index=range(3))
+ expected_rounded0 = Series(
+ [1.0, 2.0, 3.0], index=range(3), dtype=any_float_allowed_nullable_dtype
+ )
tm.assert_series_equal(result, expected_rounded0)
decimals = 2
- expected_rounded = Series([1.12, 2.12, 3.12], index=range(3))
+ expected_rounded = Series(
+ [1.12, 2.12, 3.12], index=range(3), dtype=any_float_allowed_nullable_dtype
+ )
result = round(ser, decimals)
tm.assert_series_equal(result, expected_rounded)
| Code proposed in the staled PR #38866
- [x] closes #38844
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39751 | 2021-02-11T11:04:08Z | 2021-03-08T14:32:32Z | 2021-03-08T14:32:31Z | 2021-03-08T19:54:24Z |
DOC: added more and updated links in cheat sheet | diff --git a/doc/cheatsheet/Pandas_Cheat_Sheet.pdf b/doc/cheatsheet/Pandas_Cheat_Sheet.pdf
index 48da05d053b96..fb71f869ba22f 100644
Binary files a/doc/cheatsheet/Pandas_Cheat_Sheet.pdf and b/doc/cheatsheet/Pandas_Cheat_Sheet.pdf differ
diff --git a/doc/cheatsheet/Pandas_Cheat_Sheet.pptx b/doc/cheatsheet/Pandas_Cheat_Sheet.pptx
index 039b3898fa301..fd3d699d09f7b 100644
Binary files a/doc/cheatsheet/Pandas_Cheat_Sheet.pptx and b/doc/cheatsheet/Pandas_Cheat_Sheet.pptx differ
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39748 | 2021-02-11T07:52:03Z | 2021-02-11T15:30:45Z | 2021-02-11T15:30:45Z | 2021-02-11T15:37:04Z |
DOC: remove mention of MultiIndex from rolling docs | diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index bec6cfb375716..b5714dbcd9e91 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -732,7 +732,7 @@ class Window(BaseWindow):
Provide a window type. If ``None``, all points are evenly weighted.
See the notes below for further information.
on : str, optional
- For a DataFrame, a datetime-like column or MultiIndex level on which
+ For a DataFrame, a datetime-like column or Index level on which
to calculate the rolling window, rather than the DataFrame's index.
Provided integer column is ignored and excluded from result since
an integer index is not used to calculate the rolling window.
| - [x] closes #39686
Remove mention of MultiIndex from rolling docs. | https://api.github.com/repos/pandas-dev/pandas/pulls/39747 | 2021-02-11T07:24:38Z | 2021-02-11T13:46:32Z | 2021-02-11T13:46:32Z | 2021-02-18T04:55:03Z |
CI: share pandas setup steps | diff --git a/.github/actions/build_pandas/action.yml b/.github/actions/build_pandas/action.yml
new file mode 100644
index 0000000000000..d4777bcd1d079
--- /dev/null
+++ b/.github/actions/build_pandas/action.yml
@@ -0,0 +1,17 @@
+name: Build pandas
+description: Rebuilds the C extensions and installs pandas
+runs:
+ using: composite
+ steps:
+
+ - name: Environment Detail
+ run: |
+ conda info
+ conda list
+ shell: bash -l {0}
+
+ - name: Build Pandas
+ run: |
+ python setup.py build_ext -j 2
+ python -m pip install -e . --no-build-isolation --no-use-pep517
+ shell: bash -l {0}
diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.yml
new file mode 100644
index 0000000000000..9ef00e7a85a6f
--- /dev/null
+++ b/.github/actions/setup/action.yml
@@ -0,0 +1,12 @@
+name: Set up pandas
+description: Runs all the setup steps required to have a built pandas ready to use
+runs:
+ using: composite
+ steps:
+ - name: Setting conda path
+ run: echo "${HOME}/miniconda3/bin" >> $GITHUB_PATH
+ shell: bash -l {0}
+
+ - name: Setup environment and build pandas
+ run: ci/setup_env.sh
+ shell: bash -l {0}
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b551e7ded0178..961620b54405f 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -41,15 +41,8 @@ jobs:
environment-file: ${{ env.ENV_FILE }}
use-only-tar-bz2: true
- - name: Environment Detail
- run: |
- conda info
- conda list
-
- name: Build Pandas
- run: |
- python setup.py build_ext -j 2
- python -m pip install -e . --no-build-isolation --no-use-pep517
+ uses: ./.github/actions/build_pandas
- name: Linting
run: ci/code_checks.sh lint
@@ -100,14 +93,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- - name: Setting conda path
- run: echo "${HOME}/miniconda3/bin" >> $GITHUB_PATH
-
- name: Checkout
uses: actions/checkout@v1
- - name: Setup environment and build pandas
- run: ci/setup_env.sh
+ - name: Set up pandas
+ uses: ./.github/actions/setup
- name: Build website
run: |
@@ -144,14 +134,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- - name: Setting conda path
- run: echo "${HOME}/miniconda3/bin" >> $GITHUB_PATH
-
- name: Checkout
uses: actions/checkout@v1
- - name: Setup environment and build pandas
- run: ci/setup_env.sh
+ - name: Set up pandas
+ uses: ./.github/actions/setup
- name: Run tests
run: |
diff --git a/.github/workflows/database.yml b/.github/workflows/database.yml
index c2f332cc5454a..f3ccd78266ba6 100644
--- a/.github/workflows/database.yml
+++ b/.github/workflows/database.yml
@@ -72,15 +72,8 @@ jobs:
environment-file: ${{ env.ENV_FILE }}
use-only-tar-bz2: true
- - name: Environment Detail
- run: |
- conda info
- conda list
-
- name: Build Pandas
- run: |
- python setup.py build_ext -j 2
- python -m pip install -e . --no-build-isolation --no-use-pep517
+ uses: ./.github/actions/build_pandas
- name: Test
run: ci/run_tests.sh
@@ -158,15 +151,8 @@ jobs:
environment-file: ${{ env.ENV_FILE }}
use-only-tar-bz2: true
- - name: Environment Detail
- run: |
- conda info
- conda list
-
- name: Build Pandas
- run: |
- python setup.py build_ext -j 2
- python -m pip install -e . --no-build-isolation --no-use-pep517
+ uses: ./.github/actions/build_pandas
- name: Test
run: ci/run_tests.sh
| Split out from https://github.com/pandas-dev/pandas/pull/39392. Just a refactor; puts redundant setup steps in a shared place.
To be honest, I don't actually understand why different GitHub Actions set up pandas in different ways, so didn't change that here.
The `uses` calls can be moved into the composite actions once https://github.com/actions/runner/issues/862 is complete, DRYing it up even more.
- [ ] ~~closes #xxxx~~
- [ ] tests ~~added /~~ passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] ~~whatsnew entry~~
| https://api.github.com/repos/pandas-dev/pandas/pulls/39745 | 2021-02-11T04:47:39Z | 2021-02-11T13:42:45Z | 2021-02-11T13:42:45Z | 2021-02-11T13:42:49Z |
CI: fix reference to take_1d() | diff --git a/asv_bench/benchmarks/gil.py b/asv_bench/benchmarks/gil.py
index 5d9070de92ec7..47523005a877f 100644
--- a/asv_bench/benchmarks/gil.py
+++ b/asv_bench/benchmarks/gil.py
@@ -1,7 +1,7 @@
import numpy as np
from pandas import DataFrame, Series, date_range, factorize, read_csv
-from pandas.core.algorithms import take_1d
+from pandas.core.algorithms import take_nd
from .pandas_vb_common import tm
@@ -110,7 +110,7 @@ def setup(self, dtype):
@test_parallel(num_threads=2)
def parallel_take1d():
- take_1d(df["col"].values, indexer)
+ take_nd(df["col"].values, indexer)
self.parallel_take1d = parallel_take1d
| Fix for issue noted by @lithomas1 in https://github.com/pandas-dev/pandas/pull/39731#issuecomment-777179836, which is causing the Benchmarks to fail.
- [ ] ~~closes #xxxx~~
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] ~~whatsnew entry~~
| https://api.github.com/repos/pandas-dev/pandas/pulls/39744 | 2021-02-11T04:12:38Z | 2021-02-11T07:43:30Z | 2021-02-11T07:43:30Z | 2021-02-11T17:27:05Z |
BUG: maybe_promote with dt64tz and mismatched NA | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 18f1bba6ebfb8..e27c519304e2e 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -24,7 +24,7 @@
import numpy as np
-from pandas._libs import lib, missing as libmissing, tslib
+from pandas._libs import lib, tslib
from pandas._libs.tslibs import (
NaT,
OutOfBoundsDatetime,
@@ -86,7 +86,12 @@
ABCSeries,
)
from pandas.core.dtypes.inference import is_list_like
-from pandas.core.dtypes.missing import is_valid_na_for_dtype, isna, notna
+from pandas.core.dtypes.missing import (
+ is_valid_na_for_dtype,
+ isna,
+ na_value_for_dtype,
+ notna,
+)
if TYPE_CHECKING:
from pandas import Series
@@ -529,16 +534,26 @@ def maybe_promote(dtype: np.dtype, fill_value=np.nan):
dtype = np.dtype(object)
return dtype, fill_value
+ kinds = ["i", "u", "f", "c", "m", "M"]
+ if is_valid_na_for_dtype(fill_value, dtype) and dtype.kind in kinds:
+ dtype = ensure_dtype_can_hold_na(dtype)
+ fv = na_value_for_dtype(dtype)
+ return dtype, fv
+
+ elif isna(fill_value):
+ dtype = np.dtype(object)
+ if fill_value is None:
+ # but we retain e.g. pd.NA
+ fill_value = np.nan
+ return dtype, fill_value
+
# returns tuple of (dtype, fill_value)
if issubclass(dtype.type, np.datetime64):
if isinstance(fill_value, datetime) and fill_value.tzinfo is not None:
# Trying to insert tzaware into tznaive, have to cast to object
dtype = np.dtype(np.object_)
- elif is_integer(fill_value) or (is_float(fill_value) and not isna(fill_value)):
+ elif is_integer(fill_value) or is_float(fill_value):
dtype = np.dtype(np.object_)
- elif is_valid_na_for_dtype(fill_value, dtype):
- # e.g. pd.NA, which is not accepted by Timestamp constructor
- fill_value = np.datetime64("NaT", "ns")
else:
try:
fill_value = Timestamp(fill_value).to_datetime64()
@@ -547,14 +562,11 @@ def maybe_promote(dtype: np.dtype, fill_value=np.nan):
elif issubclass(dtype.type, np.timedelta64):
if (
is_integer(fill_value)
- or (is_float(fill_value) and not np.isnan(fill_value))
+ or is_float(fill_value)
or isinstance(fill_value, str)
):
# TODO: What about str that can be a timedelta?
dtype = np.dtype(np.object_)
- elif is_valid_na_for_dtype(fill_value, dtype):
- # e.g pd.NA, which is not accepted by the Timedelta constructor
- fill_value = np.timedelta64("NaT", "ns")
else:
try:
fv = Timedelta(fill_value)
@@ -615,17 +627,6 @@ def maybe_promote(dtype: np.dtype, fill_value=np.nan):
# e.g. mst is np.complex128 and dtype is np.complex64
dtype = mst
- elif fill_value is None or fill_value is libmissing.NA:
- # Note: we already excluded dt64/td64 dtypes above
- if is_float_dtype(dtype) or is_complex_dtype(dtype):
- fill_value = np.nan
- elif is_integer_dtype(dtype):
- dtype = np.dtype(np.float64)
- fill_value = np.nan
- else:
- dtype = np.dtype(np.object_)
- if fill_value is not libmissing.NA:
- fill_value = np.nan
else:
dtype = np.dtype(np.object_)
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39743 | 2021-02-11T03:13:43Z | 2021-02-12T17:52:03Z | 2021-02-12T17:52:03Z | 2021-02-12T17:54:31Z |
BUG: Timedelta input string with only symbols and no digits raises an error (GH39710) | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index a3a9a4c5eda08..0ef4361c5fb53 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -292,7 +292,7 @@ Timedelta
^^^^^^^^^
- Bug in constructing :class:`Timedelta` from ``np.timedelta64`` objects with non-nanosecond units that are out of bounds for ``timedelta64[ns]`` (:issue:`38965`)
- Bug in constructing a :class:`TimedeltaIndex` incorrectly accepting ``np.datetime64("NaT")`` objects (:issue:`39462`)
--
+- Bug in constructing :class:`Timedelta` from input string with only symbols and no digits failed to raise an error (:issue:`39710`)
Timezones
^^^^^^^^^
diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx
index 748a4c27e64ad..d661806a496d2 100644
--- a/pandas/_libs/tslibs/timedeltas.pyx
+++ b/pandas/_libs/tslibs/timedeltas.pyx
@@ -496,6 +496,10 @@ cdef inline int64_t parse_timedelta_string(str ts) except? -1:
else:
raise ValueError("unit abbreviation w/o a number")
+ # we only have symbols and no numbers
+ elif len(number) == 0:
+ raise ValueError("symbols w/o a number")
+
# treat as nanoseconds
# but only if we don't have anything else
else:
diff --git a/pandas/tests/scalar/timedelta/test_constructors.py b/pandas/tests/scalar/timedelta/test_constructors.py
index 64d5a5e9b3fff..3cc5bfaeb73e8 100644
--- a/pandas/tests/scalar/timedelta/test_constructors.py
+++ b/pandas/tests/scalar/timedelta/test_constructors.py
@@ -1,4 +1,5 @@
from datetime import timedelta
+from itertools import product
import numpy as np
import pytest
@@ -337,3 +338,22 @@ def test_string_with_unit(constructor, value, unit, expectation):
exp, match = expectation
with pytest.raises(exp, match=match):
_ = constructor(value, unit=unit)
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ "".join(elements)
+ for repetition in (1, 2)
+ for elements in product("+-, ", repeat=repetition)
+ ],
+)
+def test_string_without_numbers(value):
+ # GH39710 Timedelta input string with only symbols and no digits raises an error
+ msg = (
+ "symbols w/o a number"
+ if value != "--"
+ else "only leading negative signs are allowed"
+ )
+ with pytest.raises(ValueError, match=msg):
+ Timedelta(value)
| - [x] closes #39710
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39737 | 2021-02-10T21:52:55Z | 2021-02-10T23:47:34Z | 2021-02-10T23:47:33Z | 2021-02-10T23:47:37Z |
CLN: remove ndarray cases from maybe_promote | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 77c7db6a07698..5d9b51238c255 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -520,28 +520,15 @@ def maybe_promote(dtype: DtypeObj, fill_value=np.nan):
ValueError
If fill_value is a non-scalar and dtype is not object.
"""
- if not is_scalar(fill_value) and not is_object_dtype(dtype):
+ if not is_scalar(fill_value):
# with object dtype there is nothing to promote, and the user can
# pass pretty much any weird fill_value they like
- raise ValueError("fill_value must be a scalar")
-
- # if we passed an array here, determine the fill value by dtype
- if isinstance(fill_value, np.ndarray):
- if issubclass(fill_value.dtype.type, (np.datetime64, np.timedelta64)):
- fill_value = fill_value.dtype.type("NaT", "ns")
- else:
-
- # we need to change to object type as our
- # fill_value is of object type
- if fill_value.dtype == np.object_:
- dtype = np.dtype(np.object_)
- fill_value = np.nan
-
- if dtype == np.object_ or dtype.kind in ["U", "S"]:
- # We treat string-like dtypes as object, and _always_ fill
- # with np.nan
- fill_value = np.nan
- dtype = np.dtype(np.object_)
+ if not is_object_dtype(dtype):
+ # with object dtype there is nothing to promote, and the user can
+ # pass pretty much any weird fill_value they like
+ raise ValueError("fill_value must be a scalar")
+ dtype = np.dtype(object)
+ return dtype, fill_value
# returns tuple of (dtype, fill_value)
if issubclass(dtype.type, np.datetime64):
diff --git a/pandas/tests/dtypes/cast/test_promote.py b/pandas/tests/dtypes/cast/test_promote.py
index 89b45890458c5..16caf935652cb 100644
--- a/pandas/tests/dtypes/cast/test_promote.py
+++ b/pandas/tests/dtypes/cast/test_promote.py
@@ -605,31 +605,3 @@ def test_maybe_promote_any_numpy_dtype_with_na(any_numpy_dtype_reduced, nulls_fi
exp_val_for_scalar = np.nan
_check_promote(dtype, fill_value, expected_dtype, exp_val_for_scalar)
-
-
-@pytest.mark.parametrize("dim", [0, 2, 3])
-def test_maybe_promote_dimensions(any_numpy_dtype_reduced, dim):
- dtype = np.dtype(any_numpy_dtype_reduced)
-
- # create 0-dim array of given dtype; casts "1" to correct dtype
- fill_array = np.array(1, dtype=dtype)
-
- # expand to desired dimension:
- for _ in range(dim):
- fill_array = np.expand_dims(fill_array, 0)
-
- if dtype != object:
- # test against 1-dimensional case
- with pytest.raises(ValueError, match="fill_value must be a scalar"):
- maybe_promote(dtype, np.array([1], dtype=dtype))
-
- with pytest.raises(ValueError, match="fill_value must be a scalar"):
- maybe_promote(dtype, fill_array)
-
- else:
- expected_dtype, expected_missing_value = maybe_promote(
- dtype, np.array([1], dtype=dtype)
- )
- result_dtype, result_missing_value = maybe_promote(dtype, fill_array)
- assert result_dtype == expected_dtype
- _assert_match(result_missing_value, expected_missing_value)
| AFAICT this is a relic of using maybe_promote where we should use infer_dtype_from + find_common_type | https://api.github.com/repos/pandas-dev/pandas/pulls/39736 | 2021-02-10T21:49:58Z | 2021-02-10T23:09:51Z | 2021-02-10T23:09:51Z | 2021-02-10T23:10:49Z |
[ArrayManager] Indexing - implement iset | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2d8f6468aca83..aec19e27a33e2 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -153,3 +153,9 @@ jobs:
run: |
source activate pandas-dev
pytest pandas/tests/frame/methods --array-manager
+
+ # indexing iset related (temporary since other tests don't pass yet)
+ pytest pandas/tests/frame/indexing/test_indexing.py::TestDataFrameIndexing::test_setitem_multi_index --array-manager
+ pytest pandas/tests/frame/indexing/test_setitem.py::TestDataFrameSetItem::test_setitem_listlike_indexer_duplicate_columns --array-manager
+ pytest pandas/tests/indexing/multiindex/test_setitem.py::TestMultiIndexSetItem::test_astype_assignment_with_dups --array-manager
+ pytest pandas/tests/indexing/multiindex/test_setitem.py::TestMultiIndexSetItem::test_frame_setitem_multi_column --array-manager
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 63d238da12101..782539c2ba4b2 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -9723,12 +9723,3 @@ def _reindex_for_setitem(value: FrameOrSeriesUnion, index: Index) -> ArrayLike:
"incompatible index of inserted column with frame index"
) from err
return reindexed_value
-
-
-def _maybe_atleast_2d(value):
- # TODO(EA2D): not needed with 2D EAs
-
- if is_extension_array_dtype(value):
- return value
-
- return np.atleast_2d(np.asarray(value))
diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py
index a8493e647f39a..083f32488acd4 100644
--- a/pandas/core/internals/array_manager.py
+++ b/pandas/core/internals/array_manager.py
@@ -659,24 +659,53 @@ def idelete(self, indexer):
def iset(self, loc: Union[int, slice, np.ndarray], value):
"""
- Set new item in-place. Does not consolidate. Adds new Block if not
- contained in the current set of items
+ Set new column(s).
+
+ This changes the ArrayManager in-place, but replaces (an) existing
+ column(s), not changing column values in-place).
+
+ Parameters
+ ----------
+ loc : integer, slice or boolean mask
+ Positional location (already bounds checked)
+ value : array-like
"""
+ # single column -> single integer index
if lib.is_integer(loc):
- # TODO normalize array -> this should in theory not be needed?
+ # TODO the extract array should in theory not be needed?
value = extract_array(value, extract_numpy=True)
+
+ # TODO can we avoid needing to unpack this here? That means converting
+ # DataFrame into 1D array when loc is an integer
if isinstance(value, np.ndarray) and value.ndim == 2:
+ assert value.shape[1] == 1
value = value[0, :]
assert isinstance(value, (np.ndarray, ExtensionArray))
- # value = np.asarray(value)
- # assert isinstance(value, np.ndarray)
+ assert value.ndim == 1
assert len(value) == len(self._axes[0])
self.arrays[loc] = value
return
- # TODO
- raise Exception
+ # multiple columns -> convert slice or array to integer indices
+ elif isinstance(loc, slice):
+ indices = range(
+ loc.start if loc.start is not None else 0,
+ loc.stop if loc.stop is not None else self.shape_proper[1],
+ loc.step if loc.step is not None else 1,
+ )
+ else:
+ assert isinstance(loc, np.ndarray)
+ assert loc.dtype == "bool"
+ indices = np.nonzero(loc)[0]
+
+ assert value.ndim == 2
+ assert value.shape[0] == len(self._axes[0])
+
+ for value_idx, mgr_idx in enumerate(indices):
+ value_arr = value[:, value_idx]
+ self.arrays[mgr_idx] = value_arr
+ return
def insert(self, loc: int, item: Hashable, value, allow_duplicates: bool = False):
"""
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 1c45b39ba990a..ccac2696b34c5 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -1140,8 +1140,7 @@ def insert(self, loc: int, item: Hashable, value, allow_duplicates: bool = False
if value.ndim == 2:
value = value.T
-
- if value.ndim == self.ndim - 1 and not is_extension_array_dtype(value.dtype):
+ elif value.ndim == self.ndim - 1 and not is_extension_array_dtype(value.dtype):
# TODO(EA2D): special case not needed with 2D EAs
value = safe_reshape(value, (1,) + value.shape)
| xref https://github.com/pandas-dev/pandas/issues/39146/, follow-up on https://github.com/pandas-dev/pandas/pull/39722 | https://api.github.com/repos/pandas-dev/pandas/pulls/39734 | 2021-02-10T20:58:42Z | 2021-02-15T19:06:52Z | 2021-02-15T19:06:52Z | 2021-02-15T19:06:55Z |
REF: remove take_1d alias of take_nd | diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py
index 024bfb02fe09d..6b67459c47c38 100644
--- a/pandas/_testing/asserters.py
+++ b/pandas/_testing/asserters.py
@@ -29,7 +29,7 @@
Series,
TimedeltaIndex,
)
-from pandas.core.algorithms import safe_sort, take_1d
+from pandas.core.algorithms import safe_sort, take_nd
from pandas.core.arrays import (
DatetimeArray,
ExtensionArray,
@@ -309,7 +309,7 @@ def _get_ilevel_values(index, level):
# accept level number only
unique = index.levels[level]
level_codes = index.codes[level]
- filled = take_1d(unique._values, level_codes, fill_value=unique._na_value)
+ filled = take_nd(unique._values, level_codes, fill_value=unique._na_value)
return unique._shallow_copy(filled, name=index.names[level])
if check_less_precise is not no_default:
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index cdbef673643e8..1c92629a40ddc 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -1652,7 +1652,7 @@ def take(arr, indices, axis: int = 0, allow_fill: bool = False, fill_value=None)
if allow_fill:
# Pandas style, -1 means NA
validate_indices(indices, arr.shape[axis])
- result = take_1d(
+ result = take_nd(
arr, indices, axis=axis, allow_fill=True, fill_value=fill_value
)
else:
@@ -1773,9 +1773,6 @@ def take_nd(
return out
-take_1d = take_nd
-
-
def take_2d_multi(arr, indexer, fill_value=np.nan):
"""
Specialized Cython take which sets NaN values in one pass.
@@ -2159,9 +2156,9 @@ def safe_sort(
sorter = ensure_platform_int(t.lookup(ordered))
if na_sentinel == -1:
- # take_1d is faster, but only works for na_sentinels of -1
+ # take_nd is faster, but only works for na_sentinels of -1
order2 = sorter.argsort()
- new_codes = take_1d(order2, codes, fill_value=-1)
+ new_codes = take_nd(order2, codes, fill_value=-1)
if verify:
mask = (codes < -len(values)) | (codes >= len(values))
else:
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 99777bc2f169e..0d1465da7297e 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -59,7 +59,7 @@
from pandas.core import ops
from pandas.core.accessor import PandasDelegate, delegate_names
import pandas.core.algorithms as algorithms
-from pandas.core.algorithms import factorize, get_data_algo, take_1d, unique1d
+from pandas.core.algorithms import factorize, get_data_algo, take_nd, unique1d
from pandas.core.arrays._mixins import NDArrayBackedExtensionArray
from pandas.core.base import ExtensionArray, NoNewAttributesMixin, PandasObject
import pandas.core.common as com
@@ -475,7 +475,7 @@ def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike:
msg = f"Cannot cast {self.categories.dtype} dtype to {dtype}"
raise ValueError(msg)
- result = take_1d(new_cats, libalgos.ensure_platform_int(self._codes))
+ result = take_nd(new_cats, libalgos.ensure_platform_int(self._codes))
return result
@@ -1310,7 +1310,7 @@ def __array__(self, dtype: Optional[NpDtype] = None) -> np.ndarray:
if dtype==None (default), the same dtype as
categorical.categories.dtype.
"""
- ret = take_1d(self.categories._values, self._codes)
+ ret = take_nd(self.categories._values, self._codes)
if dtype and not is_dtype_equal(dtype, self.categories.dtype):
return np.asarray(ret, dtype)
# When we're a Categorical[ExtensionArray], like Interval,
@@ -2349,7 +2349,7 @@ def _str_map(self, f, na_value=np.nan, dtype=np.dtype(object)):
categories = self.categories
codes = self.codes
result = PandasArray(categories.to_numpy())._str_map(f, na_value, dtype)
- return take_1d(result, codes, fill_value=na_value)
+ return take_nd(result, codes, fill_value=na_value)
def _str_get_dummies(self, sep="|"):
# sep may not be in categories. Just bail on this.
@@ -2600,7 +2600,7 @@ def recode_for_categories(
indexer = coerce_indexer_dtype(
new_categories.get_indexer(old_categories), new_categories
)
- new_codes = take_1d(indexer, codes, fill_value=-1)
+ new_codes = take_nd(indexer, codes, fill_value=-1)
return new_codes
diff --git a/pandas/core/base.py b/pandas/core/base.py
index 09e2e80f45b3d..da8ed8a59f981 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -926,7 +926,7 @@ def _map_values(self, mapper, na_action=None):
values = self._values
indexer = mapper.index.get_indexer(values)
- new_values = algorithms.take_1d(mapper._values, indexer)
+ new_values = algorithms.take_nd(mapper._values, indexer)
return new_values
diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py
index 5b46bee96d4b3..3bded4dd2834b 100644
--- a/pandas/core/dtypes/concat.py
+++ b/pandas/core/dtypes/concat.py
@@ -272,9 +272,9 @@ def _maybe_unwrap(x):
categories = categories.sort_values()
indexer = categories.get_indexer(first.categories)
- from pandas.core.algorithms import take_1d
+ from pandas.core.algorithms import take_nd
- new_codes = take_1d(indexer, new_codes, fill_value=-1)
+ new_codes = take_nd(indexer, new_codes, fill_value=-1)
elif ignore_order or all(not c.ordered for c in to_union):
# different categories - union and recode
cats = first.categories.append([c.categories for c in to_union[1:]])
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 04e9eb039c249..a7297923f1034 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -565,7 +565,7 @@ def _transform_fast(self, result) -> Series:
"""
ids, _, ngroup = self.grouper.group_info
result = result.reindex(self.grouper.result_index, copy=False)
- out = algorithms.take_1d(result._values, ids)
+ out = algorithms.take_nd(result._values, ids)
return self.obj._constructor(out, index=self.obj.index, name=self.obj.name)
def filter(self, func, dropna=True, *args, **kwargs):
@@ -1413,7 +1413,7 @@ def _transform_fast(self, result: DataFrame) -> DataFrame:
ids, _, ngroup = self.grouper.group_info
result = result.reindex(self.grouper.result_index, copy=False)
output = [
- algorithms.take_1d(result.iloc[:, i].values, ids)
+ algorithms.take_nd(result.iloc[:, i].values, ids)
for i, _ in enumerate(result.columns)
]
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index 9841b63029f17..5b2d9ce15ac89 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -42,7 +42,7 @@
)
from pandas.core.dtypes.dtypes import IntervalDtype
-from pandas.core.algorithms import take_1d, unique
+from pandas.core.algorithms import take_nd, unique
from pandas.core.arrays.interval import IntervalArray, _interval_shared_docs
import pandas.core.common as com
from pandas.core.indexers import is_valid_positional_slice
@@ -671,9 +671,9 @@ def _get_indexer(
indexer = np.where(left_indexer == right_indexer, left_indexer, -1)
elif is_categorical_dtype(target.dtype):
target = cast("CategoricalIndex", target)
- # get an indexer for unique categories then propagate to codes via take_1d
+ # get an indexer for unique categories then propagate to codes via take_nd
categories_indexer = self.get_indexer(target.categories)
- indexer = take_1d(categories_indexer, target.codes, fill_value=-1)
+ indexer = take_nd(categories_indexer, target.codes, fill_value=-1)
elif not is_object_dtype(target):
# homogeneous scalar index: use IntervalTree
target = self._maybe_convert_i8(target)
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 934780eb9acef..f5e32f53c3c54 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -1343,7 +1343,7 @@ def format(
# weird all NA case
formatted = [
pprint_thing(na if isna(x) else x, escape_chars=("\t", "\r", "\n"))
- for x in algos.take_1d(lev._values, level_codes)
+ for x in algos.take_nd(lev._values, level_codes)
]
stringified_levels.append(formatted)
@@ -1632,7 +1632,7 @@ def _get_level_values(self, level, unique=False):
name = self._names[level]
if unique:
level_codes = algos.unique(level_codes)
- filled = algos.take_1d(lev._values, level_codes, fill_value=lev._na_value)
+ filled = algos.take_nd(lev._values, level_codes, fill_value=lev._na_value)
return lev._shallow_copy(filled, name=name)
def get_level_values(self, level):
@@ -1916,7 +1916,7 @@ def _sort_levels_monotonic(self):
# indexer to reorder the level codes
indexer = ensure_int64(indexer)
ri = lib.get_reverse_indexer(indexer, len(indexer))
- level_codes = algos.take_1d(ri, level_codes)
+ level_codes = algos.take_nd(ri, level_codes)
new_levels.append(lev)
new_codes.append(level_codes)
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py
index 3dcfa85ed5c08..cc8ff40f071e0 100644
--- a/pandas/core/internals/concat.py
+++ b/pandas/core/internals/concat.py
@@ -139,8 +139,8 @@ def _get_mgr_concatenation_plan(mgr: BlockManager, indexers: Dict[int, np.ndarra
if 0 in indexers:
ax0_indexer = indexers.pop(0)
- blknos = algos.take_1d(mgr.blknos, ax0_indexer, fill_value=-1)
- blklocs = algos.take_1d(mgr.blklocs, ax0_indexer, fill_value=-1)
+ blknos = algos.take_nd(mgr.blknos, ax0_indexer, fill_value=-1)
+ blklocs = algos.take_nd(mgr.blklocs, ax0_indexer, fill_value=-1)
else:
if mgr.is_single_block:
diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py
index f864f1cddfe7a..878a5c9aafe5d 100644
--- a/pandas/core/internals/construction.py
+++ b/pandas/core/internals/construction.py
@@ -645,7 +645,7 @@ def _list_of_series_to_arrays(
indexer = indexer_cache[id(index)] = index.get_indexer(columns)
values = extract_array(s, extract_numpy=True)
- aligned_values.append(algorithms.take_1d(values, indexer))
+ aligned_values.append(algorithms.take_nd(values, indexer))
content = np.vstack(aligned_values)
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 7084fa4013900..1c45b39ba990a 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -255,7 +255,7 @@ def items(self) -> Index:
def get_dtypes(self):
dtypes = np.array([blk.dtype for blk in self.blocks])
- return algos.take_1d(dtypes, self.blknos, allow_fill=False)
+ return algos.take_nd(dtypes, self.blknos, allow_fill=False)
def __getstate__(self):
block_values = [b.values for b in self.blocks]
@@ -1308,10 +1308,10 @@ def _slice_take_blocks_ax0(
blknos = self.blknos[slobj]
blklocs = self.blklocs[slobj]
else:
- blknos = algos.take_1d(
+ blknos = algos.take_nd(
self.blknos, slobj, fill_value=-1, allow_fill=allow_fill
)
- blklocs = algos.take_1d(
+ blklocs = algos.take_nd(
self.blklocs, slobj, fill_value=-1, allow_fill=allow_fill
)
diff --git a/pandas/core/resample.py b/pandas/core/resample.py
index 34b7838d2280c..68f791ac0a837 100644
--- a/pandas/core/resample.py
+++ b/pandas/core/resample.py
@@ -1713,7 +1713,7 @@ def _get_period_bins(self, ax: PeriodIndex):
def _take_new_index(obj, indexer, new_index, axis=0):
if isinstance(obj, ABCSeries):
- new_values = algos.take_1d(obj._values, indexer)
+ new_values = algos.take_nd(obj._values, indexer)
return obj._constructor(new_values, index=new_index, name=obj.name)
elif isinstance(obj, ABCDataFrame):
if axis == 1:
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index a3eef92bacfad..8704d757c3289 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -852,13 +852,13 @@ def _maybe_add_join_keys(self, result, left_indexer, right_indexer):
lvals = result[name]._values
else:
lfill = na_value_for_dtype(take_left.dtype)
- lvals = algos.take_1d(take_left, left_indexer, fill_value=lfill)
+ lvals = algos.take_nd(take_left, left_indexer, fill_value=lfill)
if take_right is None:
rvals = result[name]._values
else:
rfill = na_value_for_dtype(take_right.dtype)
- rvals = algos.take_1d(take_right, right_indexer, fill_value=rfill)
+ rvals = algos.take_nd(take_right, right_indexer, fill_value=rfill)
# if we have an all missing left_indexer
# make sure to just use the right values or vice-versa
diff --git a/pandas/core/series.py b/pandas/core/series.py
index b8d6deb353cd2..3b8ee46cc480f 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -4155,7 +4155,7 @@ def _reindex_indexer(self, new_index, indexer, copy):
return self.copy()
return self
- new_values = algorithms.take_1d(
+ new_values = algorithms.take_nd(
self._values, indexer, allow_fill=True, fill_value=None
)
return self._constructor(new_values, index=new_index)
diff --git a/pandas/tests/test_take.py b/pandas/tests/test_take.py
index 9f0632917037c..c2668844a5f14 100644
--- a/pandas/tests/test_take.py
+++ b/pandas/tests/test_take.py
@@ -80,7 +80,7 @@ def test_1d_with_out(self, dtype_can_hold_na, writeable):
indexer = [2, 1, 0, 1]
out = np.empty(4, dtype=dtype)
- algos.take_1d(data, indexer, out=out)
+ algos.take_nd(data, indexer, out=out)
expected = data.take(indexer)
tm.assert_almost_equal(out, expected)
@@ -89,13 +89,13 @@ def test_1d_with_out(self, dtype_can_hold_na, writeable):
out = np.empty(4, dtype=dtype)
if can_hold_na:
- algos.take_1d(data, indexer, out=out)
+ algos.take_nd(data, indexer, out=out)
expected = data.take(indexer)
expected[3] = np.nan
tm.assert_almost_equal(out, expected)
else:
with pytest.raises(TypeError, match=self.fill_error):
- algos.take_1d(data, indexer, out=out)
+ algos.take_nd(data, indexer, out=out)
# No Exception otherwise.
data.take(indexer, out=out)
@@ -105,14 +105,14 @@ def test_1d_fill_nonna(self, dtype_fill_out_dtype):
data = np.random.randint(0, 2, 4).astype(dtype)
indexer = [2, 1, 0, -1]
- result = algos.take_1d(data, indexer, fill_value=fill_value)
+ result = algos.take_nd(data, indexer, fill_value=fill_value)
assert (result[[0, 1, 2]] == data[[2, 1, 0]]).all()
assert result[3] == fill_value
assert result.dtype == out_dtype
indexer = [2, 1, 0, 1]
- result = algos.take_1d(data, indexer, fill_value=fill_value)
+ result = algos.take_nd(data, indexer, fill_value=fill_value)
assert (result[[0, 1, 2, 3]] == data[indexer]).all()
assert result.dtype == dtype
@@ -269,7 +269,7 @@ def test_1d_other_dtypes(self):
arr = np.random.randn(10).astype(np.float32)
indexer = [1, 2, 3, -1]
- result = algos.take_1d(arr, indexer)
+ result = algos.take_nd(arr, indexer)
expected = arr.take(indexer)
expected[-1] = np.nan
tm.assert_almost_equal(result, expected)
@@ -294,11 +294,11 @@ def test_2d_other_dtypes(self):
def test_1d_bool(self):
arr = np.array([0, 1, 0], dtype=bool)
- result = algos.take_1d(arr, [0, 2, 2, 1])
+ result = algos.take_nd(arr, [0, 2, 2, 1])
expected = arr.take([0, 2, 2, 1])
tm.assert_numpy_array_equal(result, expected)
- result = algos.take_1d(arr, [0, 2, -1])
+ result = algos.take_nd(arr, [0, 2, -1])
assert result.dtype == np.object_
def test_2d_bool(self):
| @jreback as discussed in https://github.com/pandas-dev/pandas/pull/39692
Since this is just an alias, this is certainly fine in theory. Although now doing it, I think there is still *some* value of the alias to signal that it is taking a 1D array which can provide useful context when *reading* code that uses this. | https://api.github.com/repos/pandas-dev/pandas/pulls/39731 | 2021-02-10T19:16:06Z | 2021-02-10T23:48:46Z | 2021-02-10T23:48:46Z | 2021-02-11T07:43:02Z |
TYP: MultiIndex | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 1d633aec79e93..63d238da12101 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4821,7 +4821,10 @@ def set_index(
names.extend(col.names)
elif isinstance(col, (Index, Series)):
# if Index then not MultiIndex (treated above)
- arrays.append(col)
+
+ # error: Argument 1 to "append" of "list" has incompatible
+ # type "Union[Index, Series]"; expected "Index" [arg-type]
+ arrays.append(col) # type:ignore[arg-type]
names.append(col.name)
elif isinstance(col, (list, np.ndarray)):
arrays.append(col)
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 925e2e3feb4e8..9e6c89345d76a 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -5766,7 +5766,7 @@ def insert(self, loc: int, item):
idx = np.concatenate((arr[:loc], item, arr[loc:]))
return Index(idx, name=self.name)
- def drop(self, labels, errors: str_t = "raise"):
+ def drop(self: _IndexT, labels, errors: str_t = "raise") -> _IndexT:
"""
Make new Index with passed list of labels deleted.
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 934780eb9acef..fafe2ffe5a928 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -13,6 +13,7 @@
Sequence,
Tuple,
Union,
+ cast,
)
import warnings
@@ -71,7 +72,7 @@
)
if TYPE_CHECKING:
- from pandas import Series
+ from pandas import CategoricalIndex, Series
_index_doc_kwargs = dict(ibase._index_doc_kwargs)
_index_doc_kwargs.update(
@@ -478,7 +479,7 @@ def from_tuples(
tuples,
sortorder: Optional[int] = None,
names: Optional[Sequence[Hashable]] = None,
- ):
+ ) -> MultiIndex:
"""
Convert list of tuples to MultiIndex.
@@ -537,7 +538,9 @@ def from_tuples(
return cls.from_arrays(arrays, sortorder=sortorder, names=names)
@classmethod
- def from_product(cls, iterables, sortorder=None, names=lib.no_default):
+ def from_product(
+ cls, iterables, sortorder=None, names=lib.no_default
+ ) -> MultiIndex:
"""
Make a MultiIndex from the cartesian product of multiple iterables.
@@ -596,7 +599,7 @@ def from_product(cls, iterables, sortorder=None, names=lib.no_default):
return cls(levels, codes, sortorder=sortorder, names=names)
@classmethod
- def from_frame(cls, df, sortorder=None, names=None):
+ def from_frame(cls, df, sortorder=None, names=None) -> MultiIndex:
"""
Make a MultiIndex from a DataFrame.
@@ -664,14 +667,15 @@ def from_frame(cls, df, sortorder=None, names=None):
# --------------------------------------------------------------------
@cache_readonly
- def _values(self):
+ def _values(self) -> np.ndarray:
# We override here, since our parent uses _data, which we don't use.
values = []
for i in range(self.nlevels):
vals = self._get_level_values(i)
if is_categorical_dtype(vals.dtype):
- vals = vals._internal_get_values()
+ vals = cast("CategoricalIndex", vals)
+ vals = vals._data._internal_get_values()
if isinstance(vals.dtype, ExtensionDtype) or isinstance(
vals, (ABCDatetimeIndex, ABCTimedeltaIndex)
):
@@ -683,7 +687,7 @@ def _values(self):
return arr
@property
- def values(self):
+ def values(self) -> np.ndarray:
return self._values
@property
@@ -782,7 +786,9 @@ def _set_levels(
self._reset_cache()
- def set_levels(self, levels, level=None, inplace=None, verify_integrity=True):
+ def set_levels(
+ self, levels, level=None, inplace=None, verify_integrity: bool = True
+ ):
"""
Set new levels on MultiIndex. Defaults to returning new index.
@@ -909,7 +915,7 @@ def nlevels(self) -> int:
return len(self._levels)
@property
- def levshape(self):
+ def levshape(self) -> Shape:
"""
A tuple with the length of each level.
@@ -967,7 +973,7 @@ def _set_codes(
self._reset_cache()
- def set_codes(self, codes, level=None, inplace=None, verify_integrity=True):
+ def set_codes(self, codes, level=None, inplace=None, verify_integrity: bool = True):
"""
Set new codes on MultiIndex. Defaults to returning new index.
@@ -985,7 +991,7 @@ def set_codes(self, codes, level=None, inplace=None, verify_integrity=True):
If True, mutates in place.
.. deprecated:: 1.2.0
- verify_integrity : bool (default True)
+ verify_integrity : bool, default True
If True, checks that levels and codes are compatible.
Returns
@@ -1080,12 +1086,12 @@ def _constructor(self):
return type(self).from_tuples
@doc(Index._shallow_copy)
- def _shallow_copy(self, values, name=lib.no_default):
+ def _shallow_copy(self, values: np.ndarray, name=lib.no_default) -> MultiIndex:
names = name if name is not lib.no_default else self.names
return type(self).from_tuples(values, sortorder=None, names=names)
- def _view(self: MultiIndex) -> MultiIndex:
+ def _view(self) -> MultiIndex:
result = type(self)(
levels=self.levels,
codes=self.codes,
@@ -1580,7 +1586,7 @@ def is_monotonic_decreasing(self) -> bool:
return self[::-1].is_monotonic_increasing
@cache_readonly
- def _inferred_type_levels(self):
+ def _inferred_type_levels(self) -> List[str]:
""" return a list of the inferred types, one for each level """
return [i.inferred_type for i in self.levels]
@@ -1598,7 +1604,7 @@ def fillna(self, value=None, downcast=None):
raise NotImplementedError("isna is not defined for MultiIndex")
@doc(Index.dropna)
- def dropna(self, how="any"):
+ def dropna(self, how: str = "any") -> MultiIndex:
nans = [level_codes == -1 for level_codes in self.codes]
if how == "any":
indexer = np.any(nans, axis=0)
@@ -1610,7 +1616,7 @@ def dropna(self, how="any"):
new_codes = [level_codes[~indexer] for level_codes in self.codes]
return self.set_codes(codes=new_codes)
- def _get_level_values(self, level, unique=False):
+ def _get_level_values(self, level: int, unique: bool = False) -> Index:
"""
Return vector of label values for requested level,
equal to the length of the index
@@ -1619,13 +1625,13 @@ def _get_level_values(self, level, unique=False):
Parameters
----------
- level : int level
+ level : int
unique : bool, default False
if True, drop duplicated values
Returns
-------
- values : ndarray
+ Index
"""
lev = self.levels[level]
level_codes = self.codes[level]
@@ -1759,7 +1765,7 @@ def to_frame(self, index=True, name=None):
result.index = self
return result
- def to_flat_index(self):
+ def to_flat_index(self) -> Index:
"""
Convert a MultiIndex to an Index of Tuples containing the level values.
@@ -1862,7 +1868,7 @@ def _lexsort_depth(self) -> int:
return self.sortorder
return _lexsort_depth(self.codes, self.nlevels)
- def _sort_levels_monotonic(self):
+ def _sort_levels_monotonic(self) -> MultiIndex:
"""
This is an *internal* function.
@@ -1929,7 +1935,7 @@ def _sort_levels_monotonic(self):
verify_integrity=False,
)
- def remove_unused_levels(self):
+ def remove_unused_levels(self) -> MultiIndex:
"""
Create new MultiIndex from current that removes unused levels.
@@ -2065,7 +2071,9 @@ def __getitem__(self, key):
)
@Appender(_index_shared_docs["take"] % _index_doc_kwargs)
- def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs):
+ def take(
+ self: MultiIndex, indices, axis=0, allow_fill=True, fill_value=None, **kwargs
+ ) -> MultiIndex:
nv.validate_take((), kwargs)
indices = ensure_platform_int(indices)
@@ -2129,7 +2137,7 @@ def argsort(self, *args, **kwargs) -> np.ndarray:
return self._values.argsort(*args, **kwargs)
@Appender(_index_shared_docs["repeat"] % _index_doc_kwargs)
- def repeat(self, repeats, axis=None):
+ def repeat(self, repeats: int, axis=None) -> MultiIndex:
nv.validate_repeat((), {"axis": axis})
repeats = ensure_platform_int(repeats)
return MultiIndex(
@@ -2200,7 +2208,7 @@ def drop(self, codes, level=None, errors="raise"):
return self.delete(inds)
- def _drop_from_level(self, codes, level, errors="raise"):
+ def _drop_from_level(self, codes, level, errors="raise") -> MultiIndex:
codes = com.index_labels_to_array(codes)
i = self._get_level_number(level)
index = self.levels[i]
@@ -2219,7 +2227,7 @@ def _drop_from_level(self, codes, level, errors="raise"):
return self[mask]
- def swaplevel(self, i=-2, j=-1):
+ def swaplevel(self, i=-2, j=-1) -> MultiIndex:
"""
Swap level i with level j.
@@ -2277,7 +2285,7 @@ def swaplevel(self, i=-2, j=-1):
levels=new_levels, codes=new_codes, names=new_names, verify_integrity=False
)
- def reorder_levels(self, order):
+ def reorder_levels(self, order) -> MultiIndex:
"""
Rearrange levels using input order. May not drop or duplicate levels.
@@ -2323,7 +2331,7 @@ def reorder_levels(self, order):
levels=new_levels, codes=new_codes, names=new_names, verify_integrity=False
)
- def _get_codes_for_sorting(self):
+ def _get_codes_for_sorting(self) -> List[Categorical]:
"""
we are categorizing our codes by using the
available categories (all, not just observed)
@@ -2343,7 +2351,9 @@ def cats(level_codes):
for level_codes in self.codes
]
- def sortlevel(self, level=0, ascending=True, sort_remaining=True):
+ def sortlevel(
+ self, level=0, ascending: bool = True, sort_remaining: bool = True
+ ) -> Tuple[MultiIndex, np.ndarray]:
"""
Sort MultiIndex at the requested level.
@@ -3396,7 +3406,7 @@ def _reorder_indexer(
ind = np.lexsort(keys)
return indexer[ind]
- def truncate(self, before=None, after=None):
+ def truncate(self, before=None, after=None) -> MultiIndex:
"""
Slice index between two labels / tuples, return new MultiIndex
@@ -3517,7 +3527,7 @@ def _union(self, other, sort):
def _is_comparable_dtype(self, dtype: DtypeObj) -> bool:
return is_object_dtype(dtype)
- def _get_reconciled_name_object(self, other):
+ def _get_reconciled_name_object(self, other) -> MultiIndex:
"""
If the result of a set operation will be self,
return self, unless the names change, in which
@@ -3662,7 +3672,7 @@ def _validate_fill_value(self, item):
raise ValueError("Item must have length equal to number of levels.")
return item
- def insert(self, loc: int, item):
+ def insert(self, loc: int, item) -> MultiIndex:
"""
Make new MultiIndex inserting new item at location
@@ -3702,7 +3712,7 @@ def insert(self, loc: int, item):
levels=new_levels, codes=new_codes, names=self.names, verify_integrity=False
)
- def delete(self, loc):
+ def delete(self, loc) -> MultiIndex:
"""
Make new index with passed location deleted
@@ -3719,7 +3729,7 @@ def delete(self, loc):
)
@doc(Index.isin)
- def isin(self, values, level=None):
+ def isin(self, values, level=None) -> np.ndarray:
if level is None:
values = MultiIndex.from_tuples(values, names=self.names)._values
return algos.isin(self._values, values)
@@ -3800,7 +3810,7 @@ def _get_na_rep(dtype) -> str:
return {np.datetime64: "NaT", np.timedelta64: "NaT"}.get(dtype, "NaN")
-def maybe_droplevels(index, key):
+def maybe_droplevels(index: Index, key) -> Index:
"""
Attempt to drop level or levels from the given index.
diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py
index f0bc58cbf07bf..4049ef46f3006 100644
--- a/pandas/tests/groupby/test_categorical.py
+++ b/pandas/tests/groupby/test_categorical.py
@@ -1639,8 +1639,8 @@ def test_series_groupby_first_on_categorical_col_grouped_on_2_categoricals(
val = [0, 1, 1, 0]
df = DataFrame({"a": cat, "b": cat, "c": val})
- idx = Categorical([0, 1])
- idx = pd.MultiIndex.from_product([idx, idx], names=["a", "b"])
+ cat2 = Categorical([0, 1])
+ idx = pd.MultiIndex.from_product([cat2, cat2], names=["a", "b"])
expected_dict = {
"first": Series([0, np.NaN, np.NaN, 1], idx, name="c"),
"last": Series([1, np.NaN, np.NaN, 0], idx, name="c"),
@@ -1664,8 +1664,8 @@ def test_df_groupby_first_on_categorical_col_grouped_on_2_categoricals(
val = [0, 1, 1, 0]
df = DataFrame({"a": cat, "b": cat, "c": val})
- idx = Categorical([0, 1])
- idx = pd.MultiIndex.from_product([idx, idx], names=["a", "b"])
+ cat2 = Categorical([0, 1])
+ idx = pd.MultiIndex.from_product([cat2, cat2], names=["a", "b"])
expected_dict = {
"first": Series([0, np.NaN, np.NaN, 1], idx, name="c"),
"last": Series([1, np.NaN, np.NaN, 0], idx, name="c"),
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39729 | 2021-02-10T17:22:48Z | 2021-02-10T18:43:28Z | 2021-02-10T18:43:28Z | 2021-02-10T18:51:15Z |
REF: separate out indexer/mask preprocessing code in algorithms.take_nd | diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index cdbef673643e8..98243431e42df 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -1661,6 +1661,40 @@ def take(arr, indices, axis: int = 0, allow_fill: bool = False, fill_value=None)
return result
+def _take_preprocess_indexer_and_fill_value(
+ arr, indexer, axis, out, fill_value, allow_fill
+):
+ mask_info = None
+
+ if indexer is None:
+ indexer = np.arange(arr.shape[axis], dtype=np.int64)
+ dtype, fill_value = arr.dtype, arr.dtype.type()
+ else:
+ indexer = ensure_int64(indexer, copy=False)
+ if not allow_fill:
+ dtype, fill_value = arr.dtype, arr.dtype.type()
+ mask_info = None, False
+ else:
+ # check for promotion based on types only (do this first because
+ # it's faster than computing a mask)
+ dtype, fill_value = maybe_promote(arr.dtype, fill_value)
+ if dtype != arr.dtype and (out is None or out.dtype != dtype):
+ # check if promotion is actually required based on indexer
+ mask = indexer == -1
+ needs_masking = mask.any()
+ mask_info = mask, needs_masking
+ if needs_masking:
+ if out is not None and out.dtype != dtype:
+ raise TypeError("Incompatible type for fill_value")
+ else:
+ # if not, then depromote, set fill_value to dummy
+ # (it won't be used but we don't want the cython code
+ # to crash when trying to cast it to dtype)
+ dtype, fill_value = arr.dtype, arr.dtype.type()
+
+ return indexer, dtype, fill_value, mask_info
+
+
def take_nd(
arr,
indexer,
@@ -1700,8 +1734,6 @@ def take_nd(
subarray : array-like
May be the same type as the input, or cast to an ndarray.
"""
- mask_info = None
-
if fill_value is lib.no_default:
fill_value = na_value_for_dtype(arr.dtype, compat=False)
@@ -1712,31 +1744,9 @@ def take_nd(
arr = extract_array(arr)
arr = np.asarray(arr)
- if indexer is None:
- indexer = np.arange(arr.shape[axis], dtype=np.int64)
- dtype, fill_value = arr.dtype, arr.dtype.type()
- else:
- indexer = ensure_int64(indexer, copy=False)
- if not allow_fill:
- dtype, fill_value = arr.dtype, arr.dtype.type()
- mask_info = None, False
- else:
- # check for promotion based on types only (do this first because
- # it's faster than computing a mask)
- dtype, fill_value = maybe_promote(arr.dtype, fill_value)
- if dtype != arr.dtype and (out is None or out.dtype != dtype):
- # check if promotion is actually required based on indexer
- mask = indexer == -1
- needs_masking = mask.any()
- mask_info = mask, needs_masking
- if needs_masking:
- if out is not None and out.dtype != dtype:
- raise TypeError("Incompatible type for fill_value")
- else:
- # if not, then depromote, set fill_value to dummy
- # (it won't be used but we don't want the cython code
- # to crash when trying to cast it to dtype)
- dtype, fill_value = arr.dtype, arr.dtype.type()
+ indexer, dtype, fill_value, mask_info = _take_preprocess_indexer_and_fill_value(
+ arr, indexer, axis, out, fill_value, allow_fill
+ )
flip_order = False
if arr.ndim == 2 and arr.flags.f_contiguous:
| Precursor for https://github.com/pandas-dev/pandas/pull/39692 (just moving code into a separate helper function) | https://api.github.com/repos/pandas-dev/pandas/pulls/39728 | 2021-02-10T16:35:07Z | 2021-02-10T17:58:47Z | 2021-02-10T17:58:47Z | 2021-02-10T18:02:18Z |
SAS validate null dates | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 99ae60859b68c..11f8a5b6c2499 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -390,6 +390,7 @@ I/O
- Bug in :func:`read_json` when ``orient="split"`` does not maintain numeric string index (:issue:`28556`)
- :meth:`read_sql` returned an empty generator if ``chunksize`` was no-zero and the query returned no results. Now returns a generator with a single empty dataframe (:issue:`34411`)
- Bug in :func:`read_hdf` returning unexpected records when filtering on categorical string columns using ``where`` parameter (:issue:`39189`)
+- Bug in :func:`read_sas` raising ``ValueError`` when ``datetimes`` were null (:issue:`39725`)
Period
^^^^^^
diff --git a/pandas/io/sas/sas7bdat.py b/pandas/io/sas/sas7bdat.py
index fe06f103e6c5e..9853fa41d3fb9 100644
--- a/pandas/io/sas/sas7bdat.py
+++ b/pandas/io/sas/sas7bdat.py
@@ -23,6 +23,7 @@
from pandas.errors import EmptyDataError, OutOfBoundsDatetime
import pandas as pd
+from pandas import isna
from pandas.io.common import get_handle
from pandas.io.sas._sas import Parser
@@ -30,6 +31,20 @@
from pandas.io.sas.sasreader import ReaderBase
+def _parse_datetime(sas_datetime: float, unit: str):
+ if isna(sas_datetime):
+ return pd.NaT
+
+ if unit == "s":
+ return datetime(1960, 1, 1) + timedelta(seconds=sas_datetime)
+
+ elif unit == "d":
+ return datetime(1960, 1, 1) + timedelta(days=sas_datetime)
+
+ else:
+ raise ValueError("unit must be 'd' or 's'")
+
+
def _convert_datetimes(sas_datetimes: pd.Series, unit: str) -> pd.Series:
"""
Convert to Timestamp if possible, otherwise to datetime.datetime.
@@ -51,20 +66,9 @@ def _convert_datetimes(sas_datetimes: pd.Series, unit: str) -> pd.Series:
try:
return pd.to_datetime(sas_datetimes, unit=unit, origin="1960-01-01")
except OutOfBoundsDatetime:
- if unit == "s":
- s_series = sas_datetimes.apply(
- lambda sas_float: datetime(1960, 1, 1) + timedelta(seconds=sas_float)
- )
- s_series = cast(pd.Series, s_series)
- return s_series
- elif unit == "d":
- d_series = sas_datetimes.apply(
- lambda sas_float: datetime(1960, 1, 1) + timedelta(days=sas_float)
- )
- d_series = cast(pd.Series, d_series)
- return d_series
- else:
- raise ValueError("unit must be 'd' or 's'")
+ s_series = sas_datetimes.apply(_parse_datetime, unit=unit)
+ s_series = cast(pd.Series, s_series)
+ return s_series
class _SubheaderPointer:
diff --git a/pandas/tests/io/sas/data/dates_null.sas7bdat b/pandas/tests/io/sas/data/dates_null.sas7bdat
new file mode 100644
index 0000000000000..beadf1a34f42e
Binary files /dev/null and b/pandas/tests/io/sas/data/dates_null.sas7bdat differ
diff --git a/pandas/tests/io/sas/test_sas7bdat.py b/pandas/tests/io/sas/test_sas7bdat.py
index 4035f6aff90ce..b23959a7d87a2 100644
--- a/pandas/tests/io/sas/test_sas7bdat.py
+++ b/pandas/tests/io/sas/test_sas7bdat.py
@@ -315,3 +315,22 @@ def test_max_sas_date_iterator(datapath):
]
for result, expected in zip(results, expected):
tm.assert_frame_equal(result, expected)
+
+
+def test_null_date(datapath):
+ fname = datapath("io", "sas", "data", "dates_null.sas7bdat")
+ df = pd.read_sas(fname, encoding="utf-8")
+
+ expected = pd.DataFrame(
+ {
+ "datecol": [
+ datetime(9999, 12, 29),
+ pd.NaT,
+ ],
+ "datetimecol": [
+ datetime(9999, 12, 29, 23, 59, 59, 998993),
+ pd.NaT,
+ ],
+ },
+ )
+ tm.assert_frame_equal(df, expected)
| - [x] closes #39725
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39726 | 2021-02-10T15:42:23Z | 2021-02-12T20:12:13Z | 2021-02-12T20:12:12Z | 2021-02-12T20:23:02Z |
REF: move reshaping of array for setitem from DataFrame into BlockManager internals | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 9e54a5ee0210d..1d633aec79e93 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -3272,7 +3272,6 @@ def _set_item_frame_value(self, key, value: DataFrame) -> None:
# now align rows
value = _reindex_for_setitem(value, self.index)
- value = value.T
self._set_item_mgr(key, value)
def _iset_item_mgr(self, loc: int, value) -> None:
@@ -3280,8 +3279,6 @@ def _iset_item_mgr(self, loc: int, value) -> None:
self._clear_item_cache()
def _set_item_mgr(self, key, value):
- value = _maybe_atleast_2d(value)
-
try:
loc = self._info_axis.get_loc(key)
except KeyError:
@@ -3298,7 +3295,6 @@ def _set_item_mgr(self, key, value):
def _iset_item(self, loc: int, value):
value = self._sanitize_column(value)
- value = _maybe_atleast_2d(value)
self._iset_item_mgr(loc, value)
# check if we are modifying a copy
@@ -3328,7 +3324,7 @@ def _set_item(self, key, value):
if not self.columns.is_unique or isinstance(self.columns, MultiIndex):
existing_piece = self[key]
if isinstance(existing_piece, DataFrame):
- value = np.tile(value, (len(existing_piece.columns), 1))
+ value = np.tile(value, (len(existing_piece.columns), 1)).T
self._set_item_mgr(key, value)
@@ -3889,7 +3885,6 @@ def insert(self, loc, column, value, allow_duplicates: bool = False) -> None:
"'self.flags.allows_duplicate_labels' is False."
)
value = self._sanitize_column(value)
- value = _maybe_atleast_2d(value)
self._mgr.insert(loc, column, value, allow_duplicates=allow_duplicates)
def assign(self, **kwargs) -> DataFrame:
@@ -3994,8 +3989,6 @@ def _sanitize_column(self, value):
value = maybe_convert_platform(value)
else:
value = com.asarray_tuplesafe(value)
- elif value.ndim == 2:
- value = value.copy().T
elif isinstance(value, Index):
value = value.copy(deep=True)
else:
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 0aa97b4d6c0ed..6e4999c3e759f 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -1013,6 +1013,9 @@ def value_getitem(placement):
return value
else:
+ if value.ndim == 2:
+ value = value.T
+
if value.ndim == self.ndim - 1:
value = safe_reshape(value, (1,) + value.shape)
@@ -1135,6 +1138,9 @@ def insert(self, loc: int, item: Hashable, value, allow_duplicates: bool = False
# insert to the axis; this could possibly raise a TypeError
new_axis = self.items.insert(loc, item)
+ if value.ndim == 2:
+ value = value.T
+
if value.ndim == self.ndim - 1 and not is_extension_array_dtype(value.dtype):
# TODO(EA2D): special case not needed with 2D EAs
value = safe_reshape(value, (1,) + value.shape)
diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py
index 67bc9f3f58daa..a5b54bc153f5d 100644
--- a/pandas/tests/extension/test_numpy.py
+++ b/pandas/tests/extension/test_numpy.py
@@ -350,9 +350,9 @@ def test_fillna_fill_other(self, data_missing):
class TestReshaping(BaseNumPyTests, base.BaseReshapingTests):
- @skip_nested
+ @pytest.mark.skip(reason="Incorrect expected.")
def test_merge(self, data, na_value):
- # Fails creating expected
+ # Fails creating expected (key column becomes a PandasDtype because)
super().test_merge(data, na_value)
@skip_nested
| I think ideally the DataFrame does not need to be aware of how the underlying manager stores the data (as 2D, transposed or not), so moving the logic of ensuring 2D/transposed values from the DataFrame set_item-related method into `BlockManager.iset`.
This will help for the ArrayManager, so we don't have to re-reshape there. | https://api.github.com/repos/pandas-dev/pandas/pulls/39722 | 2021-02-10T13:14:51Z | 2021-02-10T14:40:30Z | 2021-02-10T14:40:30Z | 2021-02-10T20:19:15Z |
[ArrayManager] Implement .equals method | diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py
index 0f677ff3180be..a8493e647f39a 100644
--- a/pandas/core/internals/array_manager.py
+++ b/pandas/core/internals/array_manager.py
@@ -20,7 +20,7 @@
)
from pandas.core.dtypes.dtypes import ExtensionDtype, PandasDtype
from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
-from pandas.core.dtypes.missing import isna
+from pandas.core.dtypes.missing import array_equals, isna
import pandas.core.algorithms as algos
from pandas.core.arrays import ExtensionArray
@@ -829,9 +829,16 @@ def _make_na_array(self, fill_value=None):
values.fill(fill_value)
return values
- def equals(self, other: object) -> bool:
- # TODO
- raise NotImplementedError
+ def _equal_values(self, other) -> bool:
+ """
+ Used in .equals defined in base class. Only check the column values
+ assuming shape and indexes have already been checked.
+ """
+ for left, right in zip(self.arrays, other.arrays):
+ if not array_equals(left, right):
+ return False
+ else:
+ return True
def unstack(self, unstacker, fill_value) -> ArrayManager:
"""
diff --git a/pandas/core/internals/base.py b/pandas/core/internals/base.py
index 2295e3f2c41b2..585a2dccf3acf 100644
--- a/pandas/core/internals/base.py
+++ b/pandas/core/internals/base.py
@@ -70,3 +70,25 @@ def reindex_axis(
consolidate=consolidate,
only_slice=only_slice,
)
+
+ def _equal_values(self: T, other: T) -> bool:
+ """
+ To be implemented by the subclasses. Only check the column values
+ assuming shape and indexes have already been checked.
+ """
+ raise AbstractMethodError(self)
+
+ def equals(self, other: object) -> bool:
+ """
+ Implementation for DataFrame.equals
+ """
+ if not isinstance(other, DataManager):
+ return False
+
+ self_axes, other_axes = self.axes, other.axes
+ if len(self_axes) != len(other_axes):
+ return False
+ if not all(ax1.equals(ax2) for ax1, ax2 in zip(self_axes, other_axes)):
+ return False
+
+ return self._equal_values(other)
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 0aa97b4d6c0ed..80f5bdfc57f8a 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -1395,16 +1395,11 @@ def take(self, indexer, axis: int = 1, verify: bool = True, convert: bool = True
consolidate=False,
)
- def equals(self, other: object) -> bool:
- if not isinstance(other, BlockManager):
- return False
-
- self_axes, other_axes = self.axes, other.axes
- if len(self_axes) != len(other_axes):
- return False
- if not all(ax1.equals(ax2) for ax1, ax2 in zip(self_axes, other_axes)):
- return False
-
+ def _equal_values(self: T, other: T) -> bool:
+ """
+ Used in .equals defined in base class. Only check the column values
+ assuming shape and indexes have already been checked.
+ """
if self.ndim == 1:
# For SingleBlockManager (i.e.Series)
if other.ndim != 1:
diff --git a/pandas/tests/frame/methods/test_equals.py b/pandas/tests/frame/methods/test_equals.py
index dc45c9eb97ae4..ac9a66b4c7a6f 100644
--- a/pandas/tests/frame/methods/test_equals.py
+++ b/pandas/tests/frame/methods/test_equals.py
@@ -1,13 +1,8 @@
import numpy as np
-import pandas.util._test_decorators as td
-
from pandas import DataFrame, date_range
import pandas._testing as tm
-# TODO(ArrayManager) implement equals
-pytestmark = td.skip_array_manager_not_yet_implemented
-
class TestEquals:
def test_dataframe_not_equal(self):
@@ -16,13 +11,14 @@ def test_dataframe_not_equal(self):
df2 = DataFrame({"a": ["s", "d"], "b": [1, 2]})
assert df1.equals(df2) is False
- def test_equals_different_blocks(self):
+ def test_equals_different_blocks(self, using_array_manager):
# GH#9330
df0 = DataFrame({"A": ["x", "y"], "B": [1, 2], "C": ["w", "z"]})
df1 = df0.reset_index()[["A", "B", "C"]]
- # this assert verifies that the above operations have
- # induced a block rearrangement
- assert df0._mgr.blocks[0].dtype != df1._mgr.blocks[0].dtype
+ if not using_array_manager:
+ # this assert verifies that the above operations have
+ # induced a block rearrangement
+ assert df0._mgr.blocks[0].dtype != df1._mgr.blocks[0].dtype
# do the real tests
tm.assert_frame_equal(df0, df1)
| xref #39146
Moved the common part (checking of dimension and indices) to the base class `equals` method so this can be shared, and the actual BlockManager/AraryManager then only need to check the column values. | https://api.github.com/repos/pandas-dev/pandas/pulls/39721 | 2021-02-10T10:22:20Z | 2021-02-10T13:51:47Z | 2021-02-10T13:51:47Z | 2021-02-10T13:54:05Z |
DOC: Rewrite for `Styler` user guide with new features and other high-level changes. | diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst
index e72a9d86daeaf..3b1a3c5e380d3 100644
--- a/doc/source/ecosystem.rst
+++ b/doc/source/ecosystem.rst
@@ -98,7 +98,8 @@ which can be used for a wide variety of time series data mining tasks.
Visualization
-------------
-While :ref:`pandas has built-in support for data visualization with matplotlib <visualization>`,
+`Pandas has its own Styler class for table visualization <user_guide/style.ipynb>`_, and while
+:ref:`pandas also has built-in support for data visualization through charts with matplotlib <visualization>`,
there are a number of other pandas-compatible libraries.
`Altair <https://altair-viz.github.io/>`__
diff --git a/doc/source/user_guide/index.rst b/doc/source/user_guide/index.rst
index 901f42097b911..6b6e212cde635 100644
--- a/doc/source/user_guide/index.rst
+++ b/doc/source/user_guide/index.rst
@@ -38,12 +38,12 @@ Further information on any specific method can be obtained in the
integer_na
boolean
visualization
+ style
computation
groupby
window
timeseries
timedeltas
- style
options
enhancingperf
scale
diff --git a/doc/source/user_guide/style.ipynb b/doc/source/user_guide/style.ipynb
index a67bac0c65462..b8119477407c0 100644
--- a/doc/source/user_guide/style.ipynb
+++ b/doc/source/user_guide/style.ipynb
@@ -4,30 +4,28 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "# Styling\n",
+ "# Table Visualization\n",
"\n",
- "This document is written as a Jupyter Notebook, and can be viewed or downloaded [here](https://nbviewer.ipython.org/github/pandas-dev/pandas/blob/master/doc/source/user_guide/style.ipynb).\n",
+ "This section demonstrates visualization of tabular data using the [Styler][styler]\n",
+ "class. For information on visualization with charting please see [Chart Visualization][viz]. This document is written as a Jupyter Notebook, and can be viewed or downloaded [here][download].\n",
"\n",
- "You can apply **conditional formatting**, the visual styling of a DataFrame\n",
- "depending on the data within, by using the ``DataFrame.style`` property.\n",
- "This is a property that returns a ``Styler`` object, which has\n",
- "useful methods for formatting and displaying DataFrames.\n",
- "\n",
- "The styling is accomplished using CSS.\n",
- "You write \"style functions\" that take scalars, `DataFrame`s or `Series`, and return *like-indexed* DataFrames or Series with CSS `\"attribute: value\"` pairs for the values.\n",
- "These functions can be incrementally passed to the `Styler` which collects the styles before rendering.\n",
- "\n",
- "CSS is a flexible language and as such there may be multiple ways of achieving the same result, with potential\n",
- "advantages or disadvantages, which we try to illustrate."
+ "[styler]: ../reference/api/pandas.io.formats.style.Styler.rst\n",
+ "[viz]: visualization.rst\n",
+ "[download]: https://nbviewer.ipython.org/github/pandas-dev/pandas/blob/master/doc/source/user_guide/style.ipynb"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Styler Object\n",
+ "## Styler Object and HTML \n",
+ "\n",
+ "Styling should be performed after the data in a DataFrame has been processed. The [Styler][styler] creates an HTML `<table>` and leverages CSS styling language to manipulate many parameters including colors, fonts, borders, background, etc. See [here][w3schools] for more information on styling HTML tables. This allows a lot of flexibility out of the box, and even enables web developers to integrate DataFrames into their exiting user interface designs.\n",
+ " \n",
+ "The `DataFrame.style` attribute is a property that returns a [Styler][styler] object. It has a `_repr_html_` method defined on it so they are rendered automatically in Jupyter Notebook.\n",
"\n",
- "The `DataFrame.style` attribute is a property that returns a `Styler` object. `Styler` has a `_repr_html_` method defined on it so they are rendered automatically. If you want the actual HTML back for further processing or for writing to file call the `.render()` method which returns a string."
+ "[styler]: ../reference/api/pandas.io.formats.style.Styler.rst\n",
+ "[w3schools]: https://www.w3schools.com/html/html_tables.asp"
]
},
{
@@ -52,12 +50,9 @@
"import pandas as pd\n",
"import numpy as np\n",
"\n",
- "np.random.seed(24)\n",
- "df = pd.DataFrame({'A': np.linspace(1, 10, 10)})\n",
- "df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],\n",
- " axis=1)\n",
- "df.iloc[3, 3] = np.nan\n",
- "df.iloc[0, 2] = np.nan\n",
+ "df = pd.DataFrame([[38.0, 2.0, 18.0, 22.0, 21, np.nan],[19, 439, 6, 452, 226,232]], \n",
+ " index=pd.Index(['Tumour (Positive)', 'Non-Tumour (Negative)'], name='Actual Label:'), \n",
+ " columns=pd.MultiIndex.from_product([['Decision Tree', 'Regression', 'Random'],['Tumour', 'Non-Tumour']], names=['Model:', 'Predicted:']))\n",
"df.style"
]
},
@@ -65,49 +60,105 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The above output looks very similar to the standard DataFrame HTML representation. But we've done some work behind the scenes to attach CSS classes to each cell. We can view these by calling the `.render` method."
+ "The above output looks very similar to the standard DataFrame HTML representation. But the HTML here has already attached some CSS classes to each cell, even if we haven't yet created any styles. We can view these by calling the [.render()][render] method, which returns the raw HTML as string, which is useful for further processing or adding to a file - read on in [More about CSS and HTML](#More-About-CSS-and-HTML). Below we will show how we can use these to format the DataFrame to be more communicative. For example how we can build `s`:\n",
+ "\n",
+ "[render]: ../reference/api/pandas.io.formats.style.Styler.render.rst"
]
},
{
"cell_type": "code",
"execution_count": null,
- "metadata": {},
+ "metadata": {
+ "nbsphinx": "hidden"
+ },
"outputs": [],
"source": [
- "df.style.render().split('\\n')[:10]"
+ "# Hidden cell to just create the below example: code is covered throughout the guide.\n",
+ "s = df.style\\\n",
+ " .hide_columns([('Random', 'Tumour'), ('Random', 'Non-Tumour')])\\\n",
+ " .format('{:.0f}')\\\n",
+ " .set_table_styles([{\n",
+ " 'selector': '',\n",
+ " 'props': 'border-collapse: separate;'\n",
+ " },{\n",
+ " 'selector': 'caption',\n",
+ " 'props': 'caption-side: bottom; font-size:1.3em;'\n",
+ " },{\n",
+ " 'selector': '.index_name',\n",
+ " 'props': 'font-style: italic; color: darkgrey; font-weight:normal;'\n",
+ " },{\n",
+ " 'selector': 'th:not(.index_name)',\n",
+ " 'props': 'background-color: #000066; color: white;'\n",
+ " },{\n",
+ " 'selector': 'th.col_heading',\n",
+ " 'props': 'text-align: center;'\n",
+ " },{\n",
+ " 'selector': 'th.col_heading.level0',\n",
+ " 'props': 'font-size: 1.5em;'\n",
+ " },{\n",
+ " 'selector': 'th.col2',\n",
+ " 'props': 'border-left: 1px solid white;'\n",
+ " },{\n",
+ " 'selector': '.col2',\n",
+ " 'props': 'border-left: 1px solid #000066;'\n",
+ " },{\n",
+ " 'selector': 'td',\n",
+ " 'props': 'text-align: center; font-weight:bold;'\n",
+ " },{\n",
+ " 'selector': '.true',\n",
+ " 'props': 'background-color: #e6ffe6;'\n",
+ " },{\n",
+ " 'selector': '.false',\n",
+ " 'props': 'background-color: #ffe6e6;'\n",
+ " },{\n",
+ " 'selector': '.border-red',\n",
+ " 'props': 'border: 2px dashed red;'\n",
+ " },{\n",
+ " 'selector': '.border-green',\n",
+ " 'props': 'border: 2px dashed green;'\n",
+ " },{\n",
+ " 'selector': 'td:hover',\n",
+ " 'props': 'background-color: #ffffb3;'\n",
+ " }])\\\n",
+ " .set_td_classes(pd.DataFrame([['true border-green', 'false', 'true', 'false border-red', '', ''],\n",
+ " ['false', 'true', 'false', 'true', '', '']], \n",
+ " index=df.index, columns=df.columns))\\\n",
+ " .set_caption(\"Confusion matrix for multiple cancer prediction models.\")\\\n",
+ " .set_tooltips(pd.DataFrame([['This model has a very strong true positive rate', '', '', \"This model's total number of false negatives is too high\", '', ''],\n",
+ " ['', '', '', '', '', '']], \n",
+ " index=df.index, columns=df.columns),\n",
+ " css_class='pd-tt', props=\n",
+ " 'visibility: hidden; position: absolute; z-index: 1; border: 1px solid #000066;'\n",
+ " 'background-color: white; color: #000066; font-size: 0.8em;' \n",
+ " 'transform: translate(0px, -24px); padding: 0.6em; border-radius: 0.5em;')\n"
]
},
{
- "cell_type": "markdown",
+ "cell_type": "code",
+ "execution_count": null,
"metadata": {},
+ "outputs": [],
"source": [
- "The `row0_col2` is the identifier for that particular cell. We've also prepended each row/column identifier with a UUID unique to each DataFrame so that the style from one doesn't collide with the styling from another within the same notebook or page (you can set the `uuid` if you'd like to tie together the styling of two DataFrames, or remove it if you want to optimise HTML transfer for larger tables)."
+ "s"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Building styles\n",
+ "## Formatting the Display\n",
"\n",
- "There are 3 primary methods of adding custom styles to DataFrames using CSS and matching it to cells:\n",
+ "### Formatting Values\n",
"\n",
- "- Directly linking external CSS classes to your individual cells using `Styler.set_td_classes`.\n",
- "- Using `table_styles` to control broader areas of the DataFrame with internal CSS.\n",
- "- Using the `Styler.apply` and `Styler.applymap` functions for more specific control with internal CSS. \n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Linking External CSS\n",
+ "Before adding styles it is useful to show that the [Styler][styler] can distinguish the *display* value from the *actual* value. To control the display value, the text is printed in each cell, and we can use the [.format()][formatfunc] method to manipulate this according to a [format spec string][format] or a callable that takes a single value and returns a string. It is possible to define this for the whole table or for individual columns. \n",
"\n",
- "*New in version 1.2.0*\n",
+ "Additionally, the format function has a **precision** argument to specifically help formatting floats, an **na_rep** argument to display missing data, and an **escape** argument to help displaying safe-HTML. The default formatter is configured to adopt pandas' regular `display.precision` option, controllable using `with pd.option_context('display.precision', 2):`\n",
"\n",
- "If you have designed a website then it is likely you will already have an external CSS file that controls the styling of table and cell objects within your website.\n",
+ "Here is an example of using the multiple options to control the formatting generally and with specific column formatters.\n",
"\n",
- "For example, suppose we have an external CSS which controls table properties and has some additional classes to style individual elements (here we manually add one to this notebook):"
+ "[styler]: ../reference/api/pandas.io.formats.style.Styler.rst\n",
+ "[format]: https://docs.python.org/3/library/string.html#format-specification-mini-language\n",
+ "[formatfunc]: ../reference/api/pandas.io.formats.style.Styler.format.rst"
]
},
{
@@ -116,22 +167,28 @@
"metadata": {},
"outputs": [],
"source": [
- "from IPython.display import HTML\n",
- "style = \\\n",
- "\"<style>\"\\\n",
- "\".table-cls {color: grey;}\"\\\n",
- "\".cls1 {background-color: red; color: white;}\"\\\n",
- "\".cls2 {background-color: blue; color: white;}\"\\\n",
- "\".cls3 {font-weight: bold; font-style: italic; font-size:1.8em}\"\\\n",
- "\"</style>\"\n",
- "HTML(style)"
+ "df.style.format(precision=0, na_rep='MISSING', \n",
+ " formatter={('Decision Tree', 'Tumour'): \"{:.2f}\",\n",
+ " ('Regression', 'Non-Tumour'): lambda x: \"$ {:,.1f}\".format(x*-1e3)\n",
+ " })"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "Now we can manually link these to our DataFrame using the `Styler.set_table_attributes` and `Styler.set_td_classes` methods (note that table level 'table-cls' is overwritten here by Jupyters own CSS, but in HTML the default text color will be grey)."
+ "### Hiding Data\n",
+ "\n",
+ "The index can be hidden from rendering by calling [.hide_index()][hideidx], which might be useful if your index is integer based.\n",
+ "\n",
+ "Columns can be hidden from rendering by calling [.hide_columns()][hidecols] and passing in the name of a column, or a slice of columns.\n",
+ "\n",
+ "Hiding does not change the integer arrangement of CSS classes, e.g. hiding the first two columns of a DataFrame means the column class indexing will start at `col2`, since `col0` and `col1` are simply ignored.\n",
+ "\n",
+ "We can update our `Styler` object to hide some data and format the values.\n",
+ "\n",
+ "[hideidx]: ../reference/api/pandas.io.formats.style.Styler.hide_index.rst\n",
+ "[hidecols]: ../reference/api/pandas.io.formats.style.Styler.hide_columns.rst"
]
},
{
@@ -140,33 +197,65 @@
"metadata": {},
"outputs": [],
"source": [
- "css_classes = pd.DataFrame(data=[['cls1', None], ['cls3', 'cls2 cls3']], index=[0,2], columns=['A', 'C'])\n",
- "df.style.\\\n",
- " set_table_attributes('class=\"table-cls\"').\\\n",
- " set_td_classes(css_classes)"
+ "s = df.style.format('{:.0f}').hide_columns([('Random', 'Tumour'), ('Random', 'Non-Tumour')])\n",
+ "s"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "nbsphinx": "hidden"
+ },
+ "outputs": [],
+ "source": [
+ "# Hidden cell to avoid CSS clashes and latter code upcoding previous formatting \n",
+ "s.set_uuid('after_hide')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "The **advantage** of linking to external CSS is that it can be applied very easily. One can build a DataFrame of (multiple) CSS classes to add to each cell dynamically using traditional `DataFrame.apply` and `DataFrame.applymap` methods, or otherwise, and then add those to the Styler. It will integrate with your website's existing CSS styling.\n",
+ "## Methods to Add Styles\n",
+ "\n",
+ "There are **3 primary methods of adding custom CSS styles** to [Styler][styler]:\n",
"\n",
- "The **disadvantage** of this approach is that it is not easy to transmit files standalone. For example the external CSS must be included or the styling will simply be lost. It is also, as this example shows, not well suited (at a table level) for Jupyter Notebooks. Also this method cannot be used for exporting to Excel, for example, since the external CSS cannot be referenced either by the exporters or by Excel itself."
+ "- Using [.set_table_styles()][table] to control broader areas of the table with specified internal CSS. Although table styles allow the flexibility to add CSS selectors and properties controlling all individual parts of the table, they are unwieldy for individual cell specifications. Also, note that table styles cannot be exported to Excel. \n",
+ "- Using [.set_td_classes()][td_class] to directly link either external CSS classes to your data cells or link the internal CSS classes created by [.set_table_styles()][table]. See [here](#Setting-Classes-and-Linking-to-External-CSS). These cannot be used on column header rows or indexes, and also won't export to Excel. \n",
+ "- Using the [.apply()][apply] and [.applymap()][applymap] functions to add direct internal CSS to specific data cells. See [here](#Styler-Functions). These cannot be used on column header rows or indexes, but only these methods add styles that will export to Excel. These methods work in a similar way to [DataFrame.apply()][dfapply] and [DataFrame.applymap()][dfapplymap].\n",
+ "\n",
+ "[table]: ../reference/api/pandas.io.formats.style.Styler.set_table_styles.rst\n",
+ "[styler]: ../reference/api/pandas.io.formats.style.Styler.rst\n",
+ "[td_class]: ../reference/api/pandas.io.formats.style.Styler.set_td_classes.rst\n",
+ "[apply]: ../reference/api/pandas.io.formats.style.Styler.apply.rst\n",
+ "[applymap]: ../reference/api/pandas.io.formats.style.Styler.applymap.rst\n",
+ "[dfapply]: ../reference/api/pandas.DataFrame.apply.rst\n",
+ "[dfapplymap]: ../reference/api/pandas.DataFrame.applymap.rst"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Using Table Styles\n",
+ "## Table Styles\n",
+ "\n",
+ "Table styles are flexible enough to control all individual parts of the table, including column headers and indexes. \n",
+ "However, they can be unwieldy to type for individual data cells or for any kind of conditional formatting, so we recommend that table styles are used for broad styling, such as entire rows or columns at a time.\n",
"\n",
- "Table styles allow you to control broader areas of the DataFrame, i.e. the whole table or specific columns or rows, with minimal HTML transfer. Much of the functionality of `Styler` uses individual HTML id tags to manipulate the output, which may be inefficient for very large tables. Using `table_styles` and otherwise avoiding using id tags in data cells can greatly reduce the rendered HTML.\n",
+ "Table styles are also used to control features which can apply to the whole table at once such as greating a generic hover functionality. The `:hover` pseudo-selector, as well as other pseudo-selectors, can only be used this way.\n",
"\n",
- "Table styles are also used to control features which can apply to the whole table at once such as greating a generic hover functionality. This `:hover` pseudo-selectors, as well as others, can only be used this way.\n",
+ "To replicate the normal format of CSS selectors and properties (attribute value pairs), e.g. \n",
"\n",
- "`table_styles` are extremely flexible, but not as fun to type out by hand.\n",
- "We hope to collect some useful ones either in pandas, or preferable in a new package that [builds on top](#Extensibility) the tools here."
+ "```\n",
+ "tr:hover {\n",
+ " background-color: #ffff99;\n",
+ "}\n",
+ "```\n",
+ "\n",
+ "the necessary format to pass styles to [.set_table_styles()][table] is as a list of dicts, each with a CSS-selector tag and CSS-properties. Properties can either be a list of 2-tuples, or a regular CSS-string, for example:\n",
+ "\n",
+ "[table]: ../reference/api/pandas.io.formats.style.Styler.set_table_styles.rst"
]
},
{
@@ -175,23 +264,38 @@
"metadata": {},
"outputs": [],
"source": [
- "def hover(hover_color=\"#ffff99\"):\n",
- " return {'selector': \"tr:hover\",\n",
- " 'props': [(\"background-color\", \"%s\" % hover_color)]}\n",
- "\n",
- "styles = [\n",
- " hover(),\n",
- " {'selector': \"th\", 'props': [(\"font-size\", \"150%\"), (\"text-align\", \"center\")]}\n",
- "]\n",
- "\n",
- "df.style.set_table_styles(styles)"
+ "cell_hover = { # for row hover use <tr> instead of <td>\n",
+ " 'selector': 'td:hover',\n",
+ " 'props': [('background-color', '#ffffb3')]\n",
+ "}\n",
+ "index_names = {\n",
+ " 'selector': '.index_name',\n",
+ " 'props': 'font-style: italic; color: darkgrey; font-weight:normal;'\n",
+ "}\n",
+ "headers = {\n",
+ " 'selector': 'th:not(.index_name)',\n",
+ " 'props': 'background-color: #000066; color: white;'\n",
+ "}\n",
+ "s.set_table_styles([cell_hover, index_names, headers])"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "nbsphinx": "hidden"
+ },
+ "outputs": [],
+ "source": [
+ "# Hidden cell to avoid CSS clashes and latter code upcoding previous formatting \n",
+ "s.set_uuid('after_tab_styles1')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "If `table_styles` is given as a dictionary each key should be a specified column or index value and this will map to specific class CSS selectors of the given column or row."
+ "Next we just add a couple more styling artifacts targeting specific parts of the table, and we add some internally defined CSS classes that we need for the next section. Be careful here, since we are *chaining methods* we need to explicitly instruct the method **not to** ``overwrite`` the existing styles."
]
},
{
@@ -200,31 +304,37 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.set_table_styles({\n",
- " 'A': [{'selector': '',\n",
- " 'props': [('color', 'red')]}],\n",
- " 'B': [{'selector': 'td',\n",
- " 'props': [('color', 'blue')]}]\n",
- "}, axis=0)"
+ "s.set_table_styles([\n",
+ " {'selector': 'th.col_heading', 'props': 'text-align: center;'},\n",
+ " {'selector': 'th.col_heading.level0', 'props': 'font-size: 1.5em;'},\n",
+ " {'selector': 'td', 'props': 'text-align: center; font-weight: bold;'},\n",
+ " # internal CSS classes\n",
+ " {'selector': '.true', 'props': 'background-color: #e6ffe6;'},\n",
+ " {'selector': '.false', 'props': 'background-color: #ffe6e6;'},\n",
+ " {'selector': '.border-red', 'props': 'border: 2px dashed red;'},\n",
+ " {'selector': '.border-green', 'props': 'border: 2px dashed green;'},\n",
+ "], overwrite=False)"
]
},
{
"cell_type": "code",
"execution_count": null,
- "metadata": {},
+ "metadata": {
+ "nbsphinx": "hidden"
+ },
"outputs": [],
"source": [
- "df.style.set_table_styles({\n",
- " 3: [{'selector': 'td',\n",
- " 'props': [('color', 'green')]}]\n",
- "}, axis=1)"
+ "# Hidden cell to avoid CSS clashes and latter code upcoding previous formatting \n",
+ "s.set_uuid('after_tab_styles2')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "We can also chain all of the above by setting the `overwrite` argument to `False` so that it preserves previous settings. We also show the CSS string input rather than the list of tuples."
+ "As a convenience method (*since version 1.2.0*) we can also pass a **dict** to [.set_table_styles()][table] which contains row or column keys. Behind the scenes Styler just indexes the keys and adds relevant `.col<m>` or `.row<n>` classes as necessary to the given CSS selectors.\n",
+ "\n",
+ "[table]: ../reference/api/pandas.io.formats.style.Styler.set_table_styles.rst"
]
},
{
@@ -233,27 +343,37 @@
"metadata": {},
"outputs": [],
"source": [
- "from pandas.io.formats.style import Styler\n",
- "s = Styler(df, cell_ids=False, uuid_len=0).\\\n",
- " set_table_styles(styles).\\\n",
- " set_table_styles({\n",
- " 'A': [{'selector': '',\n",
- " 'props': 'color:red;'}],\n",
- " 'B': [{'selector': 'td',\n",
- " 'props': 'color:blue;'}]\n",
- " }, axis=0, overwrite=False).\\\n",
- " set_table_styles({\n",
- " 3: [{'selector': 'td',\n",
- " 'props': 'color:green;font-weight:bold;'}]\n",
- " }, axis=1, overwrite=False)\n",
- "s"
+ "s.set_table_styles({\n",
+ " ('Regression', 'Tumour'): [{'selector': 'th', 'props': 'border-left: 1px solid white'},\n",
+ " {'selector': 'td', 'props': 'border-left: 1px solid #000066'}]\n",
+ "}, overwrite=False, axis=0)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "nbsphinx": "hidden"
+ },
+ "outputs": [],
+ "source": [
+ "# Hidden cell to avoid CSS clashes and latter code upcoding previous formatting \n",
+ "s.set_uuid('xyz01')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "By using these `table_styles` and the additional `Styler` arguments to optimize the HTML we have compressed these styles to only a few lines withing the \\<style\\> tags and none of the \\<td\\> cells require any `id` attributes. "
+ "## Setting Classes and Linking to External CSS\n",
+ "\n",
+ "If you have designed a website then it is likely you will already have an external CSS file that controls the styling of table and cell objects within it. You may want to use these native files rather than duplicate all the CSS in python (and duplicate any maintenance work).\n",
+ "\n",
+ "### Table Attributes\n",
+ "\n",
+ "It is very easy to add a `class` to the main `<table>` using [.set_table_attributes()][tableatt]. This method can also attach inline styles - read more in [CSS Hierarchies](#CSS-Hierarchies).\n",
+ "\n",
+ "[tableatt]: ../reference/api/pandas.io.formats.style.Styler.set_table_attributes.rst"
]
},
{
@@ -262,50 +382,114 @@
"metadata": {},
"outputs": [],
"source": [
- "s.render().split('\\n')[:16]"
+ "out = s.set_table_attributes('class=\"my-table-cls\"').render()\n",
+ "print(out[out.find('<table'):][:109])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "The **advantage** of table styles is obviously the reduced HTML that it can create and the relative ease with which more general parts of the table can be quickly styled, e.g. by applying a generic hover, rather than having to apply a hover to each cell individually. Rows and columns as individual objects can only be styled in this way.\n",
+ "### Data Cell CSS Classes\n",
"\n",
- "The **disadvantage** of being restricted solely to table styles is that you have very limited ability to target and style individual cells based on dynamic criteria. For this, one must use either of the other two methods. Also table level styles cannot be exported to Excel: to format cells for Excel output you must use the Styler Functions method below."
+ "*New in version 1.2.0*\n",
+ "\n",
+ "The [.set_td_classes()][tdclass] method accepts a DataFrame with matching indices and columns to the underlying [Styler][styler]'s DataFrame. That DataFrame will contain strings as css-classes to add to individual data cells: the `<td>` elements of the `<table>`. Here we add our `.true` and `.false` classes that we created previously. We will save adding the borders until the [section on tooltips](#Tooltips).\n",
+ "\n",
+ "[tdclass]: ../reference/api/pandas.io.formats.style.Styler.set_td_classes.rst\n",
+ "[styler]: ../reference/api/pandas.io.formats.style.Styler.rst"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "cell_color = pd.DataFrame([['true ', 'false ', 'true ', 'false '], \n",
+ " ['false ', 'true ', 'false ', 'true ']], \n",
+ " index=df.index, \n",
+ " columns=df.columns[:4])\n",
+ "s.set_td_classes(cell_color)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "nbsphinx": "hidden"
+ },
+ "outputs": [],
+ "source": [
+ "# Hidden cell to avoid CSS clashes and latter code upcoding previous formatting \n",
+ "s.set_uuid('after_classes')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Styler Functions\n",
- "\n",
- "Thirdly we can use the method to pass your style functions into one of the following methods:\n",
- "\n",
- "- ``Styler.applymap``: elementwise\n",
- "- ``Styler.apply``: column-/row-/table-wise\n",
- "\n",
- "Both of those methods take a function (and some other keyword arguments) and applies your function to the DataFrame in a certain way.\n",
- "`Styler.applymap` works through the DataFrame elementwise.\n",
- "`Styler.apply` passes each column or row into your DataFrame one-at-a-time or the entire table at once, depending on the `axis` keyword argument.\n",
- "For columnwise use `axis=0`, rowwise use `axis=1`, and for the entire table at once use `axis=None`.\n",
- "\n",
- "For `Styler.applymap` your function should take a scalar and return a single string with the CSS attribute-value pair.\n",
+ "## Styler Functions\n",
"\n",
- "For `Styler.apply` your function should take a Series or DataFrame (depending on the axis parameter), and return a Series or DataFrame with an identical shape where each value is a string with a CSS attribute-value pair.\n",
+ "We use the following methods to pass your style functions. Both of those methods take a function (and some other keyword arguments) and apply it to the DataFrame in a certain way, rendering CSS styles.\n",
"\n",
- "The **advantage** of this method is that there is full granular control and the output is isolated and easily transferrable, especially in Jupyter Notebooks.\n",
+ "- [.applymap()][applymap] (elementwise): accepts a function that takes a single value and returns a string with the CSS attribute-value pair.\n",
+ "- [.apply()][apply] (column-/row-/table-wise): accepts a function that takes a Series or DataFrame and returns a Series, DataFrame, or numpy array with an identical shape where each element is a string with a CSS attribute-value pair. This method passes each column or row of your DataFrame one-at-a-time or the entire table at once, depending on the `axis` keyword argument. For columnwise use `axis=0`, rowwise use `axis=1`, and for the entire table at once use `axis=None`.\n",
"\n",
- "The **disadvantage** is that the HTML/CSS required to produce this needs to be directly generated from the Python code and it can lead to inefficient data transfer for large tables.\n",
+ "This method is powerful for applying multiple, complex logic to data cells. We create a new DataFrame to demonstrate this.\n",
"\n",
- "Let's see some examples."
+ "[apply]: ../reference/api/pandas.io.formats.style.Styler.apply.rst\n",
+ "[applymap]: ../reference/api/pandas.io.formats.style.Styler.applymap.rst"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "np.random.seed(0)\n",
+ "df2 = pd.DataFrame(np.random.randn(10,4), columns=['A','B','C','D'])\n",
+ "df2.style"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "For example we can build a function that colors text if it is negative, and chain this with a function that partially fades cells of negligible value. Since this looks at each element in turn we use ``applymap``."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def style_negative(v, props=''):\n",
+ " return props if v < 0 else None\n",
+ "s2 = df2.style.applymap(style_negative, props='color:red;')\\\n",
+ " .applymap(lambda v: 'opacity: 20%;' if (v < 0.3) and (v > -0.3) else None)\n",
+ "s2"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "nbsphinx": "hidden"
+ },
+ "outputs": [],
+ "source": [
+ "# Hidden cell to avoid CSS clashes and latter code upcoding previous formatting \n",
+ "s2.set_uuid('after_applymap')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "Let's write a simple style function that will color negative numbers red and positive numbers black."
+ "We can also build a function that highlights the maximum value across rows, cols, and the DataFrame all at once. In this case we use ``apply``. Below we highlight the maximum in a column."
]
},
{
@@ -314,19 +498,28 @@
"metadata": {},
"outputs": [],
"source": [
- "def color_negative_red(val):\n",
- " \"\"\"Color negative scalars red.\"\"\"\n",
- " css = 'color: red;'\n",
- " if val < 0: return css\n",
- " return None"
+ "def highlight_max(s, props=''):\n",
+ " return np.where(s == np.nanmax(s.values), props, '')\n",
+ "s2.apply(highlight_max, props='color:white;background-color:darkblue', axis=0)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "nbsphinx": "hidden"
+ },
+ "outputs": [],
+ "source": [
+ "# Hidden cell to avoid CSS clashes and latter code upcoding previous formatting \n",
+ "s2.set_uuid('after_apply')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "In this case, the cell's style depends only on its own value.\n",
- "That means we should use the `Styler.applymap` method which works elementwise."
+ "We can use the same function across the different axes, highlighting here the DataFrame maximum in purple, and row maximums in pink."
]
},
{
@@ -335,28 +528,34 @@
"metadata": {},
"outputs": [],
"source": [
- "s = df.style.applymap(color_negative_red)\n",
- "s"
+ "s2.apply(highlight_max, props='color:white;background-color:pink;', axis=1)\\\n",
+ " .apply(highlight_max, props='color:white;background-color:purple', axis=None)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "Notice the similarity with the standard `df.applymap`, which operates on DataFrames elementwise. We want you to be able to reuse your existing knowledge of how to interact with DataFrames.\n",
+ "This last example shows how some styles have been overwritten by others. In general the most recent style applied is active but you can read more in the [section on CSS hierarchies](#CSS-Hierarchies). You can also apply these styles to more granular parts of the DataFrame - read more in section on [subset slicing](#Finer-Control-with-Slicing).\n",
"\n",
- "Notice also that our function returned a string containing the CSS attribute and value, separated by a colon just like in a `<style>` tag. This will be a common theme.\n",
+ "It is possible to replicate some of this functionality using just classes but it can be more cumbersome. See [item 3) of Optimization](#Optimization)\n",
"\n",
- "Finally, the input shapes matched. `Styler.applymap` calls the function on each scalar input, and the function returns a scalar output."
+ "<div class=\"alert alert-info\">\n",
+ "\n",
+ "*Debugging Tip*: If you're having trouble writing your style function, try just passing it into ``DataFrame.apply``. Internally, ``Styler.apply`` uses ``DataFrame.apply`` so the result should be the same, and with ``DataFrame.apply`` you will be able to inspect the CSS string output of your intended function in each cell.\n",
+ "\n",
+ "</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "Now suppose you wanted to highlight the maximum value in each column.\n",
- "We can't use `.applymap` anymore since that operated elementwise.\n",
- "Instead, we'll turn to `.apply` which operates columnwise (or rowwise using the `axis` keyword). Later on we'll see that something like `highlight_max` is already defined on `Styler` so you wouldn't need to write this yourself."
+ "## Tooltips and Captions\n",
+ "\n",
+ "Table captions can be added with the [.set_caption()][caption] method. You can use table styles to control the CSS relevant to the caption.\n",
+ "\n",
+ "[caption]: ../reference/api/pandas.io.formats.style.Styler.set_caption.rst"
]
},
{
@@ -365,19 +564,32 @@
"metadata": {},
"outputs": [],
"source": [
- "def highlight_max(s):\n",
- " \"\"\"Highlight the maximum in a Series bold-orange.\"\"\"\n",
- " css = 'background-color: orange; font-weight: bold;'\n",
- " return np.where(s == np.nanmax(s.values), css, None)"
+ "s.set_caption(\"Confusion matrix for multiple cancer prediction models.\")\\\n",
+ " .set_table_styles([{\n",
+ " 'selector': 'caption',\n",
+ " 'props': 'caption-side: bottom; font-size:1.25em;'\n",
+ " }], overwrite=False)"
]
},
{
"cell_type": "code",
"execution_count": null,
- "metadata": {},
+ "metadata": {
+ "nbsphinx": "hidden"
+ },
"outputs": [],
"source": [
- "df.style.apply(highlight_max)"
+ "# Hidden cell to avoid CSS clashes and latter code upcoding previous formatting \n",
+ "s.set_uuid('after_caption')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Adding tooltips (*since version 1.3.0*) can be done using the [.set_tooltips()][tooltips] method in the same way you can add CSS classes to data cells by providing a string based DataFrame with intersecting indices and columns. You don't have to specify a `css_class` name or any css `props` for the tooltips, since there are standard defaults, but the option is there if you want more visual control. \n",
+ "\n",
+ "[tooltips]: ../reference/api/pandas.io.formats.style.Styler.set_tooltips.rst"
]
},
{
@@ -386,22 +598,31 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.apply(highlight_max, axis=1)"
+ "tt = pd.DataFrame([['This model has a very strong true positive rate', \n",
+ " \"This model's total number of false negatives is too high\"]], \n",
+ " index=['Tumour (Positive)'], columns=df.columns[[0,3]])\n",
+ "s.set_tooltips(tt, props='visibility: hidden; position: absolute; z-index: 1; border: 1px solid #000066;'\n",
+ " 'background-color: white; color: #000066; font-size: 0.8em;' \n",
+ " 'transform: translate(0px, -24px); padding: 0.6em; border-radius: 0.5em;')"
]
},
{
- "cell_type": "markdown",
- "metadata": {},
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "nbsphinx": "hidden"
+ },
+ "outputs": [],
"source": [
- "In this case the input is a `Series`, one column (or row) at a time.\n",
- "Notice that the output shape of `highlight_max` matches the input shape, an array with `len(s)` items."
+ "# Hidden cell to avoid CSS clashes and latter code upcoding previous formatting \n",
+ "s.set_uuid('after_tooltips')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "A common use case is also to highlight values based on comparison between columns. Suppose we wish to highlight those cells in columns 'B' and 'C' which are lower than respective values in 'E' then we can write a comparator function. (You can read a little more below in 'Finer Control: Slicing')"
+ "The only thing left to do for our table is to add the highlighting borders to draw the audience attention to the tooltips. **Setting classes always overwrites** so we need to make sure we add the previous classes."
]
},
{
@@ -410,25 +631,40 @@
"metadata": {},
"outputs": [],
"source": [
- "def compare_col(s, comparator=None):\n",
- " css = 'background-color: #00BFFF;'\n",
- " return np.where(s < comparator, css, None)"
+ "cell_border = pd.DataFrame([['border-green ', ' ', ' ', 'border-red '], \n",
+ " [' ', ' ', ' ', ' ']], \n",
+ " index=df.index, \n",
+ " columns=df.columns[:4])\n",
+ "s.set_td_classes(cell_color + cell_border)"
]
},
{
"cell_type": "code",
"execution_count": null,
- "metadata": {},
+ "metadata": {
+ "nbsphinx": "hidden"
+ },
"outputs": [],
"source": [
- "df.style.apply(compare_col, subset=['B', 'C'], comparator=df['E'])"
+ "# Hidden cell to avoid CSS clashes and latter code upcoding previous formatting \n",
+ "s.set_uuid('after_borders')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "We encourage you to use method chains to build up a style piecewise, before finally rending at the end of the chain. Note the ordering of application will affect styles that overlap."
+ "## Finer Control with Slicing\n",
+ "\n",
+ "The examples we have shown so far for the `Styler.apply` and `Styler.applymap` functions have not demonstrated the use of the ``subset`` argument. This is a useful argument which permits a lot of flexibility: it allows you to apply styles to specific rows or columns, without having to code that logic into your `style` function.\n",
+ "\n",
+ "The value passed to `subset` behaves similar to slicing a DataFrame;\n",
+ "\n",
+ "- A scalar is treated as a column label\n",
+ "- A list (or Series or NumPy array) is treated as multiple column labels\n",
+ "- A tuple is treated as `(row_indexer, column_indexer)`\n",
+ "\n",
+ "Consider using `pd.IndexSlice` to construct the tuple for the last one. We will create a MultiIndexed DataFrame to demonstrate the functionality."
]
},
{
@@ -437,22 +673,17 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.\\\n",
- " apply(compare_col, subset=['B', 'C'], comparator=df['E']).\\\n",
- " applymap(color_negative_red).\\\n",
- " apply(highlight_max)"
+ "df3 = pd.DataFrame(np.random.randn(4,4), \n",
+ " pd.MultiIndex.from_product([['A', 'B'], ['r1', 'r2']]),\n",
+ " columns=['c1','c2','c3','c4'])\n",
+ "df3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "Above we used `Styler.apply` to pass in each column (or row) one at a time.\n",
- "\n",
- "<span style=\"background-color: #DEDEBE\">*Debugging Tip*: If you're having trouble writing your style function, try just passing it into <code style=\"background-color: #DEDEBE\">DataFrame.apply</code>. Internally, <code style=\"background-color: #DEDEBE\">Styler.apply</code> uses <code style=\"background-color: #DEDEBE\">DataFrame.apply</code> so the result should be the same.</span>\n",
- "\n",
- "What if you wanted to highlight just the maximum value in the entire table?\n",
- "Use `.apply(function, axis=None)` to indicate that your function wants the entire table, not one column or row at a time. In this case the return must be a DataFrame or ndarray of the same shape as the input. Let's try that next. "
+ "We will use subset to highlight the maximum in the third and fourth columns with red text. We will highlight the subset sliced region in yellow."
]
},
{
@@ -461,35 +692,35 @@
"metadata": {},
"outputs": [],
"source": [
- "s = df.style.apply(highlight_max, axis=None)\n",
- "s"
+ "slice_ = ['c3', 'c4']\n",
+ "df3.style.apply(highlight_max, props='color:red;', axis=0, subset=slice_)\\\n",
+ " .set_properties(**{'background-color': '#ffffb3'}, subset=slice_)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Building Styles Summary\n",
- "\n",
- "Style functions should return strings with one or more CSS `attribute: value` delimited by semicolons. Use\n",
- "\n",
- "- `Styler.applymap(func)` for elementwise styles\n",
- "- `Styler.apply(func, axis=0)` for columnwise styles\n",
- "- `Styler.apply(func, axis=1)` for rowwise styles\n",
- "- `Styler.apply(func, axis=None)` for tablewise styles\n",
- "\n",
- "And crucially the input and output shapes of `func` must match. If `x` is the input then ``func(x).shape == x.shape``."
+ "If combined with the ``IndexSlice`` as suggested then it can index across both dimensions with greater flexibility."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "idx = pd.IndexSlice\n",
+ "slice_ = idx[idx[:,'r1'], idx['c2':'c4']]\n",
+ "df3.style.apply(highlight_max, props='color:red;', axis=0, subset=slice_)\\\n",
+ " .set_properties(**{'background-color': '#ffffb3'}, subset=slice_)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Tooltips\n",
- "\n",
- "*New in version 1.3.0*\n",
- "\n",
- "You can now add tooltips in the same way you can add external CSS classes to datacells by providing a string based DataFrame with intersecting indices and columns."
+ "This also provides the flexibility to sub select rows when used with the `axis=1`."
]
},
{
@@ -498,66 +729,76 @@
"metadata": {},
"outputs": [],
"source": [
- "tt = pd.DataFrame(data=[[None, 'No Data', None], \n",
- " [None, None, 'Missing Data'], \n",
- " ['Maximum value across entire DataFrame', None, None]], \n",
- " index=[0, 3, 9], \n",
- " columns=['A', 'C', 'D'])\n",
- "s.set_tooltips(tt)"
+ "slice_ = idx[idx[:,'r2'], :]\n",
+ "df3.style.apply(highlight_max, props='color:red;', axis=1, subset=slice_)\\\n",
+ " .set_properties(**{'background-color': '#ffffb3'}, subset=slice_)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "The tooltips are added with a default CSS styling, however, you have full control of the tooltips in the following way. The name of the class can be integrated with your existing website's CSS so you do not need to set any properties within Python if you have the external CSS files. "
+ "There is also scope to provide **conditional filtering**. \n",
+ "\n",
+ "Suppose we want to highlight the maximum across columns 2 and 4 only in the case that the sum of columns 1 and 3 is less than -2.0 *(essentially excluding rows* `(:,'r2')`*)*."
]
},
{
"cell_type": "code",
"execution_count": null,
- "metadata": {
- "pycharm": {
- "name": "#%%\n"
- }
- },
+ "metadata": {},
"outputs": [],
"source": [
- "s.set_tooltips_class(name='pd-tt', properties=[\n",
- " ('visibility', 'hidden'),\n",
- " ('position', 'absolute'),\n",
- " ('z-index', '1'),\n",
- " ('background-color', 'blue'),\n",
- " ('color', 'white'),\n",
- " ('font-size', '1.5em'),\n",
- " ('transform', 'translate(3px, -11px)'),\n",
- " ('padding', '0.5em'),\n",
- " ('border', '1px solid red'),\n",
- " ('border-radius', '0.5em')\n",
- "])"
+ "slice_ = idx[idx[(df3['c1'] + df3['c3']) < -2.0], ['c2', 'c4']]\n",
+ "df3.style.apply(highlight_max, props='color:red;', axis=1, subset=slice_)\\\n",
+ " .set_properties(**{'background-color': '#ffffb3'}, subset=slice_)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Finer control: slicing"
+ "Only label-based slicing is supported right now, not positional, and not callables.\n",
+ "\n",
+ "If your style function uses a `subset` or `axis` keyword argument, consider wrapping your function in a `functools.partial`, partialing out that keyword.\n",
+ "\n",
+ "```python\n",
+ "my_func2 = functools.partial(my_func, subset=42)\n",
+ "```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "Both `Styler.apply`, and `Styler.applymap` accept a `subset` keyword.\n",
- "This allows you to apply styles to specific rows or columns, without having to code that logic into your `style` function.\n",
+ "## Optimization\n",
"\n",
- "The value passed to `subset` behaves similar to slicing a DataFrame.\n",
+ "Generally, for smaller tables and most cases, the rendered HTML does not need to be optimized, and we don't really recommend it. There are two cases where it is worth considering:\n",
"\n",
- "- A scalar is treated as a column label\n",
- "- A list (or series or numpy array)\n",
- "- A tuple is treated as `(row_indexer, column_indexer)`\n",
+ " - If you are rendering and styling a very large HTML table, certain browsers have performance issues.\n",
+ " - If you are using ``Styler`` to dynamically create part of online user interfaces and want to improve network performance.\n",
+ " \n",
+ "Here we recommend the following steps to implement:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### 1. Remove UUID and cell_ids\n",
+ "\n",
+ "Ignore the `uuid` and set `cell_ids` to `False`. This will prevent unnecessary HTML."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "<div class=\"alert alert-warning\">\n",
+ "\n",
+ "<font color=red>This is sub-optimal:</font>\n",
"\n",
- "Consider using `pd.IndexSlice` to construct the tuple for the last one."
+ "</div>"
]
},
{
@@ -566,14 +807,19 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.apply(highlight_max, subset=['B', 'C', 'D'])"
+ "df4 = pd.DataFrame([[1,2],[3,4]])\n",
+ "s4 = df4.style"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "For row and column slicing, any valid indexer to `.loc` will work."
+ "<div class=\"alert alert-info\">\n",
+ "\n",
+ "<font color=green>This is better:</font>\n",
+ "\n",
+ "</div>"
]
},
{
@@ -582,31 +828,28 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.applymap(color_negative_red,\n",
- " subset=pd.IndexSlice[2:5, ['B', 'D']])"
+ "from pandas.io.formats.style import Styler\n",
+ "s4 = Styler(df4, uuid_len=0, cell_ids=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "Only label-based slicing is supported right now, not positional.\n",
+ "### 2. Use table styles\n",
"\n",
- "If your style function uses a `subset` or `axis` keyword argument, consider wrapping your function in a `functools.partial`, partialing out that keyword.\n",
- "\n",
- "```python\n",
- "my_func2 = functools.partial(my_func, subset=42)\n",
- "```"
+ "Use table styles where possible (e.g. for all cells or rows or columns at a time) since the CSS is nearly always more efficient than other formats."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Finer Control: Display Values\n",
+ "<div class=\"alert alert-warning\">\n",
+ "\n",
+ "<font color=red>This is sub-optimal:</font>\n",
"\n",
- "We distinguish the *display* value from the *actual* value in `Styler`.\n",
- "To control the display value, the text is printed in each cell, use `Styler.format`. Cells can be formatted according to a [format spec string](https://docs.python.org/3/library/string.html#format-specification-mini-language) or a callable that takes a single value and returns a string."
+ "</div>"
]
},
{
@@ -615,14 +858,19 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.format(\"{:.2%}\")"
+ "props = 'font-family: \"Times New Roman\", Times, serif; color: #e83e8c; font-size:1.3em;'\n",
+ "df4.style.applymap(lambda x: props, subset=[1])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "Use a dictionary to format specific columns."
+ "<div class=\"alert alert-info\">\n",
+ "\n",
+ "<font color=green>This is better:</font>\n",
+ "\n",
+ "</div>"
]
},
{
@@ -631,14 +879,27 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.format({'B': \"{:0<4.0f}\", 'D': '{:+.2f}'})"
+ "df4.style.set_table_styles([{'selector': 'td.col1', 'props': props}])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "Or pass in a callable (or dictionary of callables) for more flexible handling."
+ "### 3. Set classes instead of using Styler functions\n",
+ "\n",
+ "For large DataFrames where the same style is applied to many cells it can be more efficient to declare the styles as classes and then apply those classes to data cells, rather than directly applying styles to cells. It is, however, probably still easier to use the Styler function api when you are not concerned about optimization."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "<div class=\"alert alert-warning\">\n",
+ "\n",
+ "<font color=red>This is sub-optimal:</font>\n",
+ "\n",
+ "</div>"
]
},
{
@@ -647,14 +908,20 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.format({\"B\": lambda x: \"±{:.2f}\".format(abs(x))})"
+ "df2.style.apply(highlight_max, props='color:white;background-color:darkblue;', axis=0)\\\n",
+ " .apply(highlight_max, props='color:white;background-color:pink;', axis=1)\\\n",
+ " .apply(highlight_max, props='color:white;background-color:purple', axis=None)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "You can format the text displayed for missing values by `na_rep`."
+ "<div class=\"alert alert-info\">\n",
+ "\n",
+ "<font color=green>This is better:</font>\n",
+ "\n",
+ "</div>"
]
},
{
@@ -663,14 +930,56 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.format(\"{:.2%}\", na_rep=\"-\")"
+ "build = lambda x: pd.DataFrame(x, index=df2.index, columns=df2.columns)\n",
+ "cls1 = build(df2.apply(highlight_max, props='cls-1 ', axis=0))\n",
+ "cls2 = build(df2.apply(highlight_max, props='cls-2 ', axis=1, result_type='expand').values)\n",
+ "cls3 = build(highlight_max(df2, props='cls-3 '))\n",
+ "df2.style.set_table_styles([\n",
+ " {'selector': '.cls-1', 'props': 'color:white;background-color:darkblue;'},\n",
+ " {'selector': '.cls-2', 'props': 'color:white;background-color:pink;'},\n",
+ " {'selector': '.cls-3', 'props': 'color:white;background-color:purple;'}\n",
+ "]).set_td_classes(cls1 + cls2 + cls3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "These formatting techniques can be used in combination with styling."
+ "### 4. Don't use tooltips\n",
+ "\n",
+ "Tooltips require `cell_ids` to work and they generate extra HTML elements for *every* data cell."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### 5. If every byte counts use string replacement\n",
+ "\n",
+ "You can remove unnecessary HTML, or shorten the default class names with string replace functions."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "html = Styler(df4, uuid_len=0, cell_ids=False)\\\n",
+ " .set_table_styles([{'selector': 'td', 'props': props},\n",
+ " {'selector': '.col1', 'props': 'color:green;'},\n",
+ " {'selector': '.level0', 'props': 'color:blue;'}])\\\n",
+ " .render()\\\n",
+ " .replace('blank', '')\\\n",
+ " .replace('data', '')\\\n",
+ " .replace('level0', 'l0')\\\n",
+ " .replace('col_heading', '')\\\n",
+ " .replace('row_heading', '')\n",
+ "\n",
+ "import re\n",
+ "html = re.sub(r'col[0-9]+', lambda x: x.group().replace('col', 'c'), html)\n",
+ "html = re.sub(r'row[0-9]+', lambda x: x.group().replace('row', 'r'), html)\n",
+ "print(html)"
]
},
{
@@ -679,21 +988,22 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.highlight_max().format(None, na_rep=\"-\")"
+ "from IPython.display import HTML\n",
+ "HTML(html)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Builtin styles"
+ "## Builtin Styles"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "Finally, we expect certain styling functions to be common enough that we've included a few \"built-in\" to the `Styler`, so you don't have to write them yourself."
+ "We expect certain styling functions to be common enough that we've included a few \"built-in\" to the `Styler`, so you don't have to write them yourself."
]
},
{
@@ -702,7 +1012,9 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.highlight_null(null_color='red')"
+ "df2.iloc[0,2] = np.nan\n",
+ "df2.iloc[4,3] = np.nan\n",
+ "df2.loc[:4].style.highlight_null(null_color='red')"
]
},
{
@@ -719,11 +1031,9 @@
"outputs": [],
"source": [
"import seaborn as sns\n",
- "\n",
"cm = sns.light_palette(\"green\", as_cmap=True)\n",
"\n",
- "s = df.style.background_gradient(cmap=cm)\n",
- "s"
+ "df2.style.background_gradient(cmap=cm)"
]
},
{
@@ -740,7 +1050,7 @@
"outputs": [],
"source": [
"# Uses the full color range\n",
- "df.loc[:4].style.background_gradient(cmap='viridis')"
+ "df2.loc[:4].style.background_gradient(cmap='viridis')"
]
},
{
@@ -750,17 +1060,16 @@
"outputs": [],
"source": [
"# Compress the color range\n",
- "(df.loc[:4]\n",
- " .style\n",
- " .background_gradient(cmap='viridis', low=.5, high=0)\n",
- " .highlight_null('red'))"
+ "df2.loc[:4].style\\\n",
+ " .background_gradient(cmap='viridis', low=.5, high=0)\\\n",
+ " .highlight_null('red')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "There's also `.highlight_min` and `.highlight_max`."
+ "There's also `.highlight_min` and `.highlight_max`, which is almost identical to the user defined version we created above, and also a `.highlight_null` method. "
]
},
{
@@ -769,14 +1078,14 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.highlight_max(axis=0)"
+ "df2.loc[:4].style.highlight_max(axis=0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "Use `Styler.set_properties` when the style doesn't actually depend on the values."
+ "Use `Styler.set_properties` when the style doesn't actually depend on the values. This is just a simple wrapper for `.applymap` where the function returns the same properties for all cells."
]
},
{
@@ -785,7 +1094,7 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.set_properties(**{'background-color': 'black',\n",
+ "df2.loc[:4].style.set_properties(**{'background-color': 'black',\n",
" 'color': 'lawngreen',\n",
" 'border-color': 'white'})"
]
@@ -810,14 +1119,14 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.bar(subset=['A', 'B'], color='#d65f5f')"
+ "df2.style.bar(subset=['A', 'B'], color='#d65f5f')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "New in version 0.20.0 is the ability to customize further the bar chart: You can now have the `df.style.bar` be centered on zero or midpoint value (in addition to the already existing way of having the min value at the left side of the cell), and you can pass a list of `[color_negative, color_positive]`.\n",
+ "In version 0.20.0 the ability to customize the bar chart further was given. You can now have the `df.style.bar` be centered on zero or midpoint value (in addition to the already existing way of having the min value at the left side of the cell), and you can pass a list of `[color_negative, color_positive]`.\n",
"\n",
"Here's how you can change the above with the new `align='mid'` option:"
]
@@ -828,7 +1137,7 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.bar(subset=['A', 'B'], align='mid', color=['#d65f5f', '#5fba7d'])"
+ "df2.style.bar(subset=['A', 'B'], align='mid', color=['#d65f5f', '#5fba7d'])"
]
},
{
@@ -841,9 +1150,12 @@
{
"cell_type": "code",
"execution_count": null,
- "metadata": {},
+ "metadata": {
+ "nbsphinx": "hidden"
+ },
"outputs": [],
"source": [
+ "# Hide the construction of the display chart from the user\n",
"import pandas as pd\n",
"from IPython.display import HTML\n",
"\n",
@@ -878,9 +1190,15 @@
" \n",
"head+= \"\"\"\n",
"</tbody>\n",
- "</table>\"\"\"\n",
- " \n",
- "\n",
+ "</table>\"\"\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
"HTML(head)"
]
},
@@ -904,9 +1222,8 @@
"metadata": {},
"outputs": [],
"source": [
- "df2 = -df\n",
- "style1 = df.style.applymap(color_negative_red)\n",
- "style1"
+ "style1 = df2.style.applymap(style_negative, props='color:red;')\\\n",
+ " .applymap(lambda v: 'opacity: 20%;' if (v < 0.3) and (v > -0.3) else None)"
]
},
{
@@ -915,7 +1232,7 @@
"metadata": {},
"outputs": [],
"source": [
- "style2 = df2.style\n",
+ "style2 = df3.style\n",
"style2.use(style1.export())\n",
"style2"
]
@@ -931,37 +1248,33 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Other Options\n",
- "\n",
- "You've seen a few methods for data-driven styling.\n",
- "`Styler` also provides a few other options for styles that don't depend on the data.\n",
- "\n",
- "- precision\n",
- "- captions\n",
- "- table-wide styles\n",
- "- missing values representation\n",
- "- hiding the index or columns\n",
- "\n",
- "Each of these can be specified in two ways:\n",
+ "## Limitations\n",
"\n",
- "- A keyword argument to `Styler.__init__`\n",
- "- A call to one of the `.set_` or `.hide_` methods, e.g. `.set_caption` or `.hide_columns`\n",
+ "- DataFrame only `(use Series.to_frame().style)`\n",
+ "- The index and columns must be unique\n",
+ "- No large repr, and construction performance isn't great; although we have some [HTML optimizations](#Optimization)\n",
+ "- You can only style the *values*, not the index or columns (except with `table_styles` above)\n",
+ "- You can only apply styles, you can't insert new HTML entities\n",
"\n",
- "The best method to use depends on the context. Use the `Styler` constructor when building many styled DataFrames that should all share the same properties. For interactive use, the`.set_` and `.hide_` methods are more convenient."
+ "Some of these might be addressed in the future. "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Precision"
+ "## Other Fun and Useful Stuff\n",
+ "\n",
+ "Here are a few interesting examples."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "You can control the precision of floats using pandas' regular `display.precision` option."
+ "### Widgets\n",
+ "\n",
+ "`Styler` interacts pretty well with widgets. If you're viewing this online instead of running the notebook yourself, you're missing out on interactively adjusting the color palette."
]
},
{
@@ -970,18 +1283,20 @@
"metadata": {},
"outputs": [],
"source": [
- "with pd.option_context('display.precision', 2):\n",
- " html = (df.style\n",
- " .applymap(color_negative_red)\n",
- " .apply(highlight_max))\n",
- "html"
+ "from ipywidgets import widgets\n",
+ "@widgets.interact\n",
+ "def f(h_neg=(0, 359, 1), h_pos=(0, 359), s=(0., 99.9), l=(0., 99.9)):\n",
+ " return df2.style.background_gradient(\n",
+ " cmap=sns.palettes.diverging_palette(h_neg=h_neg, h_pos=h_pos, s=s, l=l,\n",
+ " as_cmap=True)\n",
+ " )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "Or through a `set_precision` method."
+ "### Magnify"
]
},
{
@@ -990,31 +1305,65 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style\\\n",
- " .applymap(color_negative_red)\\\n",
- " .apply(highlight_max)\\\n",
- " .set_precision(2)"
+ "def magnify():\n",
+ " return [dict(selector=\"th\",\n",
+ " props=[(\"font-size\", \"4pt\")]),\n",
+ " dict(selector=\"td\",\n",
+ " props=[('padding', \"0em 0em\")]),\n",
+ " dict(selector=\"th:hover\",\n",
+ " props=[(\"font-size\", \"12pt\")]),\n",
+ " dict(selector=\"tr:hover td:hover\",\n",
+ " props=[('max-width', '200px'),\n",
+ " ('font-size', '12pt')])\n",
+ "]"
]
},
{
- "cell_type": "markdown",
+ "cell_type": "code",
+ "execution_count": null,
"metadata": {},
+ "outputs": [],
"source": [
- "Setting the precision only affects the printed number; the full-precision values are always passed to your style functions. You can always use `df.round(2).style` if you'd prefer to round from the start."
+ "np.random.seed(25)\n",
+ "cmap = cmap=sns.diverging_palette(5, 250, as_cmap=True)\n",
+ "bigdf = pd.DataFrame(np.random.randn(20, 25)).cumsum()\n",
+ "\n",
+ "bigdf.style.background_gradient(cmap, axis=1)\\\n",
+ " .set_properties(**{'max-width': '80px', 'font-size': '1pt'})\\\n",
+ " .set_caption(\"Hover to magnify\")\\\n",
+ " .format(precision=2)\\\n",
+ " .set_table_styles(magnify())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Captions"
+ "### Sticky Headers\n",
+ "\n",
+ "If you display a large matrix or DataFrame in a notebook, but you want to always see the column and row headers you can use the following CSS to make them stick. We might make this into an API function later."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "bigdf = pd.DataFrame(np.random.randn(15, 100))\n",
+ "bigdf.style.set_table_styles([\n",
+ " {'selector': 'thead th', 'props': 'position: sticky; top:0; background-color:salmon;'},\n",
+ " {'selector': 'tbody th', 'props': 'position: sticky; left:0; background-color:lightgreen;'} \n",
+ "])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "Regular table captions can be added and, if necessary, controlled with CSS."
+ "### Hiding Headers\n",
+ "\n",
+ "We don't yet have any API to hide headers so a quick fix is:"
]
},
{
@@ -1023,25 +1372,26 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.set_caption('Colormaps, with a caption.')\\\n",
- " .set_table_styles([{\n",
- " 'selector': \"caption\", 'props': [(\"caption-side\", \"bottom\")]\n",
- " }])\\\n",
- " .background_gradient(cmap=cm)"
+ "df3.style.set_table_styles([{'selector': 'thead tr', 'props': 'display: none;'}]) # or 'thead th'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Missing values"
+ "### HTML Escaping\n",
+ "\n",
+ "Suppose you have to display HTML within HTML, that can be a bit of pain when the renderer can't distinguish. You can use the `escape` formatting option to handle this. Even use it within a formatter that contains HTML itself."
]
},
{
- "cell_type": "markdown",
+ "cell_type": "code",
+ "execution_count": null,
"metadata": {},
+ "outputs": [],
"source": [
- "You can control the default missing values representation for the entire table through `set_na_rep` method."
+ "df4 = pd.DataFrame([['<div></div>', '\"&other\"', '<span></span>']])\n",
+ "df4.style"
]
},
{
@@ -1050,102 +1400,151 @@
"metadata": {},
"outputs": [],
"source": [
- "(df.style\n",
- " .set_na_rep(\"FAIL\")\n",
- " .format(None, na_rep=\"PASS\", subset=[\"D\"])\n",
- " .highlight_null(\"yellow\"))"
+ "# df4.style.format(escape=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Hiding the Index or Columns"
+ "## Export to Excel\n",
+ "\n",
+ "Some support (*since version 0.20.0*) is available for exporting styled `DataFrames` to Excel worksheets using the `OpenPyXL` or `XlsxWriter` engines. CSS2.2 properties handled include:\n",
+ "\n",
+ "- `background-color`\n",
+ "- `color`\n",
+ "- `font-family`\n",
+ "- `font-style`\n",
+ "- `font-weight`\n",
+ "- `text-align`\n",
+ "- `text-decoration`\n",
+ "- `vertical-align`\n",
+ "- `white-space: nowrap`\n",
+ "\n",
+ "\n",
+ "- Currently broken: `border-style`, `border-width`, `border-color` and their {`top`, `right`, `bottom`, `left` variants}\n",
+ "\n",
+ "\n",
+ "- Only CSS2 named colors and hex colors of the form `#rgb` or `#rrggbb` are currently supported.\n",
+ "- The following pseudo CSS properties are also available to set excel specific style properties:\n",
+ " - `number-format`\n",
+ "\n",
+ "Table level styles, and data cell CSS-classes are not included in the export to Excel: individual cells must have their properties mapped by the `Styler.apply` and/or `Styler.applymap` methods."
]
},
{
- "cell_type": "markdown",
+ "cell_type": "code",
+ "execution_count": null,
"metadata": {},
+ "outputs": [],
"source": [
- "The index can be hidden from rendering by calling `Styler.hide_index`. Columns can be hidden from rendering by calling `Styler.hide_columns` and passing in the name of a column, or a slice of columns."
+ "df2.style.\\\n",
+ " applymap(style_negative, props='color:red;').\\\n",
+ " highlight_max(axis=0).\\\n",
+ " to_excel('styled.xlsx', engine='openpyxl')"
]
},
{
- "cell_type": "code",
- "execution_count": null,
+ "cell_type": "markdown",
"metadata": {},
- "outputs": [],
"source": [
- "df.style.hide_index()"
+ "A screenshot of the output:\n",
+ "\n",
+ "\n"
]
},
{
- "cell_type": "code",
- "execution_count": null,
+ "cell_type": "markdown",
"metadata": {},
- "outputs": [],
"source": [
- "df.style.hide_columns(['C','D'])"
+ "## More About CSS and HTML\n",
+ "\n",
+ "Cascading Style Sheet (CSS) language, which is designed to influence how a browser renders HTML elements, has its own peculiarities. It never reports errors: it just silently ignores them and doesn't render your objects how you intend so can sometimes be frustrating. Here is a very brief primer on how ``Styler`` creates HTML and interacts with CSS, with advice on common pitfalls to avoid."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "### CSS classes\n",
+ "### CSS Classes and Ids\n",
"\n",
- "Certain CSS classes are attached to cells.\n",
+ "The precise structure of the CSS `class` attached to each cell is as follows.\n",
"\n",
- "- Index and Column names include `index_name` and `level<k>` where `k` is its level in a MultiIndex\n",
+ "- Cells with Index and Column names include `index_name` and `level<k>` where `k` is its level in a MultiIndex\n",
"- Index label cells include\n",
" + `row_heading`\n",
- " + `row<n>` where `n` is the numeric position of the row\n",
" + `level<k>` where `k` is the level in a MultiIndex\n",
+ " + `row<m>` where `m` is the numeric position of the row\n",
"- Column label cells include\n",
" + `col_heading`\n",
- " + `col<n>` where `n` is the numeric position of the column\n",
" + `level<k>` where `k` is the level in a MultiIndex\n",
+ " + `col<n>` where `n` is the numeric position of the column\n",
+ "- Data cells include\n",
+ " + `data`\n",
+ " + `row<m>`, where `m` is the numeric position of the cell.\n",
+ " + `col<n>`, where `n` is the numeric position of the cell.\n",
"- Blank cells include `blank`\n",
- "- Data cells include `data`"
+ "\n",
+ "The structure of the `id` is `T_uuid_level<k>_row<m>_col<n>` where `level<k>` is used only on headings, and headings will only have either `row<m>` or `col<n>` whichever is needed. By default we've also prepended each row/column identifier with a UUID unique to each DataFrame so that the style from one doesn't collide with the styling from another within the same notebook or page. You can read more about the use of UUIDs in [Optimization](#Optimization).\n",
+ "\n",
+ "We can see example of the HTML by calling the [.render()][render] method.\n",
+ "\n",
+ "[render]: ../reference/api/pandas.io.formats.style.Styler.render.rst"
]
},
{
- "cell_type": "markdown",
+ "cell_type": "code",
+ "execution_count": null,
"metadata": {},
+ "outputs": [],
"source": [
- "### Limitations\n",
- "\n",
- "- DataFrame only `(use Series.to_frame().style)`\n",
- "- The index and columns must be unique\n",
- "- No large repr, and performance isn't great; this is intended for summary DataFrames\n",
- "- You can only style the *values*, not the index or columns (except with `table_styles` above)\n",
- "- You can only apply styles, you can't insert new HTML entities\n",
- "\n",
- "Some of these will be addressed in the future.\n",
- "Performance can suffer when adding styles to each cell in a large DataFrame.\n",
- "It is recommended to apply table or column based styles where possible to limit overall HTML length, as well as setting a shorter UUID to avoid unnecessary repeated data transmission. \n"
+ "print(pd.DataFrame([[1,2],[3,4]], index=['i1', 'i2'], columns=['c1', 'c2']).style.render())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "### Terms\n",
+ "### CSS Hierarchies\n",
"\n",
- "- Style function: a function that's passed into `Styler.apply` or `Styler.applymap` and returns values like `'css attribute: value'`\n",
- "- Builtin style functions: style functions that are methods on `Styler`\n",
- "- table style: a dictionary with the two keys `selector` and `props`. `selector` is the CSS selector that `props` will apply to. `props` is a list of `(attribute, value)` tuples. A list of table styles passed into `Styler`."
+ "The examples have shown that when CSS styles overlap, the one that comes last in the HTML render, takes precedence. So the following yield different results:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "df4 = pd.DataFrame([['text']])\n",
+ "df4.style.applymap(lambda x: 'color:green;')\\\n",
+ " .applymap(lambda x: 'color:red;')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "df4.style.applymap(lambda x: 'color:red;')\\\n",
+ " .applymap(lambda x: 'color:green;')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Fun stuff\n",
+ "This is only true for CSS rules that are equivalent in hierarchy, or importance. You can read more about [CSS specificity here](https://www.w3schools.com/css/css_specificity.asp) but for our purposes it suffices to summarize the key points:\n",
"\n",
- "Here are a few interesting examples.\n",
+ "A CSS importance score for each HTML element is derived by starting at zero and adding:\n",
"\n",
- "`Styler` interacts pretty well with widgets. If you're viewing this online instead of running the notebook yourself, you're missing out on interactively adjusting the color palette."
+ " - 1000 for an inline style attribute\n",
+ " - 100 for each ID\n",
+ " - 10 for each attribute, class or pseudo-class\n",
+ " - 1 for each element name or pseudo-element\n",
+ " \n",
+ "Let's use this to describe the action of the following configurations"
]
},
{
@@ -1154,13 +1553,16 @@
"metadata": {},
"outputs": [],
"source": [
- "from ipywidgets import widgets\n",
- "@widgets.interact\n",
- "def f(h_neg=(0, 359, 1), h_pos=(0, 359), s=(0., 99.9), l=(0., 99.9)):\n",
- " return df.style.background_gradient(\n",
- " cmap=sns.palettes.diverging_palette(h_neg=h_neg, h_pos=h_pos, s=s, l=l,\n",
- " as_cmap=True)\n",
- " )"
+ "df4.style.set_uuid('a_')\\\n",
+ " .set_table_styles([{'selector': 'td', 'props': 'color:red;'}])\\\n",
+ " .applymap(lambda x: 'color:green;')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This text is red because the generated selector `#T_a_ td` is worth 101 (ID plus element), whereas `#T_a_row0_col0` is only worth 100 (ID), so is considered inferior even though in the HTML it comes after the previous."
]
},
{
@@ -1169,17 +1571,18 @@
"metadata": {},
"outputs": [],
"source": [
- "def magnify():\n",
- " return [dict(selector=\"th\",\n",
- " props=[(\"font-size\", \"4pt\")]),\n",
- " dict(selector=\"td\",\n",
- " props=[('padding', \"0em 0em\")]),\n",
- " dict(selector=\"th:hover\",\n",
- " props=[(\"font-size\", \"12pt\")]),\n",
- " dict(selector=\"tr:hover td:hover\",\n",
- " props=[('max-width', '200px'),\n",
- " ('font-size', '12pt')])\n",
- "]"
+ "df4.style.set_uuid('b_')\\\n",
+ " .set_table_styles([{'selector': 'td', 'props': 'color:red;'},\n",
+ " {'selector': '.cls-1', 'props': 'color:blue;'}])\\\n",
+ " .applymap(lambda x: 'color:green;')\\\n",
+ " .set_td_classes(pd.DataFrame([['cls-1']]))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In the above case the text is blue because the selector `#T_b_ .cls-1` is worth 110 (ID plus class), which takes precendence."
]
},
{
@@ -1188,46 +1591,21 @@
"metadata": {},
"outputs": [],
"source": [
- "np.random.seed(25)\n",
- "cmap = cmap=sns.diverging_palette(5, 250, as_cmap=True)\n",
- "bigdf = pd.DataFrame(np.random.randn(20, 25)).cumsum()\n",
- "\n",
- "bigdf.style.background_gradient(cmap, axis=1)\\\n",
- " .set_properties(**{'max-width': '80px', 'font-size': '1pt'})\\\n",
- " .set_caption(\"Hover to magnify\")\\\n",
- " .set_precision(2)\\\n",
- " .set_table_styles(magnify())"
+ "df4.style.set_uuid('c_')\\\n",
+ " .set_table_styles([{'selector': 'td', 'props': 'color:red;'},\n",
+ " {'selector': '.cls-1', 'props': 'color:blue;'},\n",
+ " {'selector': 'td.data', 'props': 'color:yellow;'}])\\\n",
+ " .applymap(lambda x: 'color:green;')\\\n",
+ " .set_td_classes(pd.DataFrame([['cls-1']]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "## Export to Excel\n",
- "\n",
- "*New in version 0.20.0*\n",
- "\n",
- "<span style=\"color: red\">*Experimental: This is a new feature and still under development. We'll be adding features and possibly making breaking changes in future releases. We'd love to hear your feedback.*</span>\n",
- "\n",
- "Some support is available for exporting styled `DataFrames` to Excel worksheets using the `OpenPyXL` or `XlsxWriter` engines. CSS2.2 properties handled include:\n",
- "\n",
- "- `background-color`\n",
- "- `border-style`, `border-width`, `border-color` and their {`top`, `right`, `bottom`, `left` variants}\n",
- "- `color`\n",
- "- `font-family`\n",
- "- `font-style`\n",
- "- `font-weight`\n",
- "- `text-align`\n",
- "- `text-decoration`\n",
- "- `vertical-align`\n",
- "- `white-space: nowrap`\n",
- "\n",
- "\n",
- "- Only CSS2 named colors and hex colors of the form `#rgb` or `#rrggbb` are currently supported.\n",
- "- The following pseudo CSS properties are also available to set excel specific style properties:\n",
- " - `number-format`\n",
+ "Now we have created another table style this time the selector `T_c_ td.data` (ID plus element plus class) gets bumped up to 111. \n",
"\n",
- "Table level styles are not included in the export to Excel: individual cells must have their properties mapped by the `Styler.apply` and/or `Styler.applymap` methods."
+ "If your style fails to be applied, and its really frustrating, try the `!important` trump card."
]
},
{
@@ -1236,19 +1614,19 @@
"metadata": {},
"outputs": [],
"source": [
- "df.style.\\\n",
- " applymap(color_negative_red).\\\n",
- " apply(highlight_max).\\\n",
- " to_excel('styled.xlsx', engine='openpyxl')"
+ "df4.style.set_uuid('d_')\\\n",
+ " .set_table_styles([{'selector': 'td', 'props': 'color:red;'},\n",
+ " {'selector': '.cls-1', 'props': 'color:blue;'},\n",
+ " {'selector': 'td.data', 'props': 'color:yellow;'}])\\\n",
+ " .applymap(lambda x: 'color:green !important;')\\\n",
+ " .set_td_classes(pd.DataFrame([['cls-1']]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "A screenshot of the output:\n",
- "\n",
- "\n"
+ "Finally got that green text after all!"
]
},
{
@@ -1340,7 +1718,7 @@
"metadata": {},
"outputs": [],
"source": [
- "MyStyler(df)"
+ "MyStyler(df3)"
]
},
{
@@ -1356,7 +1734,7 @@
"metadata": {},
"outputs": [],
"source": [
- "HTML(MyStyler(df).render(table_title=\"Extending Example\"))"
+ "HTML(MyStyler(df3).render(table_title=\"Extending Example\"))"
]
},
{
@@ -1373,7 +1751,7 @@
"outputs": [],
"source": [
"EasyStyler = Styler.from_custom_template(\"templates\", \"myhtml.tpl\")\n",
- "EasyStyler(df)"
+ "EasyStyler(df3)"
]
},
{
@@ -1410,13 +1788,13 @@
},
"outputs": [],
"source": [
- "# Hack to get the same style in the notebook as the\n",
- "# main site. This is hidden in the docs.\n",
- "from IPython.display import HTML\n",
- "with open(\"themes/nature_with_gtoc/static/nature.css_t\") as f:\n",
- " css = f.read()\n",
+ "# # Hack to get the same style in the notebook as the\n",
+ "# # main site. This is hidden in the docs.\n",
+ "# from IPython.display import HTML\n",
+ "# with open(\"themes/nature_with_gtoc/static/nature.css_t\") as f:\n",
+ "# css = f.read()\n",
" \n",
- "HTML('<style>{}</style>'.format(css))"
+ "# HTML('<style>{}</style>'.format(css))"
]
}
],
diff --git a/doc/source/user_guide/visualization.rst b/doc/source/user_guide/visualization.rst
index 8b41cc24829c5..7b2c8478e71af 100644
--- a/doc/source/user_guide/visualization.rst
+++ b/doc/source/user_guide/visualization.rst
@@ -2,9 +2,12 @@
{{ header }}
-*************
-Visualization
-*************
+*******************
+Chart Visualization
+*******************
+
+This section demonstrates visualization through charting. For information on
+visualization of tabular data please see the section on `Table Visualization <style.ipynb>`_.
We use the standard convention for referencing the matplotlib API:
| - [x] closes #39593
- [x] closes #40645
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
This renames `Styling` with `Table Visualization` and aligns it more with `Chart Visualization`.
It re-organises some of the `Styler` user guide, removing outdated material, including new material with examples. | https://api.github.com/repos/pandas-dev/pandas/pulls/39720 | 2021-02-10T10:14:09Z | 2021-03-29T15:55:19Z | 2021-03-29T15:55:19Z | 2021-03-29T17:00:08Z |
[ArrayManager] Test DataFrame reductions + implement ignore_failures | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 461363d295f6a..a2162f2e66b36 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -153,6 +153,9 @@ jobs:
run: |
source activate pandas-dev
pytest pandas/tests/frame/methods --array-manager
+ pytest pandas/tests/frame/test_reductions.py --array-manager
+ pytest pandas/tests/reductions/ --array-manager
+ pytest pandas/tests/generic/test_generic.py --array-manager
pytest pandas/tests/arithmetic/ --array-manager
pytest pandas/tests/reshape/merge --array-manager
diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py
index cd8d3e547abbd..97d1303824cd4 100644
--- a/pandas/core/internals/array_manager.py
+++ b/pandas/core/internals/array_manager.py
@@ -16,7 +16,10 @@
import numpy as np
-from pandas._libs import lib
+from pandas._libs import (
+ NaT,
+ lib,
+)
from pandas._typing import (
ArrayLike,
DtypeObj,
@@ -33,6 +36,8 @@
is_dtype_equal,
is_extension_array_dtype,
is_numeric_dtype,
+ is_object_dtype,
+ is_timedelta64_ns_dtype,
)
from pandas.core.dtypes.dtypes import (
ExtensionDtype,
@@ -50,7 +55,11 @@
import pandas.core.algorithms as algos
from pandas.core.arrays import ExtensionArray
from pandas.core.arrays.sparse import SparseDtype
-from pandas.core.construction import extract_array
+from pandas.core.construction import (
+ ensure_wrapped_if_datetimelike,
+ extract_array,
+ sanitize_array,
+)
from pandas.core.indexers import maybe_convert_indices
from pandas.core.indexes.api import (
Index,
@@ -201,18 +210,48 @@ def _verify_integrity(self) -> None:
def reduce(
self: T, func: Callable, ignore_failures: bool = False
) -> Tuple[T, np.ndarray]:
- # TODO this still fails because `func` assumes to work on 2D arrays
- # TODO implement ignore_failures
- assert self.ndim == 2
+ """
+ Apply reduction function column-wise, returning a single-row ArrayManager.
- res_arrays = []
- for arr in self.arrays:
- res = func(arr, axis=0)
- res_arrays.append(np.array([res]))
+ Parameters
+ ----------
+ func : reduction function
+ ignore_failures : bool, default False
+ Whether to drop columns where func raises TypeError.
- index = Index([None]) # placeholder
- new_mgr = type(self)(res_arrays, [index, self.items])
- indexer = np.arange(self.shape[0])
+ Returns
+ -------
+ ArrayManager
+ np.ndarray
+ Indexer of column indices that are retained.
+ """
+ result_arrays: List[np.ndarray] = []
+ result_indices: List[int] = []
+ for i, arr in enumerate(self.arrays):
+ try:
+ res = func(arr, axis=0)
+ except TypeError:
+ if not ignore_failures:
+ raise
+ else:
+ # TODO NaT doesn't preserve dtype, so we need to ensure to create
+ # a timedelta result array if original was timedelta
+ # what if datetime results in timedelta? (eg std)
+ if res is NaT and is_timedelta64_ns_dtype(arr.dtype):
+ result_arrays.append(np.array(["NaT"], dtype="timedelta64[ns]"))
+ else:
+ result_arrays.append(sanitize_array([res], None))
+ result_indices.append(i)
+
+ index = Index._simple_new(np.array([None], dtype=object)) # placeholder
+ if ignore_failures:
+ indexer = np.array(result_indices)
+ columns = self.items[result_indices]
+ else:
+ indexer = np.arange(self.shape[0])
+ columns = self.items
+
+ new_mgr = type(self)(result_arrays, [index, columns])
return new_mgr, indexer
def operate_blockwise(self, other: ArrayManager, array_op) -> ArrayManager:
@@ -489,14 +528,17 @@ def _get_data_subset(self, predicate: Callable) -> ArrayManager:
def get_bool_data(self, copy: bool = False) -> ArrayManager:
"""
- Select columns that are bool-dtype.
+ Select columns that are bool-dtype and object-dtype columns that are all-bool.
Parameters
----------
copy : bool, default False
Whether to copy the blocks
"""
- return self._get_data_subset(lambda arr: is_bool_dtype(arr.dtype))
+ return self._get_data_subset(
+ lambda arr: is_bool_dtype(arr.dtype)
+ or (is_object_dtype(arr.dtype) and lib.is_bool_array(arr))
+ )
def get_numeric_data(self, copy: bool = False) -> ArrayManager:
"""
@@ -693,6 +735,10 @@ def iset(self, loc: Union[int, slice, np.ndarray], value):
assert value.shape[1] == 1
value = value[0, :]
+ # TODO we receive a datetime/timedelta64 ndarray from DataFrame._iset_item
+ # but we should avoid that and pass directly the proper array
+ value = ensure_wrapped_if_datetimelike(value)
+
assert isinstance(value, (np.ndarray, ExtensionArray))
assert value.ndim == 1
assert len(value) == len(self._axes[0])
diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py
index decff32baa970..e3145e0cc5c9f 100644
--- a/pandas/tests/reductions/test_reductions.py
+++ b/pandas/tests/reductions/test_reductions.py
@@ -6,6 +6,8 @@
import numpy as np
import pytest
+import pandas.util._test_decorators as td
+
import pandas as pd
from pandas import (
Categorical,
@@ -291,6 +293,7 @@ def test_numpy_minmax_timedelta64(self):
with pytest.raises(ValueError, match=errmsg):
np.argmax(td, out=0)
+ @td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) quantile
def test_timedelta_ops(self):
# GH#4984
# make sure ops return Timedelta
| xref https://github.com/pandas-dev/pandas/issues/39146
This adds support for ignoring failures in `ArrayManager.reduce`.
| https://api.github.com/repos/pandas-dev/pandas/pulls/39719 | 2021-02-10T09:53:00Z | 2021-02-25T00:39:26Z | 2021-02-25T00:39:26Z | 2021-02-25T08:08:18Z |
DOC: Group optional dependencies by category | diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst
index 1ee8e3401e7f4..291799cfe521d 100644
--- a/doc/source/getting_started/install.rst
+++ b/doc/source/getting_started/install.rst
@@ -255,47 +255,52 @@ For example, :func:`pandas.read_hdf` requires the ``pytables`` package, while
optional dependency is not installed, pandas will raise an ``ImportError`` when
the method requiring that dependency is called.
+Visualization
+^^^^^^^^^^^^^
+
========================= ================== =============================================================
Dependency Minimum Version Notes
========================= ================== =============================================================
-BeautifulSoup4 4.6.0 HTML parser for read_html (see :ref:`note <optional_html>`)
+matplotlib 2.2.3 Plotting library
Jinja2 2.10 Conditional formatting with DataFrame.style
-PyQt4 Clipboard I/O
-PyQt5 Clipboard I/O
-PyTables 3.5.1 HDF5-based reading / writing
-SQLAlchemy 1.3.0 SQL support for databases other than sqlite
+tabulate 0.8.7 Printing in Markdown-friendly format (see `tabulate`_)
+========================= ================== =============================================================
+
+Computation
+^^^^^^^^^^^
+
+========================= ================== =============================================================
+Dependency Minimum Version Notes
+========================= ================== =============================================================
SciPy 1.12.0 Miscellaneous statistical functions
-xlsxwriter 1.0.2 Excel writing
-blosc 1.17.0 Compression for HDF5
-fsspec 0.7.4 Handling files aside from local and HTTP
-fastparquet 0.4.0 Parquet reading / writing
-gcsfs 0.6.0 Google Cloud Storage access
-html5lib 1.0.1 HTML parser for read_html (see :ref:`note <optional_html>`)
-lxml 4.3.0 HTML parser for read_html (see :ref:`note <optional_html>`)
-matplotlib 2.2.3 Visualization
numba 0.46.0 Alternative execution engine for rolling operations
+ (see :ref:`Enhancing Performance <enhancingperf.numba>`)
+xarray 0.12.3 pandas-like API for N-dimensional data
+========================= ================== =============================================================
+
+Excel files
+^^^^^^^^^^^
+
+========================= ================== =============================================================
+Dependency Minimum Version Notes
+========================= ================== =============================================================
+xlrd 1.2.0 Reading Excel
+xlwt 1.3.0 Writing Excel
+xlsxwriter 1.0.2 Writing Excel
openpyxl 3.0.0 Reading / writing for xlsx files
-pandas-gbq 0.12.0 Google Big Query access
-psycopg2 2.7 PostgreSQL engine for sqlalchemy
-pyarrow 0.15.0 Parquet, ORC, and feather reading / writing
-pymysql 0.8.1 MySQL engine for sqlalchemy
-pyreadstat SPSS files (.sav) reading
pyxlsb 1.0.6 Reading for xlsb files
-qtpy Clipboard I/O
-s3fs 0.4.0 Amazon S3 access
-tabulate 0.8.7 Printing in Markdown-friendly format (see `tabulate`_)
-xarray 0.12.3 pandas-like API for N-dimensional data
-xclip Clipboard I/O on linux
-xlrd 1.2.0 Excel reading
-xlwt 1.3.0 Excel writing
-xsel Clipboard I/O on linux
-zlib Compression for HDF5
========================= ================== =============================================================
-.. _optional_html:
+HTML
+^^^^
-Optional dependencies for parsing HTML
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+========================= ================== =============================================================
+Dependency Minimum Version Notes
+========================= ================== =============================================================
+BeautifulSoup4 4.6.0 HTML parser for read_html
+html5lib 1.0.1 HTML parser for read_html
+lxml 4.3.0 HTML parser for read_html
+========================= ================== =============================================================
One of the following combinations of libraries is needed to use the
top-level :func:`~pandas.read_html` function:
@@ -320,3 +325,52 @@ top-level :func:`~pandas.read_html` function:
.. _BeautifulSoup4: https://www.crummy.com/software/BeautifulSoup
.. _lxml: https://lxml.de
.. _tabulate: https://github.com/astanin/python-tabulate
+
+SQL databases
+^^^^^^^^^^^^^
+
+========================= ================== =============================================================
+Dependency Minimum Version Notes
+========================= ================== =============================================================
+SQLAlchemy 1.3.0 SQL support for databases other than sqlite
+psycopg2 2.7 PostgreSQL engine for sqlalchemy
+pymysql 0.8.1 MySQL engine for sqlalchemy
+========================= ================== =============================================================
+
+Other data sources
+^^^^^^^^^^^^^^^^^^
+
+========================= ================== =============================================================
+Dependency Minimum Version Notes
+========================= ================== =============================================================
+PyTables 3.5.1 HDF5-based reading / writing
+blosc 1.17.0 Compression for HDF5
+zlib Compression for HDF5
+fastparquet 0.4.0 Parquet reading / writing
+pyarrow 0.15.0 Parquet, ORC, and feather reading / writing
+pyreadstat SPSS files (.sav) reading
+========================= ================== =============================================================
+
+Access data in the cloud
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+========================= ================== =============================================================
+Dependency Minimum Version Notes
+========================= ================== =============================================================
+fsspec 0.7.4 Handling files aside from simple local and HTTP
+gcsfs 0.6.0 Google Cloud Storage access
+pandas-gbq 0.12.0 Google Big Query access
+s3fs 0.4.0 Amazon S3 access
+========================= ================== =============================================================
+
+Clipboard
+^^^^^^^^^
+
+========================= ================== =============================================================
+Dependency Minimum Version Notes
+========================= ================== =============================================================
+PyQt4/PyQt5 Clipboard I/O
+qtpy Clipboard I/O
+xclip Clipboard I/O on linux
+xsel Clipboard I/O on linux
+========================= ================== =============================================================
| - [x] closes #39594
- [ ] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
This PR splits the Optional Dependencies table into multiple tables one for each category. It should help people compare different options when looking for a specific capability, e.g. "I need to read an Excel file. What are my options?".
The specific grouping felt pretty subjective. If you think of a better way to group them, we can do that instead. | https://api.github.com/repos/pandas-dev/pandas/pulls/39715 | 2021-02-10T06:39:20Z | 2021-02-22T23:20:50Z | 2021-02-22T23:20:50Z | 2021-02-22T23:50:10Z |
REF: implement ensure_can_hold_na | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 67e9aaa99debd..77c7db6a07698 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -475,7 +475,8 @@ def maybe_upcast_putmask(result: np.ndarray, mask: np.ndarray) -> np.ndarray:
# upcast (possibly), otherwise we DON't want to upcast (e.g. if we
# have values, say integers, in the success portion then it's ok to not
# upcast)
- new_dtype, _ = maybe_promote(result.dtype, np.nan)
+ new_dtype = ensure_dtype_can_hold_na(result.dtype)
+
if new_dtype != result.dtype:
result = result.astype(new_dtype, copy=True)
@@ -484,7 +485,21 @@ def maybe_upcast_putmask(result: np.ndarray, mask: np.ndarray) -> np.ndarray:
return result
-def maybe_promote(dtype, fill_value=np.nan):
+def ensure_dtype_can_hold_na(dtype: DtypeObj) -> DtypeObj:
+ """
+ If we have a dtype that cannot hold NA values, find the best match that can.
+ """
+ if isinstance(dtype, ExtensionDtype):
+ # TODO: ExtensionDtype.can_hold_na?
+ return dtype
+ elif dtype.kind == "b":
+ return np.dtype(object)
+ elif dtype.kind in ["i", "u"]:
+ return np.dtype(np.float64)
+ return dtype
+
+
+def maybe_promote(dtype: DtypeObj, fill_value=np.nan):
"""
Find the minimal dtype that can hold both the given dtype and fill_value.
@@ -565,7 +580,7 @@ def maybe_promote(dtype, fill_value=np.nan):
fill_value = np.timedelta64("NaT", "ns")
else:
fill_value = fv.to_timedelta64()
- elif is_datetime64tz_dtype(dtype):
+ elif isinstance(dtype, DatetimeTZDtype):
if isna(fill_value):
fill_value = NaT
elif not isinstance(fill_value, datetime):
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py
index 3dcfa85ed5c08..35af0dae2bce3 100644
--- a/pandas/core/internals/concat.py
+++ b/pandas/core/internals/concat.py
@@ -11,9 +11,8 @@
from pandas._typing import ArrayLike, DtypeObj, Manager, Shape
from pandas.util._decorators import cache_readonly
-from pandas.core.dtypes.cast import find_common_type, maybe_promote
+from pandas.core.dtypes.cast import ensure_dtype_can_hold_na, find_common_type
from pandas.core.dtypes.common import (
- get_dtype,
is_categorical_dtype,
is_datetime64_dtype,
is_datetime64tz_dtype,
@@ -225,13 +224,13 @@ def needs_filling(self) -> bool:
@cache_readonly
def dtype(self):
- if self.block is None:
+ blk = self.block
+ if blk is None:
raise AssertionError("Block is None, no dtype")
if not self.needs_filling:
- return self.block.dtype
- else:
- return get_dtype(maybe_promote(self.block.dtype, self.block.fill_value)[0])
+ return blk.dtype
+ return ensure_dtype_can_hold_na(blk.dtype)
@cache_readonly
def is_na(self) -> bool:
| Much simpler than maybe_promote, which for the most part id like to replace with something like
```
def maybe_promote(dtype, fill_value):
inferred, fv = infer_dtype_from(fill_value)
new_dtype = find_common_type([dtype, inferred])
return inferred, fv
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/39714 | 2021-02-10T05:33:06Z | 2021-02-10T18:41:25Z | 2021-02-10T18:41:25Z | 2021-02-10T18:51:57Z |
Backport PR #39709 on branch 1.2.x (CI: pin numpydoc) | diff --git a/environment.yml b/environment.yml
index a5b61220f88f3..ac696b95f6ba9 100644
--- a/environment.yml
+++ b/environment.yml
@@ -114,4 +114,4 @@ dependencies:
- natsort # DataFrame.sort_values
- pip:
- git+https://github.com/pandas-dev/pydata-sphinx-theme.git@2488b7defbd3d753dd5fcfc890fc4a7e79d25103
- - git+https://github.com/numpy/numpydoc
+ - numpydoc < 1.2 # 2021-02-09 1.2dev breaking CI
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 3a992f8899139..92a98fbb0547c 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -77,4 +77,4 @@ pyreadstat
tabulate>=0.8.3
natsort
git+https://github.com/pandas-dev/pydata-sphinx-theme.git@2488b7defbd3d753dd5fcfc890fc4a7e79d25103
-git+https://github.com/numpy/numpydoc
+numpydoc < 1.2
| Backport PR #39709: CI: pin numpydoc | https://api.github.com/repos/pandas-dev/pandas/pulls/39712 | 2021-02-10T00:32:25Z | 2021-02-10T10:26:20Z | 2021-02-10T10:26:20Z | 2021-02-10T10:26:20Z |
REF: Rename is_valid_nat_for_dtype -> is_valid_na_for_dtype | diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 13da3df93af14..99777bc2f169e 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -54,7 +54,7 @@
)
from pandas.core.dtypes.dtypes import CategoricalDtype
from pandas.core.dtypes.generic import ABCIndex, ABCSeries
-from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna, notna
+from pandas.core.dtypes.missing import is_valid_na_for_dtype, isna, notna
from pandas.core import ops
from pandas.core.accessor import PandasDelegate, delegate_names
@@ -1284,7 +1284,7 @@ def _validate_fill_value(self, fill_value):
TypeError
"""
- if is_valid_nat_for_dtype(fill_value, self.categories.dtype):
+ if is_valid_na_for_dtype(fill_value, self.categories.dtype):
fill_value = -1
elif fill_value in self.categories:
fill_value = self._unbox_scalar(fill_value)
@@ -1779,7 +1779,7 @@ def __contains__(self, key) -> bool:
Returns True if `key` is in this Categorical.
"""
# if key is a NaN, check if any NaN is in self.
- if is_valid_nat_for_dtype(key, self.categories.dtype):
+ if is_valid_na_for_dtype(key, self.categories.dtype):
return self.isna().any()
return contains(self, key, container=self._codes)
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 5ee7a5715d6af..48df98930244a 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -57,7 +57,7 @@
is_unsigned_integer_dtype,
pandas_dtype,
)
-from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna
+from pandas.core.dtypes.missing import is_valid_na_for_dtype, isna
from pandas.core import nanops, ops
from pandas.core.algorithms import checked_add_with_arr, isin, unique1d
@@ -493,7 +493,7 @@ def _validate_fill_value(self, fill_value):
def _validate_shift_value(self, fill_value):
# TODO(2.0): once this deprecation is enforced, use _validate_fill_value
- if is_valid_nat_for_dtype(fill_value, self.dtype):
+ if is_valid_na_for_dtype(fill_value, self.dtype):
fill_value = NaT
elif isinstance(fill_value, self._recognized_scalars):
# pandas\core\arrays\datetimelike.py:746: error: Too many arguments
@@ -557,7 +557,7 @@ def _validate_scalar(
msg = self._validation_error_message(value, allow_listlike)
raise TypeError(msg) from err
- elif is_valid_nat_for_dtype(value, self.dtype):
+ elif is_valid_na_for_dtype(value, self.dtype):
# GH#18295
value = NaT
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index f4db68a2d7ac5..0f3e028c34c05 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -43,7 +43,7 @@
ABCPeriodIndex,
ABCSeries,
)
-from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna, notna
+from pandas.core.dtypes.missing import is_valid_na_for_dtype, isna, notna
from pandas.core.algorithms import isin, take, value_counts
from pandas.core.arrays.base import ExtensionArray, _extension_array_shared_docs
@@ -979,7 +979,7 @@ def _validate_scalar(self, value):
if isinstance(value, Interval):
self._check_closed_matches(value, name="value")
left, right = value.left, value.right
- elif is_valid_nat_for_dtype(value, self.left.dtype):
+ elif is_valid_na_for_dtype(value, self.left.dtype):
# GH#18295
left = right = value
else:
@@ -994,7 +994,7 @@ def _validate_fill_value(self, value):
def _validate_setitem_value(self, value):
needs_float_conversion = False
- if is_valid_nat_for_dtype(value, self.left.dtype):
+ if is_valid_na_for_dtype(value, self.left.dtype):
# na value: need special casing to set directly on numpy arrays
if is_integer_dtype(self.dtype.subtype):
# can't set NaN on a numpy integer array
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index ed36beb80986e..67e9aaa99debd 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -87,7 +87,7 @@
ABCSeries,
)
from pandas.core.dtypes.inference import is_list_like
-from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna, notna
+from pandas.core.dtypes.missing import is_valid_na_for_dtype, isna, notna
if TYPE_CHECKING:
from pandas import Series
@@ -159,7 +159,7 @@ def maybe_unbox_datetimelike(value: Scalar, dtype: DtypeObj) -> Scalar:
-----
Caller is responsible for checking dtype.kind in ["m", "M"]
"""
- if is_valid_nat_for_dtype(value, dtype):
+ if is_valid_na_for_dtype(value, dtype):
# GH#36541: can't fill array directly with pd.NaT
# > np.empty(10, dtype="datetime64[64]").fill(pd.NaT)
# ValueError: cannot convert float NaN to integer
@@ -535,7 +535,7 @@ def maybe_promote(dtype, fill_value=np.nan):
dtype = np.dtype(np.object_)
elif is_integer(fill_value) or (is_float(fill_value) and not isna(fill_value)):
dtype = np.dtype(np.object_)
- elif is_valid_nat_for_dtype(fill_value, dtype):
+ elif is_valid_na_for_dtype(fill_value, dtype):
# e.g. pd.NA, which is not accepted by Timestamp constructor
fill_value = np.datetime64("NaT", "ns")
else:
@@ -551,7 +551,7 @@ def maybe_promote(dtype, fill_value=np.nan):
):
# TODO: What about str that can be a timedelta?
dtype = np.dtype(np.object_)
- elif is_valid_nat_for_dtype(fill_value, dtype):
+ elif is_valid_na_for_dtype(fill_value, dtype):
# e.g pd.NA, which is not accepted by the Timedelta constructor
fill_value = np.timedelta64("NaT", "ns")
else:
diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py
index 0db0b1f6a97ef..ef645313de614 100644
--- a/pandas/core/dtypes/missing.py
+++ b/pandas/core/dtypes/missing.py
@@ -29,7 +29,6 @@
is_string_dtype,
is_string_like_dtype,
needs_i8_conversion,
- pandas_dtype,
)
from pandas.core.dtypes.generic import (
ABCDataFrame,
@@ -535,7 +534,7 @@ def maybe_fill(arr, fill_value=np.nan):
return arr
-def na_value_for_dtype(dtype, compat: bool = True):
+def na_value_for_dtype(dtype: DtypeObj, compat: bool = True):
"""
Return a dtype compat na value
@@ -561,7 +560,6 @@ def na_value_for_dtype(dtype, compat: bool = True):
>>> na_value_for_dtype(np.dtype('datetime64[ns]'))
numpy.datetime64('NaT')
"""
- dtype = pandas_dtype(dtype)
if is_extension_array_dtype(dtype):
return dtype.na_value
@@ -590,7 +588,7 @@ def remove_na_arraylike(arr):
return arr[notna(np.asarray(arr))]
-def is_valid_nat_for_dtype(obj, dtype: DtypeObj) -> bool:
+def is_valid_na_for_dtype(obj, dtype: DtypeObj) -> bool:
"""
isna check that excludes incompatible dtypes
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 550c1ac906a99..c493bdea64d6b 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -88,7 +88,7 @@
ABCTimedeltaIndex,
)
from pandas.core.dtypes.inference import is_dict_like
-from pandas.core.dtypes.missing import array_equivalent, is_valid_nat_for_dtype, isna
+from pandas.core.dtypes.missing import array_equivalent, is_valid_na_for_dtype, isna
from pandas.core import missing, ops
from pandas.core.accessor import CachedAccessor
@@ -5216,7 +5216,7 @@ def _find_common_type_compat(self, target) -> DtypeObj:
Implementation of find_common_type that adjusts for Index-specific
special cases.
"""
- if is_interval_dtype(self.dtype) and is_valid_nat_for_dtype(target, self.dtype):
+ if is_interval_dtype(self.dtype) and is_valid_na_for_dtype(target, self.dtype):
# e.g. setting NA value into IntervalArray[int64]
self = cast("IntervalIndex", self)
return IntervalDtype(np.float64, closed=self.closed)
@@ -5770,7 +5770,7 @@ def insert(self, loc: int, item):
# Note: this method is overridden by all ExtensionIndex subclasses,
# so self is never backed by an EA.
item = lib.item_from_zerodim(item)
- if is_valid_nat_for_dtype(item, self.dtype) and self.dtype != object:
+ if is_valid_na_for_dtype(item, self.dtype) and self.dtype != object:
item = self._na_value
try:
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index 32da2c1cd1f3f..265170dd28a3b 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -15,7 +15,7 @@
is_categorical_dtype,
is_scalar,
)
-from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna, notna
+from pandas.core.dtypes.missing import is_valid_na_for_dtype, isna, notna
from pandas.core import accessor
from pandas.core.arrays.categorical import Categorical, contains
@@ -348,7 +348,7 @@ def inferred_type(self) -> str:
@doc(Index.__contains__)
def __contains__(self, key: Any) -> bool:
# if key is a NaN, check if any NaN is in self.
- if is_valid_nat_for_dtype(key, self.categories.dtype):
+ if is_valid_na_for_dtype(key, self.categories.dtype):
return self.hasnans
return contains(self, key, container=self._engine)
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index e306698fe0202..2ef703de85dbe 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -26,7 +26,7 @@
is_datetime64tz_dtype,
is_scalar,
)
-from pandas.core.dtypes.missing import is_valid_nat_for_dtype
+from pandas.core.dtypes.missing import is_valid_na_for_dtype
from pandas.core.arrays.datetimes import DatetimeArray, tz_to_dtype
import pandas.core.common as com
@@ -636,7 +636,7 @@ def get_loc(self, key, method=None, tolerance=None):
raise InvalidIndexError(key)
orig_key = key
- if is_valid_nat_for_dtype(key, self.dtype):
+ if is_valid_na_for_dtype(key, self.dtype):
key = NaT
if isinstance(key, self._data._recognized_scalars):
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 559b27aeb7e50..b8d6deb353cd2 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -60,6 +60,7 @@
is_list_like,
is_object_dtype,
is_scalar,
+ pandas_dtype,
validate_all_hashable,
)
from pandas.core.dtypes.generic import ABCDataFrame
@@ -405,7 +406,7 @@ def _init_dict(self, data, index=None, dtype: Optional[Dtype] = None):
elif index is not None:
# fastpath for Series(data=None). Just use broadcasting a scalar
# instead of reindexing.
- values = na_value_for_dtype(dtype)
+ values = na_value_for_dtype(pandas_dtype(dtype))
keys = index
else:
keys, values = (), []
| https://api.github.com/repos/pandas-dev/pandas/pulls/39711 | 2021-02-09T23:36:14Z | 2021-02-10T09:57:07Z | 2021-02-10T09:57:07Z | 2021-02-10T16:24:03Z | |
CI: pin numpydoc | diff --git a/environment.yml b/environment.yml
index 6376da76bd580..113780ed0264a 100644
--- a/environment.yml
+++ b/environment.yml
@@ -114,4 +114,4 @@ dependencies:
- natsort # DataFrame.sort_values
- pip:
- git+https://github.com/pandas-dev/pydata-sphinx-theme.git@2488b7defbd3d753dd5fcfc890fc4a7e79d25103
- - git+https://github.com/numpy/numpydoc
+ - numpydoc < 1.2 # 2021-02-09 1.2dev breaking CI
diff --git a/requirements-dev.txt b/requirements-dev.txt
index ec9da940ca4ed..be60c90aef8aa 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -77,4 +77,4 @@ pyreadstat
tabulate>=0.8.3
natsort
git+https://github.com/pandas-dev/pydata-sphinx-theme.git@2488b7defbd3d753dd5fcfc890fc4a7e79d25103
-git+https://github.com/numpy/numpydoc
+numpydoc < 1.2
| xref #39688
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/39709 | 2021-02-09T22:12:35Z | 2021-02-10T00:32:07Z | 2021-02-10T00:32:07Z | 2021-02-10T02:30:19Z |
DOCS: Added links to official docs in cheat sheets | - [x] closes #39706
- [x] tests added / passed (not necessary, only edited ppt and pdf)
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them (not necessary, only edited ppt and pdf)
- [x] whatsnew entry (not necesarry)
| https://api.github.com/repos/pandas-dev/pandas/pulls/39707 | 2021-02-09T20:15:35Z | 2021-02-10T23:10:01Z | 2021-02-10T23:10:00Z | 2021-02-10T23:42:38Z | |
DEP: bump min version of openpyxl to 3.0.0 #39603 | diff --git a/ci/deps/azure-37-locale_slow.yaml b/ci/deps/azure-37-locale_slow.yaml
index 7f658fe62d268..0c47b1a72774f 100644
--- a/ci/deps/azure-37-locale_slow.yaml
+++ b/ci/deps/azure-37-locale_slow.yaml
@@ -18,7 +18,7 @@ dependencies:
- lxml
- matplotlib=3.0.0
- numpy=1.16.*
- - openpyxl=2.6.0
+ - openpyxl=3.0.0
- python-dateutil
- python-blosc
- pytz=2017.3
diff --git a/ci/deps/azure-37-minimum_versions.yaml b/ci/deps/azure-37-minimum_versions.yaml
index f184ea87c89fe..9cc158b76cd41 100644
--- a/ci/deps/azure-37-minimum_versions.yaml
+++ b/ci/deps/azure-37-minimum_versions.yaml
@@ -19,7 +19,7 @@ dependencies:
- numba=0.46.0
- numexpr=2.6.8
- numpy=1.16.5
- - openpyxl=2.6.0
+ - openpyxl=3.0.0
- pytables=3.5.1
- python-dateutil=2.7.3
- pytz=2017.3
diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst
index 49039f05b889a..06e1af75053d3 100644
--- a/doc/source/getting_started/install.rst
+++ b/doc/source/getting_started/install.rst
@@ -274,7 +274,7 @@ html5lib 1.0.1 HTML parser for read_html (see :ref
lxml 4.3.0 HTML parser for read_html (see :ref:`note <optional_html>`)
matplotlib 2.2.3 Visualization
numba 0.46.0 Alternative execution engine for rolling operations
-openpyxl 2.6.0 Reading / writing for xlsx files
+openpyxl 3.0.0 Reading / writing for xlsx files
pandas-gbq 0.12.0 Google Big Query access
psycopg2 2.7 PostgreSQL engine for sqlalchemy
pyarrow 0.15.0 Parquet, ORC, and feather reading / writing
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 799bc88ffff4e..7b2c993cde024 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -186,7 +186,7 @@ Optional libraries below the lowest tested version may still work, but are not c
+-----------------+-----------------+---------+
| numba | 0.46.0 | |
+-----------------+-----------------+---------+
-| openpyxl | 2.6.0 | |
+| openpyxl | 3.0.0 | X |
+-----------------+-----------------+---------+
| pyarrow | 0.15.0 | |
+-----------------+-----------------+---------+
diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py
index bcad9f1ddab09..eb2b4caddb7a6 100644
--- a/pandas/compat/_optional.py
+++ b/pandas/compat/_optional.py
@@ -17,7 +17,7 @@
"matplotlib": "2.2.3",
"numexpr": "2.6.8",
"odfpy": "1.3.0",
- "openpyxl": "2.6.0",
+ "openpyxl": "3.0.0",
"pandas_gbq": "0.12.0",
"pyarrow": "0.15.0",
"pytest": "5.0.1",
diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py
index d0fe64a82d187..ef70706920dc4 100644
--- a/pandas/io/excel/_openpyxl.py
+++ b/pandas/io/excel/_openpyxl.py
@@ -1,13 +1,12 @@
from __future__ import annotations
-from distutils.version import LooseVersion
import mmap
from typing import TYPE_CHECKING, Dict, List, Optional
import numpy as np
from pandas._typing import FilePathOrBuffer, Scalar, StorageOptions
-from pandas.compat._optional import get_version, import_optional_dependency
+from pandas.compat._optional import import_optional_dependency
from pandas.io.excel._base import BaseExcelReader, ExcelWriter
from pandas.io.excel._util import validate_freeze_panes
@@ -531,14 +530,8 @@ def _convert_cell(self, cell, convert_float: bool) -> Scalar:
return cell.value
def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]:
- # GH 39001
- # Reading of excel file depends on dimension data being correct but
- # writers sometimes omit or get it wrong
- import openpyxl
- version = LooseVersion(get_version(openpyxl))
-
- if version >= "3.0.0" and self.book.read_only:
+ if self.book.read_only:
sheet.reset_dimensions()
data: List[List[Scalar]] = []
@@ -552,7 +545,7 @@ def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]:
# Trim trailing empty rows
data = data[: last_row_with_data + 1]
- if version >= "3.0.0" and self.book.read_only and len(data) > 0:
+ if self.book.read_only and len(data) > 0:
# With dimension reset, openpyxl no longer pads rows
max_width = max(len(data_row) for data_row in data)
if min(len(data_row) for data_row in data) < max_width:
diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py
index 0962b719efd4d..8128e958141e2 100644
--- a/pandas/tests/io/excel/test_openpyxl.py
+++ b/pandas/tests/io/excel/test_openpyxl.py
@@ -1,11 +1,8 @@
-from distutils.version import LooseVersion
from pathlib import Path
import numpy as np
import pytest
-from pandas.compat._optional import get_version
-
import pandas as pd
from pandas import DataFrame
import pandas._testing as tm
@@ -157,10 +154,6 @@ def test_read_with_bad_dimension(
datapath, ext, header, expected_data, filename, read_only, request
):
# GH 38956, 39001 - no/incorrect dimension information
- version = LooseVersion(get_version(openpyxl))
- if (read_only or read_only is None) and version < "3.0.0":
- msg = "openpyxl read-only sheet is incorrect when dimension data is wrong"
- request.node.add_marker(pytest.mark.xfail(reason=msg))
path = datapath("io", "data", "excel", f"{filename}{ext}")
if read_only is None:
result = pd.read_excel(path, header=header)
@@ -195,10 +188,6 @@ def test_append_mode_file(ext):
@pytest.mark.parametrize("read_only", [True, False, None])
def test_read_with_empty_trailing_rows(datapath, ext, read_only, request):
# GH 39181
- version = LooseVersion(get_version(openpyxl))
- if (read_only or read_only is None) and version < "3.0.0":
- msg = "openpyxl read-only sheet is incorrect when dimension data is wrong"
- request.node.add_marker(pytest.mark.xfail(reason=msg))
path = datapath("io", "data", "excel", f"empty_trailing_rows{ext}")
if read_only is None:
result = pd.read_excel(path)
| - [x] closes #39603
| https://api.github.com/repos/pandas-dev/pandas/pulls/39702 | 2021-02-09T17:23:18Z | 2021-02-15T22:14:02Z | 2021-02-15T22:14:02Z | 2021-03-18T16:36:39Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.