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 |
|---|---|---|---|---|---|---|---|
BUG: Fix to GH34422 SeriesGroupBy works only with 'func' now | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 5ef1f9dea5091..88524b1f458ff 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -907,6 +907,7 @@ Groupby/resample/rolling
to the input DataFrame is inconsistent. An internal heuristic to detect index mutation would behave differently for equal but not identical
indices. In particular, the result index shape might change if a copy of the input would be returned.
The behaviour now is consistent, independent of internal heuristics. (:issue:`31612`, :issue:`14927`, :issue:`13056`)
+- Bug in :meth:`SeriesGroupBy.agg` where any column name was accepted in the named aggregation of ``SeriesGroupBy`` previously. The behaviour now allows only ``str`` and callables else would raise ``TypeError``. (:issue:`34422`)
Reshaping
^^^^^^^^^
diff --git a/pandas/core/aggregation.py b/pandas/core/aggregation.py
index 6130e05b2a4dc..838722f60b380 100644
--- a/pandas/core/aggregation.py
+++ b/pandas/core/aggregation.py
@@ -5,7 +5,7 @@
from collections import defaultdict
from functools import partial
-from typing import Any, DefaultDict, List, Sequence, Tuple
+from typing import Any, Callable, DefaultDict, List, Sequence, Tuple, Union
from pandas.core.dtypes.common import is_dict_like, is_list_like
@@ -196,3 +196,39 @@ def maybe_mangle_lambdas(agg_spec: Any) -> Any:
mangled_aggspec = _managle_lambda_list(agg_spec)
return mangled_aggspec
+
+
+def validate_func_kwargs(
+ kwargs: dict,
+) -> Tuple[List[str], List[Union[str, Callable[..., Any]]]]:
+ """
+ Validates types of user-provided "named aggregation" kwargs.
+ `TypeError` is raised if aggfunc is not `str` or callable.
+
+ Parameters
+ ----------
+ kwargs : dict
+
+ Returns
+ -------
+ columns : List[str]
+ List of user-provied keys.
+ func : List[Union[str, callable[...,Any]]]
+ List of user-provided aggfuncs
+
+ Examples
+ --------
+ >>> validate_func_kwargs({'one': 'min', 'two': 'max'})
+ (['one', 'two'], ['min', 'max'])
+ """
+ no_arg_message = "Must provide 'func' or named aggregation **kwargs."
+ tuple_given_message = "func is expected but recieved {} in **kwargs."
+ columns = list(kwargs)
+ func = []
+ for col_func in kwargs.values():
+ if not (isinstance(col_func, str) or callable(col_func)):
+ raise TypeError(tuple_given_message.format(type(col_func).__name__))
+ func.append(col_func)
+ if not columns:
+ raise TypeError(no_arg_message)
+ return columns, func
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index ea4b6f4e65341..d589b0e0fe83c 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -57,6 +57,7 @@
is_multi_agg_with_relabel,
maybe_mangle_lambdas,
normalize_keyword_aggregation,
+ validate_func_kwargs,
)
import pandas.core.algorithms as algorithms
from pandas.core.base import DataError, SpecificationError
@@ -233,13 +234,9 @@ def aggregate(
relabeling = func is None
columns = None
- no_arg_message = "Must provide 'func' or named aggregation **kwargs."
if relabeling:
- columns = list(kwargs)
- func = [kwargs[col] for col in columns]
+ columns, func = validate_func_kwargs(kwargs)
kwargs = {}
- if not columns:
- raise TypeError(no_arg_message)
if isinstance(func, str):
return getattr(self, func)(*args, **kwargs)
diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py
index d4b061594c364..371ec11cdba77 100644
--- a/pandas/tests/groupby/aggregate/test_aggregate.py
+++ b/pandas/tests/groupby/aggregate/test_aggregate.py
@@ -511,6 +511,21 @@ def test_mangled(self):
expected = pd.DataFrame({"a": [0, 0], "b": [1, 1]})
tm.assert_frame_equal(result, expected)
+ @pytest.mark.parametrize(
+ "inp",
+ [
+ pd.NamedAgg(column="anything", aggfunc="min"),
+ ("anything", "min"),
+ ["anything", "min"],
+ ],
+ )
+ def test_named_agg_nametuple(self, inp):
+ # GH34422
+ s = pd.Series([1, 1, 2, 2, 3, 3, 4, 5])
+ msg = f"func is expected but recieved {type(inp).__name__}"
+ with pytest.raises(TypeError, match=msg):
+ s.groupby(s.values).agg(a=inp)
+
class TestNamedAggregationDataFrame:
def test_agg_relabel(self):
| - [X] closes #34422
- [x] tests added / passed
- [x] passes `black pandas`
- [x] whatsnew entry
This PR tries to fix the bug pointed in #34422 where `SeriesGroupBy.agg` works with any given column name in `NamedAgg`.
After discussing with @TomAugspurger and @MarcoGorelli in another issue #34380 regarding this issue in the comments, We came to a solution that
> So for SeriesGroupBy.agg, if there are any tuples or NamedAgg present in kwargs then I think we should raise.
> Disallowing `NamedAgg` and tuples with `SeriesGroupBy`.
#### Before fix:
```python3
s = pd.Series([1,1,2,2,3,3,4,5])
s.groupby(s.values).agg(one = pd.NamedAgg(column='anything',aggfunc='sum'))
one
1 2
2 4
3 6
4 4
5 5
s.groupby(s.values).agg(one=('something','sum'))
one
1 2
2 4
3 6
4 4
5 5
```
#### After fix:
```python3
s = pd.Series([1,1,2,2,3,3,4,5])
s.groupby(s.values).agg(one = pd.NamedAgg(column='anything',aggfunc='sum'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "d:\#gh34422\pandas\pandas\core\groupby\generic.py", line 243, in aggregate
raise TypeError(tuple_given_message.format(type(kwargs[col]).__name__))
TypeError: 'func' is expected but recieved NamedAgg in **kwargs.
s.groupby(s.values).agg(one=('something','sum'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "d:\#gh34422\pandas\pandas\core\groupby\generic.py", line 243, in aggregate
raise TypeError(tuple_given_message.format(type(kwargs[col]).__name__))
TypeError: 'func' is expected but recieved tuple in **kwargs.
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/34435 | 2020-05-28T18:42:25Z | 2020-06-03T22:26:16Z | 2020-06-03T22:26:15Z | 2020-06-05T17:30:50Z |
TST: additional regression cases for slicing blockwise op (GH34421) | diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py
index 993b644c6993b..e7b7f3e524d44 100644
--- a/pandas/tests/frame/test_arithmetic.py
+++ b/pandas/tests/frame/test_arithmetic.py
@@ -1523,7 +1523,16 @@ def test_dataframe_blockwise_slicelike():
df2 = df1.copy()
df2.iloc[0, [1, 3, 7]] = np.nan
- res = df1 + df2
+ df3 = df1.copy()
+ df3.iloc[0, [5]] = np.nan
- expected = pd.DataFrame({i: df1[i] + df2[i] for i in df1.columns})
- tm.assert_frame_equal(res, expected)
+ df4 = df1.copy()
+ df4.iloc[0, np.arange(2, 5)] = np.nan
+ df5 = df1.copy()
+ df5.iloc[0, np.arange(4, 7)] = np.nan
+
+ for left, right in [(df1, df2), (df2, df3), (df4, df5)]:
+ res = left + right
+
+ expected = pd.DataFrame({i: left[i] + right[i] for i in left.columns})
+ tm.assert_frame_equal(res, expected)
| Adding the other case from https://github.com/pandas-dev/pandas/issues/34367 to the test as well (although also fixed by the PR, it was failing with a different error originally, so might be worth it to add as test case as well).
cc @jbrockmendel | https://api.github.com/repos/pandas-dev/pandas/pulls/34434 | 2020-05-28T18:17:28Z | 2020-05-28T22:20:24Z | 2020-05-28T22:20:24Z | 2020-05-29T06:38:58Z |
DOC: reduce API docs for offset aliases | diff --git a/doc/source/reference/offset_frequency.rst b/doc/source/reference/offset_frequency.rst
index ee89df3114048..1b63253cde2c5 100644
--- a/doc/source/reference/offset_frequency.rst
+++ b/doc/source/reference/offset_frequency.rst
@@ -42,11 +42,20 @@ Methods
BusinessDay
-----------
+
.. autosummary::
:toctree: api/
BusinessDay
+Alias:
+
+.. autosummary::
+ :toctree: api/
+ :template: autosummary/class_without_autosummary.rst
+
+ BDay
+
Properties
~~~~~~~~~~
.. autosummary::
@@ -117,11 +126,20 @@ Methods
CustomBusinessDay
-----------------
+
.. autosummary::
:toctree: api/
CustomBusinessDay
+Alias:
+
+.. autosummary::
+ :toctree: api/
+ :template: autosummary/class_without_autosummary.rst
+
+ CDay
+
Properties
~~~~~~~~~~
.. autosummary::
@@ -260,11 +278,20 @@ Methods
BusinessMonthEnd
----------------
+
.. autosummary::
:toctree: api/
BusinessMonthEnd
+Alias:
+
+.. autosummary::
+ :toctree: api/
+ :template: autosummary/class_without_autosummary.rst
+
+ BMonthEnd
+
Properties
~~~~~~~~~~
.. autosummary::
@@ -294,11 +321,20 @@ Methods
BusinessMonthBegin
------------------
+
.. autosummary::
:toctree: api/
BusinessMonthBegin
+Alias:
+
+.. autosummary::
+ :toctree: api/
+ :template: autosummary/class_without_autosummary.rst
+
+ BMonthBegin
+
Properties
~~~~~~~~~~
.. autosummary::
@@ -328,11 +364,20 @@ Methods
CustomBusinessMonthEnd
----------------------
+
.. autosummary::
:toctree: api/
CustomBusinessMonthEnd
+Alias:
+
+.. autosummary::
+ :toctree: api/
+ :template: autosummary/class_without_autosummary.rst
+
+ CBMonthEnd
+
Properties
~~~~~~~~~~
.. autosummary::
@@ -365,11 +410,20 @@ Methods
CustomBusinessMonthBegin
------------------------
+
.. autosummary::
:toctree: api/
CustomBusinessMonthBegin
+Alias:
+
+.. autosummary::
+ :toctree: api/
+ :template: autosummary/class_without_autosummary.rst
+
+ CBMonthBegin
+
Properties
~~~~~~~~~~
.. autosummary::
@@ -1238,251 +1292,6 @@ Methods
Nano.__call__
Nano.apply
-BDay
-----
-.. autosummary::
- :toctree: api/
-
- BDay
-
-Properties
-~~~~~~~~~~
-.. autosummary::
- :toctree: api/
-
- BDay.base
- BDay.freqstr
- BDay.kwds
- BDay.name
- BDay.nanos
- BDay.normalize
- BDay.offset
- BDay.rule_code
- BDay.n
- BDay.weekmask
- BDay.holidays
- BDay.calendar
-
-Methods
-~~~~~~~
-.. autosummary::
- :toctree: api/
-
- BDay.apply
- BDay.apply_index
- BDay.copy
- BDay.isAnchored
- BDay.onOffset
- BDay.is_anchored
- BDay.is_on_offset
- BDay.rollback
- BDay.rollforward
- BDay.__call__
-
-BMonthEnd
----------
-.. autosummary::
- :toctree: api/
-
- BMonthEnd
-
-Properties
-~~~~~~~~~~
-.. autosummary::
- :toctree: api/
-
- BMonthEnd.base
- BMonthEnd.freqstr
- BMonthEnd.kwds
- BMonthEnd.name
- BMonthEnd.nanos
- BMonthEnd.normalize
- BMonthEnd.rule_code
- BMonthEnd.n
-
-Methods
-~~~~~~~
-.. autosummary::
- :toctree: api/
-
- BMonthEnd.apply
- BMonthEnd.apply_index
- BMonthEnd.copy
- BMonthEnd.isAnchored
- BMonthEnd.onOffset
- BMonthEnd.is_anchored
- BMonthEnd.is_on_offset
- BMonthEnd.rollback
- BMonthEnd.rollforward
- BMonthEnd.__call__
-
-BMonthBegin
------------
-.. autosummary::
- :toctree: api/
-
- BMonthBegin
-
-Properties
-~~~~~~~~~~
-.. autosummary::
- :toctree: api/
-
- BMonthBegin.base
- BMonthBegin.freqstr
- BMonthBegin.kwds
- BMonthBegin.name
- BMonthBegin.nanos
- BMonthBegin.normalize
- BMonthBegin.rule_code
- BMonthBegin.n
-
-Methods
-~~~~~~~
-.. autosummary::
- :toctree: api/
-
- BMonthBegin.apply
- BMonthBegin.apply_index
- BMonthBegin.copy
- BMonthBegin.isAnchored
- BMonthBegin.onOffset
- BMonthBegin.is_anchored
- BMonthBegin.is_on_offset
- BMonthBegin.rollback
- BMonthBegin.rollforward
- BMonthBegin.__call__
-
-CBMonthEnd
-----------
-.. autosummary::
- :toctree: api/
-
- CBMonthEnd
-
-Properties
-~~~~~~~~~~
-.. autosummary::
- :toctree: api/
-
- CBMonthEnd.base
- CBMonthEnd.cbday_roll
- CBMonthEnd.freqstr
- CBMonthEnd.kwds
- CBMonthEnd.m_offset
- CBMonthEnd.month_roll
- CBMonthEnd.name
- CBMonthEnd.nanos
- CBMonthEnd.normalize
- CBMonthEnd.offset
- CBMonthEnd.rule_code
- CBMonthEnd.n
- CBMonthEnd.weekmask
- CBMonthEnd.holidays
- CBMonthEnd.calendar
-
-Methods
-~~~~~~~
-.. autosummary::
- :toctree: api/
-
- CBMonthEnd.apply
- CBMonthEnd.apply_index
- CBMonthEnd.copy
- CBMonthEnd.isAnchored
- CBMonthEnd.onOffset
- CBMonthEnd.is_anchored
- CBMonthEnd.is_on_offset
- CBMonthEnd.rollback
- CBMonthEnd.rollforward
- CBMonthEnd.__call__
-
-CBMonthBegin
-------------
-.. autosummary::
- :toctree: api/
-
- CBMonthBegin
-
-Properties
-~~~~~~~~~~
-.. autosummary::
- :toctree: api/
-
- CBMonthBegin.base
- CBMonthBegin.cbday_roll
- CBMonthBegin.freqstr
- CBMonthBegin.kwds
- CBMonthBegin.m_offset
- CBMonthBegin.month_roll
- CBMonthBegin.name
- CBMonthBegin.nanos
- CBMonthBegin.normalize
- CBMonthBegin.offset
- CBMonthBegin.rule_code
- CBMonthBegin.n
- CBMonthBegin.weekmask
- CBMonthBegin.holidays
- CBMonthBegin.calendar
-
-Methods
-~~~~~~~
-.. autosummary::
- :toctree: api/
-
- CBMonthBegin.apply
- CBMonthBegin.apply_index
- CBMonthBegin.copy
- CBMonthBegin.isAnchored
- CBMonthBegin.onOffset
- CBMonthBegin.is_anchored
- CBMonthBegin.is_on_offset
- CBMonthBegin.rollback
- CBMonthBegin.rollforward
- CBMonthBegin.__call__
-
-CDay
-----
-.. autosummary::
- :toctree: api/
-
- CDay
-
-Properties
-~~~~~~~~~~
-.. autosummary::
- :toctree: api/
-
- CDay.base
- CDay.freqstr
- CDay.kwds
- CDay.name
- CDay.nanos
- CDay.normalize
- CDay.offset
- CDay.rule_code
- CDay.n
- CDay.weekmask
- CDay.calendar
- CDay.holidays
-
-Methods
-~~~~~~~
-.. autosummary::
- :toctree: api/
-
- CDay.apply
- CDay.apply_index
- CDay.copy
- CDay.isAnchored
- CDay.onOffset
- CDay.is_anchored
- CDay.is_on_offset
- CDay.rollback
- CDay.rollforward
- CDay.__call__
-
-
.. _api.frequencies:
===========
| Test to see if this works with sphinx | https://api.github.com/repos/pandas-dev/pandas/pulls/34433 | 2020-05-28T17:38:54Z | 2020-06-19T11:01:22Z | 2020-06-19T11:01:22Z | 2020-06-19T11:01:29Z |
CLN: assorted tslibs cleanups | diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx
index 660cd3af1b35e..baf8889b415fb 100644
--- a/pandas/_libs/tslibs/offsets.pyx
+++ b/pandas/_libs/tslibs/offsets.pyx
@@ -1325,7 +1325,7 @@ cdef class BusinessDay(BusinessMixin):
off_str += str(td.microseconds) + "us"
return off_str
- if isinstance(self.offset, timedelta):
+ if PyDelta_Check(self.offset):
zero = timedelta(0, 0, 0)
if self.offset >= zero:
off_str = "+" + get_str(self.offset)
@@ -1337,7 +1337,7 @@ cdef class BusinessDay(BusinessMixin):
@apply_wraps
def apply(self, other):
- if isinstance(other, datetime):
+ if PyDateTime_Check(other):
n = self.n
wday = other.weekday()
@@ -1368,7 +1368,7 @@ cdef class BusinessDay(BusinessMixin):
result = result + self.offset
return result
- elif isinstance(other, (timedelta, Tick)):
+ elif PyDelta_Check(other) or isinstance(other, Tick):
return BusinessDay(
self.n, offset=self.offset + other, normalize=self.normalize
)
@@ -1649,7 +1649,7 @@ cdef class BusinessHour(BusinessMixin):
@apply_wraps
def apply(self, other):
- if isinstance(other, datetime):
+ if PyDateTime_Check(other):
# used for detecting edge condition
nanosecond = getattr(other, "nanosecond", 0)
# reset timezone and nanosecond
@@ -2511,7 +2511,7 @@ cdef class Week(SingleConstructorOffset):
if self.weekday is None:
return other + self.n * self._inc
- if not isinstance(other, datetime):
+ if not PyDateTime_Check(other):
raise TypeError(
f"Cannot add {type(other).__name__} to {type(self).__name__}"
)
@@ -3305,7 +3305,7 @@ class CustomBusinessDay(CustomMixin, BusinessDay):
else:
roll = "backward"
- if isinstance(other, datetime):
+ if PyDateTime_Check(other):
date_in = other
np_dt = np.datetime64(date_in.date())
@@ -3320,7 +3320,7 @@ class CustomBusinessDay(CustomMixin, BusinessDay):
result = result + self.offset
return result
- elif isinstance(other, (timedelta, Tick)):
+ elif PyDelta_Check(other) or isinstance(other, Tick):
return BDay(self.n, offset=self.offset + other, normalize=self.normalize)
else:
raise ApplyTypeError(
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx
index ec6f8de159dae..9757c4d36d5fa 100644
--- a/pandas/_libs/tslibs/period.pyx
+++ b/pandas/_libs/tslibs/period.pyx
@@ -40,7 +40,10 @@ cimport pandas._libs.tslibs.util as util
from pandas._libs.tslibs.timestamps import Timestamp
from pandas._libs.tslibs.timezones cimport is_utc, is_tzlocal, get_dst_info
from pandas._libs.tslibs.timedeltas import Timedelta
-from pandas._libs.tslibs.timedeltas cimport delta_to_nanoseconds
+from pandas._libs.tslibs.timedeltas cimport (
+ delta_to_nanoseconds,
+ is_any_td_scalar,
+)
from pandas._libs.tslibs.ccalendar cimport (
dayofweek,
@@ -1591,7 +1594,7 @@ cdef class _Period:
return NaT
return other.__add__(self)
- if is_any_tdlike_scalar(other):
+ if is_any_td_scalar(other):
return self._add_delta(other)
elif is_offset_object(other):
return self._add_offset(other)
@@ -1618,7 +1621,7 @@ cdef class _Period:
return NaT
return NotImplemented
- elif is_any_tdlike_scalar(other):
+ elif is_any_td_scalar(other):
neg_other = -other
return self + neg_other
elif is_offset_object(other):
@@ -2494,18 +2497,3 @@ def validate_end_alias(how):
if how not in {'S', 'E'}:
raise ValueError('How must be one of S or E')
return how
-
-
-cpdef is_any_tdlike_scalar(object obj):
- """
- Cython equivalent for `isinstance(obj, (timedelta, np.timedelta64, Tick))`
-
- Parameters
- ----------
- obj : object
-
- Returns
- -------
- bool
- """
- return util.is_timedelta64_object(obj) or PyDelta_Check(obj) or is_tick_object(obj)
diff --git a/pandas/_libs/tslibs/timedeltas.pxd b/pandas/_libs/tslibs/timedeltas.pxd
index 8f9c1b190b021..95ddf8840e65d 100644
--- a/pandas/_libs/tslibs/timedeltas.pxd
+++ b/pandas/_libs/tslibs/timedeltas.pxd
@@ -3,3 +3,4 @@ from numpy cimport int64_t
# Exposed for tslib, not intended for outside use.
cpdef int64_t delta_to_nanoseconds(delta) except? -1
cdef convert_to_timedelta64(object ts, object unit)
+cdef bint is_any_td_scalar(object obj)
diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx
index 5bc3694cf8dad..f7f8b86359732 100644
--- a/pandas/_libs/tslibs/timedeltas.pyx
+++ b/pandas/_libs/tslibs/timedeltas.pyx
@@ -446,7 +446,8 @@ cdef inline timedelta_from_spec(object number, object frac, object unit):
frac : a list of frac digits
unit : a list of unit characters
"""
- cdef object n
+ cdef:
+ str n
try:
unit = ''.join(unit)
@@ -1376,6 +1377,17 @@ class Timedelta(_Timedelta):
cdef bint is_any_td_scalar(object obj):
+ """
+ Cython equivalent for `isinstance(obj, (timedelta, np.timedelta64, Tick))`
+
+ Parameters
+ ----------
+ obj : object
+
+ Returns
+ -------
+ bool
+ """
return (
PyDelta_Check(obj) or is_timedelta64_object(obj) or is_tick_object(obj)
)
diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx
index 9fd62e5e25c54..48c4afe7d4c1b 100644
--- a/pandas/_libs/tslibs/timestamps.pyx
+++ b/pandas/_libs/tslibs/timestamps.pyx
@@ -808,7 +808,7 @@ class Timestamp(_Timestamp):
# check that only ts_input is passed
# checking verbosely, because cython doesn't optimize
# list comprehensions (as of cython 0.29.x)
- if (isinstance(ts_input, Timestamp) and freq is None and
+ if (isinstance(ts_input, _Timestamp) and freq is None and
tz is None and unit is None and year is None and
month is None and day is None and hour is None and
minute is None and second is None and
| https://api.github.com/repos/pandas-dev/pandas/pulls/34432 | 2020-05-28T15:41:33Z | 2020-05-28T20:56:28Z | 2020-05-28T20:56:28Z | 2020-05-28T21:28:52Z | |
DOC: cleanup whatsnew post 1.0.4 release | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 5ef1f9dea5091..4f37cf9931075 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -706,9 +706,6 @@ Categorical
- Bug when passing categorical data to :class:`Index` constructor along with ``dtype=object`` incorrectly returning a :class:`CategoricalIndex` instead of object-dtype :class:`Index` (:issue:`32167`)
- Bug where :class:`Categorical` comparison operator ``__ne__`` would incorrectly evaluate to ``False`` when either element was missing (:issue:`32276`)
- :meth:`Categorical.fillna` now accepts :class:`Categorical` ``other`` argument (:issue:`32420`)
-- Bug where :meth:`Categorical.replace` would replace with ``NaN`` whenever the new value and replacement value were equal (:issue:`33288`)
-- Bug where an ordered :class:`Categorical` containing only ``NaN`` values would raise rather than returning ``NaN`` when taking the minimum or maximum (:issue:`33450`)
-- Bug where :meth:`Series.isna` and :meth:`DataFrame.isna` would raise for categorical dtype when ``pandas.options.mode.use_inf_as_na`` was set to ``True`` (:issue:`33594`)
Datetimelike
^^^^^^^^^^^^
@@ -759,7 +756,6 @@ Numeric
- Bug in :meth:`DataFrame.mean` with ``numeric_only=False`` and either ``datetime64`` dtype or ``PeriodDtype`` column incorrectly raising ``TypeError`` (:issue:`32426`)
- Bug in :meth:`DataFrame.count` with ``level="foo"`` and index level ``"foo"`` containing NaNs causes segmentation fault (:issue:`21824`)
- Bug in :meth:`DataFrame.diff` with ``axis=1`` returning incorrect results with mixed dtypes (:issue:`32995`)
-- Bug in DataFrame reductions using ``numeric_only=True`` and ExtensionArrays (:issue:`33256`).
- Bug in :meth:`DataFrame.corr` and :meth:`DataFrame.cov` raising when handling nullable integer columns with ``pandas.NA`` (:issue:`33803`)
- Bug in :class:`DataFrame` and :class:`Series` addition and subtraction between object-dtype objects and ``datetime64`` dtype objects (:issue:`33824`)
@@ -796,7 +792,6 @@ Indexing
- Bug in :meth:`DataFrame.iloc.__setitem__` on a :class:`DataFrame` with duplicate columns incorrectly setting values for all matching columns (:issue:`15686`, :issue:`22036`)
- Bug in :meth:`DataFrame.loc:` and :meth:`Series.loc` with a :class:`DatetimeIndex`, :class:`TimedeltaIndex`, or :class:`PeriodIndex` incorrectly allowing lookups of non-matching datetime-like dtypes (:issue:`32650`)
- Bug in :meth:`Series.__getitem__` indexing with non-standard scalars, e.g. ``np.dtype`` (:issue:`32684`)
-- Fix to preserve the ability to index with the "nearest" method with xarray's CFTimeIndex, an :class:`Index` subclass (`pydata/xarray#3751 <https://github.com/pydata/xarray/issues/3751>`_, :issue:`32905`).
- Bug in :class:`Index` constructor where an unhelpful error message was raised for ``numpy`` scalars (:issue:`33017`)
- Bug in :meth:`DataFrame.lookup` incorrectly raising an ``AttributeError`` when ``frame.index`` or ``frame.columns`` is not unique; this will now raise a ``ValueError`` with a helpful error message (:issue:`33041`)
- Bug in :meth:`DataFrame.iloc.__setitem__` creating a new array instead of overwriting ``Categorical`` values in-place (:issue:`32831`)
@@ -866,11 +861,7 @@ I/O
- Bug in :func:`pandas.io.json.json_normalize` where location specified by `record_path` doesn't point to an array. (:issue:`26284`)
- :func:`pandas.read_hdf` has a more explicit error message when loading an
unsupported HDF file (:issue:`9539`)
-- Bug in :meth:`~DataFrame.to_parquet` was not raising ``PermissionError`` when writing to a private s3 bucket with invalid creds. (:issue:`27679`)
-- Bug in :meth:`~DataFrame.to_csv` was silently failing when writing to an invalid s3 bucket. (:issue:`32486`)
- Bug in :meth:`~DataFrame.read_feather` was raising an `ArrowIOError` when reading an s3 or http file path (:issue:`29055`)
-- Bug in :meth:`read_parquet` was raising a ``FileNotFoundError`` when passed an s3 directory path. (:issue:`26388`)
-- Bug in :meth:`~DataFrame.to_parquet` was throwing an ``AttributeError`` when writing a partitioned parquet file to s3 (:issue:`27596`)
- Bug in :meth:`~DataFrame.to_excel` could not handle the column name `render` and was raising an ``KeyError`` (:issue:`34331`)
- Bug in :meth:`~SQLDatabase.execute` was raising a ``ProgrammingError`` for some DB-API drivers when the SQL statement contained the `%` character and no parameters were present (:issue:`34211`)
@@ -893,16 +884,9 @@ Groupby/resample/rolling
- Bug in :meth:`DataFrame.groupby` and :meth:`Series.groupby` produces inconsistent type when aggregating Boolean series (:issue:`32894`)
- Bug in :meth:`DataFrameGroupBy.sum` and :meth:`SeriesGroupBy.sum` where a large negative number would be returned when the number of non-null values was below ``min_count`` for nullable integer dtypes (:issue:`32861`)
- Bug in :meth:`SeriesGroupBy.quantile` raising on nullable integers (:issue:`33136`)
-- Bug in :meth:`SeriesGroupBy.first`, :meth:`SeriesGroupBy.last`, :meth:`SeriesGroupBy.min`, and :meth:`SeriesGroupBy.max` returning floats when applied to nullable Booleans (:issue:`33071`)
-- Bug in :meth:`DataFrameGroupBy.agg` with dictionary input losing ``ExtensionArray`` dtypes (:issue:`32194`)
- Bug in :meth:`DataFrame.resample` where an ``AmbiguousTimeError`` would be raised when the resulting timezone aware :class:`DatetimeIndex` had a DST transition at midnight (:issue:`25758`)
- Bug in :meth:`DataFrame.groupby` where a ``ValueError`` would be raised when grouping by a categorical column with read-only categories and ``sort=False`` (:issue:`33410`)
-- Bug in :meth:`GroupBy.first` and :meth:`GroupBy.last` where None is not preserved in object dtype (:issue:`32800`)
-- Bug in :meth:`GroupBy.quantile` causes the quantiles to be shifted when the ``by`` axis contains ``NaN`` (:issue:`33200`, :issue:`33569`)
-- Bug in :meth:`Rolling.min` and :meth:`Rolling.max`: Growing memory usage after multiple calls when using a fixed window (:issue:`30726`)
-- Bug in :meth:`Series.groupby` would raise ``ValueError`` when grouping by :class:`PeriodIndex` level (:issue:`34010`)
- Bug in :meth:`GroupBy.agg`, :meth:`GroupBy.transform`, and :meth:`GroupBy.resample` where subclasses are not preserved (:issue:`28330`)
-- Bug in :meth:`GroupBy.rolling.apply` ignores args and kwargs parameters (:issue:`33433`)
- Bug in :meth:`core.groupby.DataFrameGroupBy.apply` where the output index shape for functions returning a DataFrame which is equally indexed
to the input DataFrame is inconsistent. An internal heuristic to detect index mutation would behave differently for equal but not identical
indices. In particular, the result index shape might change if a copy of the input would be returned.
@@ -934,7 +918,6 @@ Reshaping
returning subclassed types. (:issue:`31331`)
- Bug in :func:`concat` was not allowing for concatenation of ``DataFrame`` and ``Series`` with duplicate keys (:issue:`33654`)
- Bug in :func:`cut` raised an error when non-unique labels (:issue:`33141`)
-- Bug in :meth:`DataFrame.replace` casts columns to ``object`` dtype if items in ``to_replace`` not in values (:issue:`32988`)
- Ensure only named functions can be used in :func:`eval()` (:issue:`32460`)
- Fixed bug in :func:`melt` where melting MultiIndex columns with ``col_level`` > 0 would raise a ``KeyError`` on ``id_vars`` (:issue:`34129`)
@@ -973,7 +956,6 @@ Other
- Bug in :meth:`DataFrame.__dir__` caused a segfault when using unicode surrogates in a column name (:issue:`25509`)
- Bug in :meth:`DataFrame.plot.scatter` caused an error when plotting variable marker sizes (:issue:`32904`)
- :class:`IntegerArray` now implements the ``sum`` operation (:issue:`33172`)
-- More informative error message with ``np.min`` or ``np.max`` on unordered :class:`Categorical` (:issue:`33115`)
- Bug in :class:`Tick` comparisons raising ``TypeError`` when comparing against timedelta-like objects (:issue:`34088`)
.. ---------------------------------------------------------------------------
| https://api.github.com/repos/pandas-dev/pandas/pulls/34430 | 2020-05-28T12:21:33Z | 2020-05-28T18:13:52Z | 2020-05-28T18:13:51Z | 2020-06-01T15:47:51Z | |
Fix read_sql empty result with chunksize bug GH34411 | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 196d2f2d968a7..0cb46a5164674 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -281,6 +281,7 @@ I/O
- :func:`read_excel` now respects :func:`set_option` (:issue:`34252`)
- Bug in :func:`read_csv` not switching ``true_values`` and ``false_values`` for nullable ``boolean`` dtype (:issue:`34655`)
- 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`)
Period
^^^^^^
diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index bbc5e6ad82493..e1af3169420fc 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -926,11 +926,17 @@ def _query_iterator(
parse_dates=None,
):
"""Return generator through chunked result set."""
+ has_read_data = False
while True:
data = result.fetchmany(chunksize)
if not data:
+ if not has_read_data:
+ yield DataFrame.from_records(
+ [], columns=columns, coerce_float=coerce_float
+ )
break
else:
+ has_read_data = True
self.frame = DataFrame.from_records(
data, columns=columns, coerce_float=coerce_float
)
@@ -1343,11 +1349,21 @@ def _query_iterator(
dtype: Optional[DtypeArg] = None,
):
"""Return generator through chunked result set"""
+ has_read_data = False
while True:
data = result.fetchmany(chunksize)
if not data:
+ if not has_read_data:
+ yield _wrap_result(
+ [],
+ columns,
+ index_col=index_col,
+ coerce_float=coerce_float,
+ parse_dates=parse_dates,
+ )
break
else:
+ has_read_data = True
yield _wrap_result(
data,
columns,
@@ -1849,14 +1865,20 @@ def _query_iterator(
dtype: Optional[DtypeArg] = None,
):
"""Return generator through chunked result set"""
+ has_read_data = False
while True:
data = cursor.fetchmany(chunksize)
if type(data) == tuple:
data = list(data)
if not data:
cursor.close()
+ if not has_read_data:
+ yield DataFrame.from_records(
+ [], columns=columns, coerce_float=coerce_float
+ )
break
else:
+ has_read_data = True
yield _wrap_result(
data,
columns,
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index 6fb120faa6db2..b70bc3c598702 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -661,6 +661,12 @@ def test_read_sql_view(self):
iris_frame = sql.read_sql_query("SELECT * FROM iris_view", self.conn)
self._check_iris_loaded_frame(iris_frame)
+ def test_read_sql_with_chunksize_no_result(self):
+ query = "SELECT * FROM iris_view WHERE SepalLength < 0.0"
+ with_batch = sql.read_sql_query(query, self.conn, chunksize=5)
+ without_batch = sql.read_sql_query(query, self.conn)
+ tm.assert_frame_equal(pd.concat(with_batch), without_batch)
+
def test_to_sql(self):
sql.to_sql(self.test_frame1, "test_frame1", self.conn)
assert sql.has_table("test_frame1", self.conn)
| - [x ] closes #34411
- [ x] tests added / passed
- [ x] passes `black pandas`
- [ x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ x] whatsnew entry
`pd.read_sql` was returning an empty generator when chunksize is set and the query returns zero results. Now it correctly returns a generator with a single empty DataFrame (:issue:`34411`). | https://api.github.com/repos/pandas-dev/pandas/pulls/34429 | 2020-05-28T11:52:29Z | 2021-01-14T18:52:47Z | 2021-01-14T18:52:47Z | 2021-01-14T18:52:51Z |
DOC: 1.0.4 whatsnew | diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst
index b5ac96752536e..b381dae3579c8 100644
--- a/doc/source/whatsnew/index.rst
+++ b/doc/source/whatsnew/index.rst
@@ -24,6 +24,7 @@ Version 1.0
.. toctree::
:maxdepth: 2
+ v1.0.4
v1.0.3
v1.0.2
v1.0.1
diff --git a/doc/source/whatsnew/v1.0.3.rst b/doc/source/whatsnew/v1.0.3.rst
index 26d06433bda0c..62e6ae5b1c5cc 100644
--- a/doc/source/whatsnew/v1.0.3.rst
+++ b/doc/source/whatsnew/v1.0.3.rst
@@ -26,4 +26,4 @@ Bug fixes
Contributors
~~~~~~~~~~~~
-.. contributors:: v1.0.2..v1.0.3|HEAD
+.. contributors:: v1.0.2..v1.0.3
diff --git a/doc/source/whatsnew/v1.0.4.rst b/doc/source/whatsnew/v1.0.4.rst
new file mode 100644
index 0000000000000..5cc1edc9ca9cd
--- /dev/null
+++ b/doc/source/whatsnew/v1.0.4.rst
@@ -0,0 +1,48 @@
+
+.. _whatsnew_104:
+
+What's new in 1.0.4 (May 28, 2020)
+------------------------------------
+
+These are the changes in pandas 1.0.4. See :ref:`release` for a full changelog
+including other versions of pandas.
+
+{{ header }}
+
+.. ---------------------------------------------------------------------------
+
+.. _whatsnew_104.regressions:
+
+Fixed regressions
+~~~~~~~~~~~~~~~~~
+- Fix regression where :meth:`Series.isna` and :meth:`DataFrame.isna` would raise for categorical dtype when ``pandas.options.mode.use_inf_as_na`` was set to ``True`` (:issue:`33594`)
+- Fix regression in :meth:`GroupBy.first` and :meth:`GroupBy.last` where None is not preserved in object dtype (:issue:`32800`)
+- Fix regression in DataFrame reductions using ``numeric_only=True`` and ExtensionArrays (:issue:`33256`).
+- Fix performance regression in ``memory_usage(deep=True)`` for object dtype (:issue:`33012`)
+- Fix regression where :meth:`Categorical.replace` would replace with ``NaN`` whenever the new value and replacement value were equal (:issue:`33288`)
+- Fix regression where an ordered :class:`Categorical` containing only ``NaN`` values would raise rather than returning ``NaN`` when taking the minimum or maximum (:issue:`33450`)
+- Fix regression in :meth:`DataFrameGroupBy.agg` with dictionary input losing ``ExtensionArray`` dtypes (:issue:`32194`)
+- Fix to preserve the ability to index with the "nearest" method with xarray's CFTimeIndex, an :class:`Index` subclass (`pydata/xarray#3751 <https://github.com/pydata/xarray/issues/3751>`_, :issue:`32905`).
+- Fix regression in :meth:`DataFrame.describe` raising ``TypeError: unhashable type: 'dict'`` (:issue:`32409`)
+- Fix regression in :meth:`DataFrame.replace` casts columns to ``object`` dtype if items in ``to_replace`` not in values (:issue:`32988`)
+- Fix regression in :meth:`Series.groupby` would raise ``ValueError`` when grouping by :class:`PeriodIndex` level (:issue:`34010`)
+- Fix regression in :meth:`GroupBy.rolling.apply` ignores args and kwargs parameters (:issue:`33433`)
+- Fix regression in error message with ``np.min`` or ``np.max`` on unordered :class:`Categorical` (:issue:`33115`)
+- Fix regression in :meth:`DataFrame.loc` and :meth:`Series.loc` throwing an error when a ``datetime64[ns, tz]`` value is provided (:issue:`32395`)
+
+.. _whatsnew_104.bug_fixes:
+
+Bug fixes
+~~~~~~~~~
+- Bug in :meth:`SeriesGroupBy.first`, :meth:`SeriesGroupBy.last`, :meth:`SeriesGroupBy.min`, and :meth:`SeriesGroupBy.max` returning floats when applied to nullable Booleans (:issue:`33071`)
+- Bug in :meth:`Rolling.min` and :meth:`Rolling.max`: Growing memory usage after multiple calls when using a fixed window (:issue:`30726`)
+- Bug in :meth:`~DataFrame.to_parquet` was not raising ``PermissionError`` when writing to a private s3 bucket with invalid creds. (:issue:`27679`)
+- Bug in :meth:`~DataFrame.to_csv` was silently failing when writing to an invalid s3 bucket. (:issue:`32486`)
+- Bug in :meth:`read_parquet` was raising a ``FileNotFoundError`` when passed an s3 directory path. (:issue:`26388`)
+- Bug in :meth:`~DataFrame.to_parquet` was throwing an ``AttributeError`` when writing a partitioned parquet file to s3 (:issue:`27596`)
+- Bug in :meth:`GroupBy.quantile` causes the quantiles to be shifted when the ``by`` axis contains ``NaN`` (:issue:`33200`, :issue:`33569`)
+
+Contributors
+~~~~~~~~~~~~
+
+.. contributors:: v1.0.3..v1.0.4|HEAD
| Brings 1.0.4.rst to master & sets the release date (for tomorrow)
cc @simonjayhawkins. | https://api.github.com/repos/pandas-dev/pandas/pulls/34428 | 2020-05-28T11:38:59Z | 2020-05-28T12:54:26Z | 2020-05-28T12:54:26Z | 2020-05-28T12:55:01Z |
DOC: 1.0.4 release notes and date | diff --git a/doc/source/whatsnew/v1.0.4.rst b/doc/source/whatsnew/v1.0.4.rst
index 1f2d4e2dba370..5cc1edc9ca9cd 100644
--- a/doc/source/whatsnew/v1.0.4.rst
+++ b/doc/source/whatsnew/v1.0.4.rst
@@ -1,7 +1,7 @@
.. _whatsnew_104:
-What's new in 1.0.4 (May ??, 2020)
+What's new in 1.0.4 (May 28, 2020)
------------------------------------
These are the changes in pandas 1.0.4. See :ref:`release` for a full changelog
@@ -15,21 +15,20 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
-- Bug where :meth:`Series.isna` and :meth:`DataFrame.isna` would raise for categorical dtype when ``pandas.options.mode.use_inf_as_na`` was set to ``True`` (:issue:`33594`)
-- Bug in :meth:`GroupBy.first` and :meth:`GroupBy.last` where None is not preserved in object dtype (:issue:`32800`)
-- Bug in DataFrame reductions using ``numeric_only=True`` and ExtensionArrays (:issue:`33256`).
+- Fix regression where :meth:`Series.isna` and :meth:`DataFrame.isna` would raise for categorical dtype when ``pandas.options.mode.use_inf_as_na`` was set to ``True`` (:issue:`33594`)
+- Fix regression in :meth:`GroupBy.first` and :meth:`GroupBy.last` where None is not preserved in object dtype (:issue:`32800`)
+- Fix regression in DataFrame reductions using ``numeric_only=True`` and ExtensionArrays (:issue:`33256`).
- Fix performance regression in ``memory_usage(deep=True)`` for object dtype (:issue:`33012`)
-- Bug where :meth:`Categorical.replace` would replace with ``NaN`` whenever the new value and replacement value were equal (:issue:`33288`)
-- Bug where an ordered :class:`Categorical` containing only ``NaN`` values would raise rather than returning ``NaN`` when taking the minimum or maximum (:issue:`33450`)
-- Bug in :meth:`DataFrameGroupBy.agg` with dictionary input losing ``ExtensionArray`` dtypes (:issue:`32194`)
+- Fix regression where :meth:`Categorical.replace` would replace with ``NaN`` whenever the new value and replacement value were equal (:issue:`33288`)
+- Fix regression where an ordered :class:`Categorical` containing only ``NaN`` values would raise rather than returning ``NaN`` when taking the minimum or maximum (:issue:`33450`)
+- Fix regression in :meth:`DataFrameGroupBy.agg` with dictionary input losing ``ExtensionArray`` dtypes (:issue:`32194`)
- Fix to preserve the ability to index with the "nearest" method with xarray's CFTimeIndex, an :class:`Index` subclass (`pydata/xarray#3751 <https://github.com/pydata/xarray/issues/3751>`_, :issue:`32905`).
- Fix regression in :meth:`DataFrame.describe` raising ``TypeError: unhashable type: 'dict'`` (:issue:`32409`)
-- Bug in :meth:`DataFrame.replace` casts columns to ``object`` dtype if items in ``to_replace`` not in values (:issue:`32988`)
-- Bug in :meth:`Series.groupby` would raise ``ValueError`` when grouping by :class:`PeriodIndex` level (:issue:`34010`)
-- Bug in :meth:`GroupBy.rolling.apply` ignores args and kwargs parameters (:issue:`33433`)
-- More informative error message with ``np.min`` or ``np.max`` on unordered :class:`Categorical` (:issue:`33115`)
-- Fixed regression in :meth:`DataFrame.loc` and :meth:`Series.loc` throwing an error when a ``datetime64[ns, tz]`` value is provided (:issue:`32395`)
--
+- Fix regression in :meth:`DataFrame.replace` casts columns to ``object`` dtype if items in ``to_replace`` not in values (:issue:`32988`)
+- Fix regression in :meth:`Series.groupby` would raise ``ValueError`` when grouping by :class:`PeriodIndex` level (:issue:`34010`)
+- Fix regression in :meth:`GroupBy.rolling.apply` ignores args and kwargs parameters (:issue:`33433`)
+- Fix regression in error message with ``np.min`` or ``np.max`` on unordered :class:`Categorical` (:issue:`33115`)
+- Fix regression in :meth:`DataFrame.loc` and :meth:`Series.loc` throwing an error when a ``datetime64[ns, tz]`` value is provided (:issue:`32395`)
.. _whatsnew_104.bug_fixes:
@@ -42,7 +41,6 @@ Bug fixes
- Bug in :meth:`read_parquet` was raising a ``FileNotFoundError`` when passed an s3 directory path. (:issue:`26388`)
- Bug in :meth:`~DataFrame.to_parquet` was throwing an ``AttributeError`` when writing a partitioned parquet file to s3 (:issue:`27596`)
- Bug in :meth:`GroupBy.quantile` causes the quantiles to be shifted when the ``by`` axis contains ``NaN`` (:issue:`33200`, :issue:`33569`)
--
Contributors
~~~~~~~~~~~~
| https://api.github.com/repos/pandas-dev/pandas/pulls/34425 | 2020-05-28T10:35:29Z | 2020-05-28T11:38:16Z | 2020-05-28T11:38:16Z | 2020-05-28T11:38:23Z | |
DOC: intersphinx inventory link for statsmodels | diff --git a/doc/source/conf.py b/doc/source/conf.py
index e8d825a509be9..2db09841db2f8 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -413,7 +413,7 @@
"py": ("https://pylib.readthedocs.io/en/latest/", None),
"python": ("https://docs.python.org/3/", None),
"scipy": ("https://docs.scipy.org/doc/scipy/reference/", None),
- "statsmodels": ("http://www.statsmodels.org/devel/", None),
+ "statsmodels": ("https://www.statsmodels.org/devel/", None),
}
# extlinks alias
| intersphinx inventory has moved: http://www.statsmodels.org/devel/objects.inv -> https://www.statsmodels.org/devel/objects.inv
EDIT: this is already change on master. this PR directly against 1.0.x | https://api.github.com/repos/pandas-dev/pandas/pulls/34424 | 2020-05-28T08:53:27Z | 2020-05-28T09:41:36Z | 2020-05-28T09:41:36Z | 2020-05-28T09:41:45Z |
BUG: Fix failing MacPython 32bit wheels for groupby rolling | diff --git a/pandas/core/window/indexers.py b/pandas/core/window/indexers.py
index 263502e3e26dc..f0a76dc17b411 100644
--- a/pandas/core/window/indexers.py
+++ b/pandas/core/window/indexers.py
@@ -218,16 +218,18 @@ def get_window_bounds(
start, end = indexer.get_window_bounds(
len(indicies), min_periods, center, closed
)
+ start = start.astype(np.int64)
+ end = end.astype(np.int64)
# Cannot use groupby_indicies as they might not be monotonic with the object
# we're rolling over
window_indicies = np.arange(
- window_indicies_start,
- window_indicies_start + len(indicies),
- dtype=np.int64,
+ window_indicies_start, window_indicies_start + len(indicies),
)
window_indicies_start += len(indicies)
# Extend as we'll be slicing window like [start, end)
- window_indicies = np.append(window_indicies, [window_indicies[-1] + 1])
+ window_indicies = np.append(
+ window_indicies, [window_indicies[-1] + 1]
+ ).astype(np.int64)
start_arrays.append(window_indicies.take(start))
end_arrays.append(window_indicies.take(end))
start = np.concatenate(start_arrays)
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index 3985cd8927b27..b06128052fa8f 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -2228,7 +2228,10 @@ def _create_blocks(self, obj: FrameOrSeries):
"""
# Ensure the object we're rolling over is monotonically sorted relative
# to the groups
- obj = obj.take(np.concatenate(list(self._groupby.grouper.indices.values())))
+ groupby_order = np.concatenate(
+ list(self._groupby.grouper.indices.values())
+ ).astype(np.int64)
+ obj = obj.take(groupby_order)
return super()._create_blocks(obj)
def _get_cython_func_type(self, func: str) -> Callable:
| - [x] closes #34410
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
What would be the best way to validate that this fixes the MacPython/pandas-wheels @TomAugspurger | https://api.github.com/repos/pandas-dev/pandas/pulls/34423 | 2020-05-28T04:26:34Z | 2020-05-29T19:05:06Z | 2020-05-29T19:05:06Z | 2020-05-29T19:08:49Z |
BUG: taking slices in _slice_take_blocks_ax0 | diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index e43c7bf887bcc..8e16d31b49150 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -1337,7 +1337,8 @@ def _slice_take_blocks_ax0(
# When filling blknos, make sure blknos is updated before appending to
# blocks list, that way new blkno is exactly len(blocks).
blocks = []
- for blkno, mgr_locs in libinternals.get_blkno_placements(blknos, group=True):
+ group = not only_slice
+ for blkno, mgr_locs in libinternals.get_blkno_placements(blknos, group=group):
if blkno == -1:
# If we've got here, fill_value was not lib.no_default
diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py
index b8ca5f16e4060..993b644c6993b 100644
--- a/pandas/tests/frame/test_arithmetic.py
+++ b/pandas/tests/frame/test_arithmetic.py
@@ -1514,3 +1514,16 @@ def test_dataframe_series_extension_dtypes():
tm.assert_frame_equal(result, expected)
result = df_ea + ser.astype("Int64")
tm.assert_frame_equal(result, expected)
+
+
+def test_dataframe_blockwise_slicelike():
+ # GH#34367
+ arr = np.random.randint(0, 1000, (100, 10))
+ df1 = pd.DataFrame(arr)
+ df2 = df1.copy()
+ df2.iloc[0, [1, 3, 7]] = np.nan
+
+ res = df1 + df2
+
+ expected = pd.DataFrame({i: df1[i] + df2[i] for i in df1.columns})
+ tm.assert_frame_equal(res, expected)
| - [x] closes #34367
- [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/34421 | 2020-05-28T03:16:31Z | 2020-05-28T17:19:47Z | 2020-05-28T17:19:47Z | 2021-11-20T23:23:10Z |
REF: move to_offset to liboffsets | diff --git a/pandas/_libs/tslibs/frequencies.pyx b/pandas/_libs/tslibs/frequencies.pyx
index 13edf3c46152a..8246e24319dbd 100644
--- a/pandas/_libs/tslibs/frequencies.pyx
+++ b/pandas/_libs/tslibs/frequencies.pyx
@@ -1,22 +1,17 @@
-import re
-
cimport numpy as cnp
cnp.import_array()
from pandas._libs.tslibs.util cimport is_integer_object
from pandas._libs.tslibs.offsets cimport is_offset_object
-
-# ----------------------------------------------------------------------
-# Constants
-
-# hack to handle WOM-1MON
-opattern = re.compile(
- r'([+\-]?\d*|[+\-]?\d*\.\d*)\s*([A-Za-z]+([\-][\dA-Za-z\-]+)?)'
+from pandas._libs.tslibs.offsets import (
+ INVALID_FREQ_ERR_MSG,
+ _dont_uppercase,
+ _lite_rule_alias,
+ base_and_stride,
+ opattern,
)
-INVALID_FREQ_ERR_MSG = "Invalid frequency: {0}"
-
# ---------------------------------------------------------------------
# Period codes
@@ -103,27 +98,6 @@ _period_code_map.update({
"W": 4000, # Weekly
"C": 5000}) # Custom Business Day
-_lite_rule_alias = {
- 'W': 'W-SUN',
- 'Q': 'Q-DEC',
-
- 'A': 'A-DEC', # YearEnd(month=12),
- 'Y': 'A-DEC',
- 'AS': 'AS-JAN', # YearBegin(month=1),
- 'YS': 'AS-JAN',
- 'BA': 'BA-DEC', # BYearEnd(month=12),
- 'BY': 'BA-DEC',
- 'BAS': 'BAS-JAN', # BYearBegin(month=1),
- 'BYS': 'BAS-JAN',
-
- 'Min': 'T',
- 'min': 'T',
- 'ms': 'L',
- 'us': 'U',
- 'ns': 'N'}
-
-_dont_uppercase = {'MS', 'ms'}
-
# Map attribute-name resolutions to resolution abbreviations
_attrname_to_abbrevs = {
"year": "A",
@@ -223,36 +197,6 @@ cpdef get_freq_code(freqstr):
return code, stride
-cpdef base_and_stride(str freqstr):
- """
- Return base freq and stride info from string representation
-
- Returns
- -------
- base : str
- stride : int
-
- Examples
- --------
- _freq_and_stride('5Min') -> 'Min', 5
- """
- groups = opattern.match(freqstr)
-
- if not groups:
- raise ValueError(f"Could not evaluate {freqstr}")
-
- stride = groups.group(1)
-
- if len(stride):
- stride = int(stride)
- else:
- stride = 1
-
- base = groups.group(2)
-
- return base, stride
-
-
cpdef _period_str_to_code(str freqstr):
freqstr = _lite_rule_alias.get(freqstr, freqstr)
diff --git a/pandas/_libs/tslibs/offsets.pxd b/pandas/_libs/tslibs/offsets.pxd
index e75cd8bdf1baf..69b878c77f0b8 100644
--- a/pandas/_libs/tslibs/offsets.pxd
+++ b/pandas/_libs/tslibs/offsets.pxd
@@ -1,3 +1,3 @@
-cdef to_offset(object obj)
+cpdef to_offset(object obj)
cdef bint is_offset_object(object obj)
cdef bint is_tick_object(object obj)
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx
index 8e5634253bd39..a32ffb8aa3689 100644
--- a/pandas/_libs/tslibs/offsets.pyx
+++ b/pandas/_libs/tslibs/offsets.pyx
@@ -1,6 +1,7 @@
import cython
import operator
+import re
import time
from typing import Any
import warnings
@@ -103,17 +104,6 @@ cdef bint is_tick_object(object obj):
return isinstance(obj, Tick)
-cdef to_offset(object obj):
- """
- Wrap pandas.tseries.frequencies.to_offset to keep centralize runtime
- imports
- """
- if isinstance(obj, BaseOffset):
- return obj
- from pandas.tseries.frequencies import to_offset
- return to_offset(obj)
-
-
cdef datetime _as_datetime(datetime obj):
if isinstance(obj, ABCTimestamp):
return obj.to_pydatetime()
@@ -3505,6 +3495,9 @@ CBMonthEnd = CustomBusinessMonthEnd
CBMonthBegin = CustomBusinessMonthBegin
CDay = CustomBusinessDay
+# ----------------------------------------------------------------------
+# to_offset helpers
+
prefix_mapping = {
offset._prefix: offset
for offset in [
@@ -3542,6 +3535,224 @@ prefix_mapping = {
]
}
+_name_to_offset_map = {
+ "days": Day(1),
+ "hours": Hour(1),
+ "minutes": Minute(1),
+ "seconds": Second(1),
+ "milliseconds": Milli(1),
+ "microseconds": Micro(1),
+ "nanoseconds": Nano(1),
+}
+
+# hack to handle WOM-1MON
+opattern = re.compile(
+ r"([+\-]?\d*|[+\-]?\d*\.\d*)\s*([A-Za-z]+([\-][\dA-Za-z\-]+)?)"
+)
+
+_lite_rule_alias = {
+ "W": "W-SUN",
+ "Q": "Q-DEC",
+
+ "A": "A-DEC", # YearEnd(month=12),
+ "Y": "A-DEC",
+ "AS": "AS-JAN", # YearBegin(month=1),
+ "YS": "AS-JAN",
+ "BA": "BA-DEC", # BYearEnd(month=12),
+ "BY": "BA-DEC",
+ "BAS": "BAS-JAN", # BYearBegin(month=1),
+ "BYS": "BAS-JAN",
+
+ "Min": "T",
+ "min": "T",
+ "ms": "L",
+ "us": "U",
+ "ns": "N",
+}
+
+_dont_uppercase = {"MS", "ms"}
+
+INVALID_FREQ_ERR_MSG = "Invalid frequency: {0}"
+
+# TODO: still needed?
+# cache of previously seen offsets
+_offset_map = {}
+
+
+cpdef base_and_stride(str freqstr):
+ """
+ Return base freq and stride info from string representation
+
+ Returns
+ -------
+ base : str
+ stride : int
+
+ Examples
+ --------
+ _freq_and_stride('5Min') -> 'Min', 5
+ """
+ groups = opattern.match(freqstr)
+
+ if not groups:
+ raise ValueError(f"Could not evaluate {freqstr}")
+
+ stride = groups.group(1)
+
+ if len(stride):
+ stride = int(stride)
+ else:
+ stride = 1
+
+ base = groups.group(2)
+
+ return base, stride
+
+
+# TODO: better name?
+def _get_offset(name: str) -> BaseOffset:
+ """
+ Return DateOffset object associated with rule name.
+
+ Examples
+ --------
+ _get_offset('EOM') --> BMonthEnd(1)
+ """
+ if name not in _dont_uppercase:
+ name = name.upper()
+ name = _lite_rule_alias.get(name, name)
+ name = _lite_rule_alias.get(name.lower(), name)
+ else:
+ name = _lite_rule_alias.get(name, name)
+
+ if name not in _offset_map:
+ try:
+ split = name.split("-")
+ klass = prefix_mapping[split[0]]
+ # handles case where there's no suffix (and will TypeError if too
+ # many '-')
+ offset = klass._from_name(*split[1:])
+ except (ValueError, TypeError, KeyError) as err:
+ # bad prefix or suffix
+ raise ValueError(INVALID_FREQ_ERR_MSG.format(name)) from err
+ # cache
+ _offset_map[name] = offset
+
+ return _offset_map[name]
+
+
+cpdef to_offset(freq):
+ """
+ Return DateOffset object from string or tuple representation
+ or datetime.timedelta object.
+
+ Parameters
+ ----------
+ freq : str, tuple, datetime.timedelta, DateOffset or None
+
+ Returns
+ -------
+ DateOffset or None
+
+ Raises
+ ------
+ ValueError
+ If freq is an invalid frequency
+
+ See Also
+ --------
+ DateOffset : Standard kind of date increment used for a date range.
+
+ Examples
+ --------
+ >>> to_offset("5min")
+ <5 * Minutes>
+
+ >>> to_offset("1D1H")
+ <25 * Hours>
+
+ >>> to_offset(("W", 2))
+ <2 * Weeks: weekday=6>
+
+ >>> to_offset((2, "B"))
+ <2 * BusinessDays>
+
+ >>> to_offset(pd.Timedelta(days=1))
+ <Day>
+
+ >>> to_offset(Hour())
+ <Hour>
+ """
+ if freq is None:
+ return None
+
+ if isinstance(freq, BaseOffset):
+ return freq
+
+ if isinstance(freq, tuple):
+ name = freq[0]
+ stride = freq[1]
+ if isinstance(stride, str):
+ name, stride = stride, name
+ name, _ = base_and_stride(name)
+ delta = _get_offset(name) * stride
+
+ elif isinstance(freq, timedelta):
+ from .timedeltas import Timedelta
+
+ delta = None
+ freq = Timedelta(freq)
+ try:
+ for name in freq.components._fields:
+ offset = _name_to_offset_map[name]
+ stride = getattr(freq.components, name)
+ if stride != 0:
+ offset = stride * offset
+ if delta is None:
+ delta = offset
+ else:
+ delta = delta + offset
+ except ValueError as err:
+ raise ValueError(INVALID_FREQ_ERR_MSG.format(freq)) from err
+
+ else:
+ delta = None
+ stride_sign = None
+ try:
+ split = re.split(opattern, freq)
+ if split[-1] != "" and not split[-1].isspace():
+ # the last element must be blank
+ raise ValueError("last element must be blank")
+ for sep, stride, name in zip(split[0::4], split[1::4], split[2::4]):
+ if sep != "" and not sep.isspace():
+ raise ValueError("separator must be spaces")
+ prefix = _lite_rule_alias.get(name) or name
+ if stride_sign is None:
+ stride_sign = -1 if stride.startswith("-") else 1
+ if not stride:
+ stride = 1
+
+ from .resolution import Resolution # TODO: avoid runtime import
+
+ if prefix in Resolution.reso_str_bump_map:
+ stride, name = Resolution.get_stride_from_decimal(
+ float(stride), prefix
+ )
+ stride = int(stride)
+ offset = _get_offset(name)
+ offset = offset * int(np.fabs(stride) * stride_sign)
+ if delta is None:
+ delta = offset
+ else:
+ delta = delta + offset
+ except (ValueError, TypeError) as err:
+ raise ValueError(INVALID_FREQ_ERR_MSG.format(freq)) from err
+
+ if delta is None:
+ raise ValueError(INVALID_FREQ_ERR_MSG.format(freq))
+
+ return delta
+
# ----------------------------------------------------------------------
# RelativeDelta Arithmetic
diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py
index 350bf8c38e6bf..86cc7ff753660 100644
--- a/pandas/tests/tseries/offsets/test_offsets.py
+++ b/pandas/tests/tseries/offsets/test_offsets.py
@@ -17,7 +17,7 @@
get_freq_str,
)
import pandas._libs.tslibs.offsets as liboffsets
-from pandas._libs.tslibs.offsets import ApplyTypeError
+from pandas._libs.tslibs.offsets import ApplyTypeError, _get_offset, _offset_map
import pandas.compat as compat
from pandas.compat.numpy import np_datetime64_compat
from pandas.errors import PerformanceWarning
@@ -27,7 +27,6 @@
from pandas.core.series import Series
from pandas.io.pickle import read_pickle
-from pandas.tseries.frequencies import _get_offset, _offset_map
from pandas.tseries.holiday import USFederalHolidayCalendar
import pandas.tseries.offsets as offsets
from pandas.tseries.offsets import (
diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py
index 084ad4294f9d0..47ae66ac4f91b 100644
--- a/pandas/tseries/frequencies.py
+++ b/pandas/tseries/frequencies.py
@@ -1,29 +1,21 @@
-from datetime import timedelta
-import re
-from typing import Dict, Optional
+from typing import Optional
import warnings
import numpy as np
from pandas._libs.algos import unique_deltas
-from pandas._libs.tslibs import Timedelta, Timestamp
+from pandas._libs.tslibs import Timestamp
from pandas._libs.tslibs.ccalendar import MONTH_ALIASES, MONTH_NUMBERS, int_to_weekday
from pandas._libs.tslibs.fields import build_field_sarray
-import pandas._libs.tslibs.frequencies as libfreqs
-from pandas._libs.tslibs.offsets import (
+from pandas._libs.tslibs.offsets import ( # noqa:F401
DateOffset,
Day,
- Hour,
- Micro,
- Milli,
- Minute,
- Nano,
- Second,
+ _get_offset,
_offset_to_period_map,
- prefix_mapping,
+ to_offset,
)
from pandas._libs.tslibs.parsing import get_rule_month
-from pandas._libs.tslibs.resolution import Resolution, month_position_check
+from pandas._libs.tslibs.resolution import month_position_check
from pandas._libs.tslibs.timezones import UTC
from pandas._libs.tslibs.tzconversion import tz_convert
from pandas.util._decorators import cache_readonly
@@ -47,9 +39,6 @@
# ---------------------------------------------------------------------
# Offset names ("time rules") and related functions
-#: cache of previously seen offsets
-_offset_map: Dict[str, DateOffset] = {}
-
def get_period_alias(offset_str: str) -> Optional[str]:
"""
@@ -58,126 +47,6 @@ def get_period_alias(offset_str: str) -> Optional[str]:
return _offset_to_period_map.get(offset_str, None)
-_name_to_offset_map = {
- "days": Day(1),
- "hours": Hour(1),
- "minutes": Minute(1),
- "seconds": Second(1),
- "milliseconds": Milli(1),
- "microseconds": Micro(1),
- "nanoseconds": Nano(1),
-}
-
-
-def to_offset(freq) -> Optional[DateOffset]:
- """
- Return DateOffset object from string or tuple representation
- or datetime.timedelta object.
-
- Parameters
- ----------
- freq : str, tuple, datetime.timedelta, DateOffset or None
-
- Returns
- -------
- DateOffset
- None if freq is None.
-
- Raises
- ------
- ValueError
- If freq is an invalid frequency
-
- See Also
- --------
- DateOffset : Standard kind of date increment used for a date range.
-
- Examples
- --------
- >>> to_offset("5min")
- <5 * Minutes>
-
- >>> to_offset("1D1H")
- <25 * Hours>
-
- >>> to_offset(("W", 2))
- <2 * Weeks: weekday=6>
-
- >>> to_offset((2, "B"))
- <2 * BusinessDays>
-
- >>> to_offset(pd.Timedelta(days=1))
- <Day>
-
- >>> to_offset(Hour())
- <Hour>
- """
- if freq is None:
- return None
-
- if isinstance(freq, DateOffset):
- return freq
-
- if isinstance(freq, tuple):
- name = freq[0]
- stride = freq[1]
- if isinstance(stride, str):
- name, stride = stride, name
- name, _ = libfreqs.base_and_stride(name)
- delta = _get_offset(name) * stride
-
- elif isinstance(freq, timedelta):
- delta = None
- freq = Timedelta(freq)
- try:
- for name in freq.components._fields:
- offset = _name_to_offset_map[name]
- stride = getattr(freq.components, name)
- if stride != 0:
- offset = stride * offset
- if delta is None:
- delta = offset
- else:
- delta = delta + offset
- except ValueError as err:
- raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq)) from err
-
- else:
- delta = None
- stride_sign = None
- try:
- split = re.split(libfreqs.opattern, freq)
- if split[-1] != "" and not split[-1].isspace():
- # the last element must be blank
- raise ValueError("last element must be blank")
- for sep, stride, name in zip(split[0::4], split[1::4], split[2::4]):
- if sep != "" and not sep.isspace():
- raise ValueError("separator must be spaces")
- prefix = libfreqs._lite_rule_alias.get(name) or name
- if stride_sign is None:
- stride_sign = -1 if stride.startswith("-") else 1
- if not stride:
- stride = 1
- if prefix in Resolution.reso_str_bump_map:
- stride, name = Resolution.get_stride_from_decimal(
- float(stride), prefix
- )
- stride = int(stride)
- offset = _get_offset(name)
- offset = offset * int(np.fabs(stride) * stride_sign)
- if delta is None:
- delta = offset
- else:
- delta = delta + offset
- except (ValueError, TypeError) as err:
- raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq)) from err
-
- if delta is None:
- raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq))
-
- return delta
-
-
def get_offset(name: str) -> DateOffset:
"""
Return DateOffset object associated with rule name.
@@ -197,37 +66,6 @@ def get_offset(name: str) -> DateOffset:
return _get_offset(name)
-def _get_offset(name: str) -> DateOffset:
- """
- Return DateOffset object associated with rule name.
-
- Examples
- --------
- _get_offset('EOM') --> BMonthEnd(1)
- """
- if name not in libfreqs._dont_uppercase:
- name = name.upper()
- name = libfreqs._lite_rule_alias.get(name, name)
- name = libfreqs._lite_rule_alias.get(name.lower(), name)
- else:
- name = libfreqs._lite_rule_alias.get(name, name)
-
- if name not in _offset_map:
- try:
- split = name.split("-")
- klass = prefix_mapping[split[0]]
- # handles case where there's no suffix (and will TypeError if too
- # many '-')
- offset = klass._from_name(*split[1:])
- except (ValueError, TypeError, KeyError) as err:
- # bad prefix or suffix
- raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(name)) from err
- # cache
- _offset_map[name] = offset
-
- return _offset_map[name]
-
-
# ---------------------------------------------------------------------
# Period codes
| https://api.github.com/repos/pandas-dev/pandas/pulls/34420 | 2020-05-28T02:16:20Z | 2020-05-28T17:11:55Z | 2020-05-28T17:11:55Z | 2020-05-28T17:20:37Z | |
REF: make remaining offset classes cdef | diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx
index 8e5634253bd39..37d9f48de5146 100644
--- a/pandas/_libs/tslibs/offsets.pyx
+++ b/pandas/_libs/tslibs/offsets.pyx
@@ -3347,7 +3347,7 @@ cdef class CustomBusinessDay(BusinessDay):
return np.is_busday(day64, busdaycal=self.calendar)
-class CustomBusinessHour(BusinessHour):
+cdef class CustomBusinessHour(BusinessHour):
"""
DateOffset subclass representing possibly n custom business days.
"""
@@ -3389,7 +3389,7 @@ class CustomBusinessHour(BusinessHour):
)
-class _CustomBusinessMonth(BusinessMixin, MonthOffset):
+cdef class _CustomBusinessMonth(BusinessMixin):
"""
DateOffset subclass representing custom business month(s).
@@ -3416,9 +3416,6 @@ class _CustomBusinessMonth(BusinessMixin, MonthOffset):
["n", "normalize", "weekmask", "holidays", "calendar", "offset"]
)
- is_on_offset = BaseOffset.is_on_offset # override MonthOffset method
- apply_index = BaseOffset.apply_index # override MonthOffset method
-
def __init__(
self,
n=1,
@@ -3490,11 +3487,11 @@ class _CustomBusinessMonth(BusinessMixin, MonthOffset):
return result
-class CustomBusinessMonthEnd(_CustomBusinessMonth):
+cdef class CustomBusinessMonthEnd(_CustomBusinessMonth):
_prefix = "CBM"
-class CustomBusinessMonthBegin(_CustomBusinessMonth):
+cdef class CustomBusinessMonthBegin(_CustomBusinessMonth):
_prefix = "CBMS"
| After this its just down to
1) a pass to clean up pickle-based kludges that were needed when these were mixed python/cython
2) privatize things in liboffsets no longer needed externally
3) move to_offset int liboffsets | https://api.github.com/repos/pandas-dev/pandas/pulls/34419 | 2020-05-28T00:20:04Z | 2020-05-28T17:13:18Z | 2020-05-28T17:13:18Z | 2020-05-28T17:21:51Z |
DEPR: deprecate non keyword arguments in read_excel | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 20e2cce1a3dfa..a014729e86a7e 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -588,6 +588,10 @@ Deprecations
version 1.1. All other arguments should be given as keyword
arguments (:issue:`27573`).
+- Passing any arguments but the first 2 to :func:`read_excel` as
+ positional arguments is deprecated since version 1.1. All other
+ arguments should be given as keyword arguments (:issue:`27573`).
+
- :func:`pandas.api.types.is_categorical` is deprecated and will be removed in a future version; use `:func:pandas.api.types.is_categorical_dtype` instead (:issue:`33385`)
- :meth:`Index.get_value` is deprecated and will be removed in a future version (:issue:`19728`)
- :meth:`DateOffset.__call__` is deprecated and will be removed in a future version, use ``offset + other`` instead (:issue:`34171`)
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index d1139f640cef4..d55bdffe689f2 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -8,7 +8,7 @@
from pandas._libs.parsers import STR_NA_VALUES
from pandas.errors import EmptyDataError
-from pandas.util._decorators import Appender
+from pandas.util._decorators import Appender, deprecate_nonkeyword_arguments
from pandas.core.dtypes.common import is_bool, is_float, is_integer, is_list_like
@@ -266,6 +266,7 @@
)
+@deprecate_nonkeyword_arguments(allowed_args=2, version="2.0")
@Appender(_read_excel_doc)
def read_excel(
io,
diff --git a/pandas/tests/io/excel/test_odf.py b/pandas/tests/io/excel/test_odf.py
index b9a3e8b59b133..d6c6399f082c6 100644
--- a/pandas/tests/io/excel/test_odf.py
+++ b/pandas/tests/io/excel/test_odf.py
@@ -33,7 +33,7 @@ def test_read_writer_table():
columns=["Column 1", "Unnamed: 2", "Column 3"],
)
- result = pd.read_excel("writertable.odt", "Table1", index_col=0)
+ result = pd.read_excel("writertable.odt", sheet_name="Table1", index_col=0)
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
index 99447c03e89af..fd1533dd65dc4 100644
--- a/pandas/tests/io/excel/test_readers.py
+++ b/pandas/tests/io/excel/test_readers.py
@@ -1,4 +1,3 @@
-from collections import OrderedDict
import contextlib
from datetime import datetime, time
from functools import partial
@@ -136,13 +135,19 @@ def test_usecols_int(self, read_ext, df_ref):
msg = "Passing an integer for `usecols`"
with pytest.raises(ValueError, match=msg):
with ignore_xlrd_time_clock_warning():
- pd.read_excel("test1" + read_ext, "Sheet1", index_col=0, usecols=3)
+ pd.read_excel(
+ "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols=3
+ )
# usecols as int
with pytest.raises(ValueError, match=msg):
with ignore_xlrd_time_clock_warning():
pd.read_excel(
- "test1" + read_ext, "Sheet2", skiprows=[1], index_col=0, usecols=3
+ "test1" + read_ext,
+ sheet_name="Sheet2",
+ skiprows=[1],
+ index_col=0,
+ usecols=3,
)
def test_usecols_list(self, read_ext, df_ref):
@@ -151,10 +156,14 @@ def test_usecols_list(self, read_ext, df_ref):
df_ref = df_ref.reindex(columns=["B", "C"])
df1 = pd.read_excel(
- "test1" + read_ext, "Sheet1", index_col=0, usecols=[0, 2, 3]
+ "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols=[0, 2, 3]
)
df2 = pd.read_excel(
- "test1" + read_ext, "Sheet2", skiprows=[1], index_col=0, usecols=[0, 2, 3]
+ "test1" + read_ext,
+ sheet_name="Sheet2",
+ skiprows=[1],
+ index_col=0,
+ usecols=[0, 2, 3],
)
# TODO add index to xls file)
@@ -166,9 +175,15 @@ def test_usecols_str(self, read_ext, df_ref):
pytest.xfail("Sheets containing datetimes not supported by pyxlsb")
df1 = df_ref.reindex(columns=["A", "B", "C"])
- df2 = pd.read_excel("test1" + read_ext, "Sheet1", index_col=0, usecols="A:D")
+ df2 = pd.read_excel(
+ "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A:D"
+ )
df3 = pd.read_excel(
- "test1" + read_ext, "Sheet2", skiprows=[1], index_col=0, usecols="A:D"
+ "test1" + read_ext,
+ sheet_name="Sheet2",
+ skiprows=[1],
+ index_col=0,
+ usecols="A:D",
)
# TODO add index to xls, read xls ignores index name ?
@@ -176,18 +191,30 @@ def test_usecols_str(self, read_ext, df_ref):
tm.assert_frame_equal(df3, df1, check_names=False)
df1 = df_ref.reindex(columns=["B", "C"])
- df2 = pd.read_excel("test1" + read_ext, "Sheet1", index_col=0, usecols="A,C,D")
+ df2 = pd.read_excel(
+ "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A,C,D"
+ )
df3 = pd.read_excel(
- "test1" + read_ext, "Sheet2", skiprows=[1], index_col=0, usecols="A,C,D"
+ "test1" + read_ext,
+ sheet_name="Sheet2",
+ skiprows=[1],
+ index_col=0,
+ usecols="A,C,D",
)
# TODO add index to xls file
tm.assert_frame_equal(df2, df1, check_names=False)
tm.assert_frame_equal(df3, df1, check_names=False)
df1 = df_ref.reindex(columns=["B", "C"])
- df2 = pd.read_excel("test1" + read_ext, "Sheet1", index_col=0, usecols="A,C:D")
+ df2 = pd.read_excel(
+ "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A,C:D"
+ )
df3 = pd.read_excel(
- "test1" + read_ext, "Sheet2", skiprows=[1], index_col=0, usecols="A,C:D"
+ "test1" + read_ext,
+ sheet_name="Sheet2",
+ skiprows=[1],
+ index_col=0,
+ usecols="A,C:D",
)
tm.assert_frame_equal(df2, df1, check_names=False)
tm.assert_frame_equal(df3, df1, check_names=False)
@@ -201,7 +228,7 @@ def test_usecols_diff_positional_int_columns_order(self, read_ext, usecols, df_r
expected = df_ref[["A", "C"]]
result = pd.read_excel(
- "test1" + read_ext, "Sheet1", index_col=0, usecols=usecols
+ "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols=usecols
)
tm.assert_frame_equal(result, expected, check_names=False)
@@ -210,7 +237,7 @@ def test_usecols_diff_positional_str_columns_order(self, read_ext, usecols, df_r
expected = df_ref[["B", "D"]]
expected.index = range(len(expected))
- result = pd.read_excel("test1" + read_ext, "Sheet1", usecols=usecols)
+ result = pd.read_excel("test1" + read_ext, sheet_name="Sheet1", usecols=usecols)
tm.assert_frame_equal(result, expected, check_names=False)
def test_read_excel_without_slicing(self, read_ext, df_ref):
@@ -218,7 +245,7 @@ def test_read_excel_without_slicing(self, read_ext, df_ref):
pytest.xfail("Sheets containing datetimes not supported by pyxlsb")
expected = df_ref
- result = pd.read_excel("test1" + read_ext, "Sheet1", index_col=0)
+ result = pd.read_excel("test1" + read_ext, sheet_name="Sheet1", index_col=0)
tm.assert_frame_equal(result, expected, check_names=False)
def test_usecols_excel_range_str(self, read_ext, df_ref):
@@ -227,7 +254,7 @@ def test_usecols_excel_range_str(self, read_ext, df_ref):
expected = df_ref[["C", "D"]]
result = pd.read_excel(
- "test1" + read_ext, "Sheet1", index_col=0, usecols="A,D:E"
+ "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A,D:E"
)
tm.assert_frame_equal(result, expected, check_names=False)
@@ -235,19 +262,24 @@ def test_usecols_excel_range_str_invalid(self, read_ext):
msg = "Invalid column name: E1"
with pytest.raises(ValueError, match=msg):
- pd.read_excel("test1" + read_ext, "Sheet1", usecols="D:E1")
+ pd.read_excel("test1" + read_ext, sheet_name="Sheet1", usecols="D:E1")
def test_index_col_label_error(self, read_ext):
msg = "list indices must be integers.*, not str"
with pytest.raises(TypeError, match=msg):
pd.read_excel(
- "test1" + read_ext, "Sheet1", index_col=["A"], usecols=["A", "C"]
+ "test1" + read_ext,
+ sheet_name="Sheet1",
+ index_col=["A"],
+ usecols=["A", "C"],
)
def test_index_col_empty(self, read_ext):
# see gh-9208
- result = pd.read_excel("test1" + read_ext, "Sheet3", index_col=["A", "B", "C"])
+ result = pd.read_excel(
+ "test1" + read_ext, sheet_name="Sheet3", index_col=["A", "B", "C"]
+ )
expected = DataFrame(
columns=["D", "E", "F"],
index=MultiIndex(levels=[[]] * 3, codes=[[]] * 3, names=["A", "B", "C"]),
@@ -257,7 +289,9 @@ def test_index_col_empty(self, read_ext):
@pytest.mark.parametrize("index_col", [None, 2])
def test_index_col_with_unnamed(self, read_ext, index_col):
# see gh-18792
- result = pd.read_excel("test1" + read_ext, "Sheet4", index_col=index_col)
+ result = pd.read_excel(
+ "test1" + read_ext, sheet_name="Sheet4", index_col=index_col
+ )
expected = DataFrame(
[["i1", "a", "x"], ["i2", "b", "y"]], columns=["Unnamed: 0", "col1", "col2"]
)
@@ -286,7 +320,7 @@ def test_usecols_wrong_type(self, read_ext):
def test_excel_stop_iterator(self, read_ext):
- parsed = pd.read_excel("test2" + read_ext, "Sheet1")
+ parsed = pd.read_excel("test2" + read_ext, sheet_name="Sheet1")
expected = DataFrame([["aaaa", "bbbbb"]], columns=["Test", "Test1"])
tm.assert_frame_equal(parsed, expected)
@@ -294,7 +328,7 @@ def test_excel_cell_error_na(self, read_ext):
if pd.read_excel.keywords["engine"] == "pyxlsb":
pytest.xfail("Sheets containing datetimes not supported by pyxlsb")
- parsed = pd.read_excel("test3" + read_ext, "Sheet1")
+ parsed = pd.read_excel("test3" + read_ext, sheet_name="Sheet1")
expected = DataFrame([[np.nan]], columns=["Test"])
tm.assert_frame_equal(parsed, expected)
@@ -302,13 +336,17 @@ def test_excel_table(self, read_ext, df_ref):
if pd.read_excel.keywords["engine"] == "pyxlsb":
pytest.xfail("Sheets containing datetimes not supported by pyxlsb")
- df1 = pd.read_excel("test1" + read_ext, "Sheet1", index_col=0)
- df2 = pd.read_excel("test1" + read_ext, "Sheet2", skiprows=[1], index_col=0)
+ df1 = pd.read_excel("test1" + read_ext, sheet_name="Sheet1", index_col=0)
+ df2 = pd.read_excel(
+ "test1" + read_ext, sheet_name="Sheet2", skiprows=[1], index_col=0
+ )
# TODO add index to file
tm.assert_frame_equal(df1, df_ref, check_names=False)
tm.assert_frame_equal(df2, df_ref, check_names=False)
- df3 = pd.read_excel("test1" + read_ext, "Sheet1", index_col=0, skipfooter=1)
+ df3 = pd.read_excel(
+ "test1" + read_ext, sheet_name="Sheet1", index_col=0, skipfooter=1
+ )
tm.assert_frame_equal(df3, df1.iloc[:-1])
def test_reader_special_dtypes(self, read_ext):
@@ -316,50 +354,49 @@ def test_reader_special_dtypes(self, read_ext):
pytest.xfail("Sheets containing datetimes not supported by pyxlsb")
expected = DataFrame.from_dict(
- OrderedDict(
- [
- ("IntCol", [1, 2, -3, 4, 0]),
- ("FloatCol", [1.25, 2.25, 1.83, 1.92, 0.0000000005]),
- ("BoolCol", [True, False, True, True, False]),
- ("StrCol", [1, 2, 3, 4, 5]),
- # GH5394 - this is why convert_float isn't vectorized
- ("Str2Col", ["a", 3, "c", "d", "e"]),
- (
- "DateCol",
- [
- datetime(2013, 10, 30),
- datetime(2013, 10, 31),
- datetime(1905, 1, 1),
- datetime(2013, 12, 14),
- datetime(2015, 3, 14),
- ],
- ),
- ]
- )
+ {
+ "IntCol": [1, 2, -3, 4, 0],
+ "FloatCol": [1.25, 2.25, 1.83, 1.92, 0.0000000005],
+ "BoolCol": [True, False, True, True, False],
+ "StrCol": [1, 2, 3, 4, 5],
+ # GH5394 - this is why convert_float isn't vectorized
+ "Str2Col": ["a", 3, "c", "d", "e"],
+ "DateCol": [
+ datetime(2013, 10, 30),
+ datetime(2013, 10, 31),
+ datetime(1905, 1, 1),
+ datetime(2013, 12, 14),
+ datetime(2015, 3, 14),
+ ],
+ },
)
basename = "test_types"
# should read in correctly and infer types
- actual = pd.read_excel(basename + read_ext, "Sheet1")
+ actual = pd.read_excel(basename + read_ext, sheet_name="Sheet1")
tm.assert_frame_equal(actual, expected)
# if not coercing number, then int comes in as float
float_expected = expected.copy()
float_expected["IntCol"] = float_expected["IntCol"].astype(float)
float_expected.loc[float_expected.index[1], "Str2Col"] = 3.0
- actual = pd.read_excel(basename + read_ext, "Sheet1", convert_float=False)
+ actual = pd.read_excel(
+ basename + read_ext, sheet_name="Sheet1", convert_float=False
+ )
tm.assert_frame_equal(actual, float_expected)
# check setting Index (assuming xls and xlsx are the same here)
for icol, name in enumerate(expected.columns):
- actual = pd.read_excel(basename + read_ext, "Sheet1", index_col=icol)
+ actual = pd.read_excel(
+ basename + read_ext, sheet_name="Sheet1", index_col=icol
+ )
exp = expected.set_index(name)
tm.assert_frame_equal(actual, exp)
# convert_float and converters should be different but both accepted
expected["StrCol"] = expected["StrCol"].apply(str)
actual = pd.read_excel(
- basename + read_ext, "Sheet1", converters={"StrCol": str}
+ basename + read_ext, sheet_name="Sheet1", converters={"StrCol": str}
)
tm.assert_frame_equal(actual, expected)
@@ -367,7 +404,7 @@ def test_reader_special_dtypes(self, read_ext):
no_convert_float["StrCol"] = no_convert_float["StrCol"].apply(str)
actual = pd.read_excel(
basename + read_ext,
- "Sheet1",
+ sheet_name="Sheet1",
convert_float=False,
converters={"StrCol": str},
)
@@ -379,14 +416,12 @@ def test_reader_converters(self, read_ext):
basename = "test_converters"
expected = DataFrame.from_dict(
- OrderedDict(
- [
- ("IntCol", [1, 2, -3, -1000, 0]),
- ("FloatCol", [12.5, np.nan, 18.3, 19.2, 0.000000005]),
- ("BoolCol", ["Found", "Found", "Found", "Not found", "Found"]),
- ("StrCol", ["1", np.nan, "3", "4", "5"]),
- ]
- )
+ {
+ "IntCol": [1, 2, -3, -1000, 0],
+ "FloatCol": [12.5, np.nan, 18.3, 19.2, 0.000000005],
+ "BoolCol": ["Found", "Found", "Found", "Not found", "Found"],
+ "StrCol": ["1", np.nan, "3", "4", "5"],
+ }
)
converters = {
@@ -398,7 +433,9 @@ def test_reader_converters(self, read_ext):
# should read in correctly and set types of single cells (not array
# dtypes)
- actual = pd.read_excel(basename + read_ext, "Sheet1", converters=converters)
+ actual = pd.read_excel(
+ basename + read_ext, sheet_name="Sheet1", converters=converters
+ )
tm.assert_frame_equal(actual, expected)
def test_reader_dtype(self, read_ext):
@@ -483,7 +520,7 @@ def test_reader_spaces(self, read_ext):
tm.assert_frame_equal(actual, expected)
def test_reading_all_sheets(self, read_ext):
- # Test reading all sheetnames by setting sheetname to None,
+ # Test reading all sheet names by setting sheet_name to None,
# Ensure a dict is returned.
# See PR #9450
basename = "test_multisheet"
@@ -496,7 +533,7 @@ def test_reading_all_sheets(self, read_ext):
assert expected_keys == list(dfs.keys())
def test_reading_multiple_specific_sheets(self, read_ext):
- # Test reading specific sheetnames by specifying a mixed list
+ # Test reading specific sheet names by specifying a mixed list
# of integers and strings, and confirm that duplicated sheet
# references (positions/names) are removed properly.
# Ensure a dict is returned
@@ -510,7 +547,7 @@ def test_reading_multiple_specific_sheets(self, read_ext):
assert len(expected_keys) == len(dfs.keys())
def test_reading_all_sheets_with_blank(self, read_ext):
- # Test reading all sheetnames by setting sheetname to None,
+ # Test reading all sheet names by setting sheet_name to None,
# In the case where some sheets are blank.
# Issue #11711
basename = "blank_with_header"
@@ -520,12 +557,12 @@ def test_reading_all_sheets_with_blank(self, read_ext):
# GH6403
def test_read_excel_blank(self, read_ext):
- actual = pd.read_excel("blank" + read_ext, "Sheet1")
+ actual = pd.read_excel("blank" + read_ext, sheet_name="Sheet1")
tm.assert_frame_equal(actual, DataFrame())
def test_read_excel_blank_with_header(self, read_ext):
expected = DataFrame(columns=["col_1", "col_2"])
- actual = pd.read_excel("blank_with_header" + read_ext, "Sheet1")
+ actual = pd.read_excel("blank_with_header" + read_ext, sheet_name="Sheet1")
tm.assert_frame_equal(actual, expected)
def test_date_conversion_overflow(self, read_ext):
@@ -569,9 +606,9 @@ def test_sheet_name(self, read_ext, df_ref):
def test_excel_read_buffer(self, read_ext):
pth = "test1" + read_ext
- expected = pd.read_excel(pth, "Sheet1", index_col=0)
+ expected = pd.read_excel(pth, sheet_name="Sheet1", index_col=0)
with open(pth, "rb") as f:
- actual = pd.read_excel(f, "Sheet1", index_col=0)
+ actual = pd.read_excel(f, sheet_name="Sheet1", index_col=0)
tm.assert_frame_equal(expected, actual)
def test_bad_engine_raises(self, read_ext):
@@ -626,10 +663,10 @@ def test_read_from_pathlib_path(self, read_ext):
from pathlib import Path
str_path = "test1" + read_ext
- expected = pd.read_excel(str_path, "Sheet1", index_col=0)
+ expected = pd.read_excel(str_path, sheet_name="Sheet1", index_col=0)
path_obj = Path("test1" + read_ext)
- actual = pd.read_excel(path_obj, "Sheet1", index_col=0)
+ actual = pd.read_excel(path_obj, sheet_name="Sheet1", index_col=0)
tm.assert_frame_equal(expected, actual)
@@ -641,10 +678,10 @@ def test_read_from_py_localpath(self, read_ext):
from py.path import local as LocalPath
str_path = os.path.join("test1" + read_ext)
- expected = pd.read_excel(str_path, "Sheet1", index_col=0)
+ expected = pd.read_excel(str_path, sheet_name="Sheet1", index_col=0)
path_obj = LocalPath().join("test1" + read_ext)
- actual = pd.read_excel(path_obj, "Sheet1", index_col=0)
+ actual = pd.read_excel(path_obj, sheet_name="Sheet1", index_col=0)
tm.assert_frame_equal(expected, actual)
@@ -654,7 +691,7 @@ def test_close_from_py_localpath(self, read_ext):
# GH31467
str_path = os.path.join("test1" + read_ext)
with open(str_path, "rb") as f:
- x = pd.read_excel(f, "Sheet1", index_col=0)
+ x = pd.read_excel(f, sheet_name="Sheet1", index_col=0)
del x
# should not throw an exception because the passed file was closed
f.read()
@@ -682,10 +719,10 @@ def test_reader_seconds(self, read_ext):
}
)
- actual = pd.read_excel("times_1900" + read_ext, "Sheet1")
+ actual = pd.read_excel("times_1900" + read_ext, sheet_name="Sheet1")
tm.assert_frame_equal(actual, expected)
- actual = pd.read_excel("times_1904" + read_ext, "Sheet1")
+ actual = pd.read_excel("times_1904" + read_ext, sheet_name="Sheet1")
tm.assert_frame_equal(actual, expected)
def test_read_excel_multiindex(self, read_ext):
@@ -707,52 +744,66 @@ def test_read_excel_multiindex(self, read_ext):
columns=mi,
)
- actual = pd.read_excel(mi_file, "mi_column", header=[0, 1], index_col=0)
+ actual = pd.read_excel(
+ mi_file, sheet_name="mi_column", header=[0, 1], index_col=0
+ )
tm.assert_frame_equal(actual, expected)
# "mi_index" sheet
expected.index = mi
expected.columns = ["a", "b", "c", "d"]
- actual = pd.read_excel(mi_file, "mi_index", index_col=[0, 1])
+ actual = pd.read_excel(mi_file, sheet_name="mi_index", index_col=[0, 1])
tm.assert_frame_equal(actual, expected, check_names=False)
# "both" sheet
expected.columns = mi
- actual = pd.read_excel(mi_file, "both", index_col=[0, 1], header=[0, 1])
+ actual = pd.read_excel(
+ mi_file, sheet_name="both", index_col=[0, 1], header=[0, 1]
+ )
tm.assert_frame_equal(actual, expected, check_names=False)
# "mi_index_name" sheet
expected.columns = ["a", "b", "c", "d"]
expected.index = mi.set_names(["ilvl1", "ilvl2"])
- actual = pd.read_excel(mi_file, "mi_index_name", index_col=[0, 1])
+ actual = pd.read_excel(mi_file, sheet_name="mi_index_name", index_col=[0, 1])
tm.assert_frame_equal(actual, expected)
# "mi_column_name" sheet
expected.index = list(range(4))
expected.columns = mi.set_names(["c1", "c2"])
- actual = pd.read_excel(mi_file, "mi_column_name", header=[0, 1], index_col=0)
+ actual = pd.read_excel(
+ mi_file, sheet_name="mi_column_name", header=[0, 1], index_col=0
+ )
tm.assert_frame_equal(actual, expected)
# see gh-11317
# "name_with_int" sheet
expected.columns = mi.set_levels([1, 2], level=1).set_names(["c1", "c2"])
- actual = pd.read_excel(mi_file, "name_with_int", index_col=0, header=[0, 1])
+ actual = pd.read_excel(
+ mi_file, sheet_name="name_with_int", index_col=0, header=[0, 1]
+ )
tm.assert_frame_equal(actual, expected)
# "both_name" sheet
expected.columns = mi.set_names(["c1", "c2"])
expected.index = mi.set_names(["ilvl1", "ilvl2"])
- actual = pd.read_excel(mi_file, "both_name", index_col=[0, 1], header=[0, 1])
+ actual = pd.read_excel(
+ mi_file, sheet_name="both_name", index_col=[0, 1], header=[0, 1]
+ )
tm.assert_frame_equal(actual, expected)
# "both_skiprows" sheet
actual = pd.read_excel(
- mi_file, "both_name_skiprows", index_col=[0, 1], header=[0, 1], skiprows=2
+ mi_file,
+ sheet_name="both_name_skiprows",
+ index_col=[0, 1],
+ header=[0, 1],
+ skiprows=2,
)
tm.assert_frame_equal(actual, expected)
@@ -761,7 +812,7 @@ def test_read_excel_multiindex_header_only(self, read_ext):
#
# Don't try to parse a header name if there isn't one.
mi_file = "testmultiindex" + read_ext
- result = pd.read_excel(mi_file, "index_col_none", header=[0, 1])
+ result = pd.read_excel(mi_file, sheet_name="index_col_none", header=[0, 1])
exp_columns = MultiIndex.from_product([("A", "B"), ("key", "val")])
expected = DataFrame([[1, 2, 3, 4]] * 2, columns=exp_columns)
@@ -799,12 +850,12 @@ def test_excel_old_index_format(self, read_ext):
expected = pd.DataFrame(data, index=si, columns=columns)
- actual = pd.read_excel(filename, "single_names", index_col=0)
+ actual = pd.read_excel(filename, sheet_name="single_names", index_col=0)
tm.assert_frame_equal(actual, expected)
expected.index = mi
- actual = pd.read_excel(filename, "multi_names", index_col=[0, 1])
+ actual = pd.read_excel(filename, sheet_name="multi_names", index_col=[0, 1])
tm.assert_frame_equal(actual, expected)
# The analogous versions of the "names" version data
@@ -831,12 +882,12 @@ def test_excel_old_index_format(self, read_ext):
expected = pd.DataFrame(data, index=si, columns=columns)
- actual = pd.read_excel(filename, "single_no_names", index_col=0)
+ actual = pd.read_excel(filename, sheet_name="single_no_names", index_col=0)
tm.assert_frame_equal(actual, expected)
expected.index = mi
- actual = pd.read_excel(filename, "multi_no_names", index_col=[0, 1])
+ actual = pd.read_excel(filename, sheet_name="multi_no_names", index_col=[0, 1])
tm.assert_frame_equal(actual, expected, check_names=False)
def test_read_excel_bool_header_arg(self, read_ext):
@@ -858,7 +909,7 @@ def test_read_excel_skiprows_list(self, read_ext):
pytest.xfail("Sheets containing datetimes not supported by pyxlsb")
actual = pd.read_excel(
- "testskiprows" + read_ext, "skiprows_list", skiprows=[0, 2]
+ "testskiprows" + read_ext, sheet_name="skiprows_list", skiprows=[0, 2]
)
expected = DataFrame(
[
@@ -872,7 +923,9 @@ def test_read_excel_skiprows_list(self, read_ext):
tm.assert_frame_equal(actual, expected)
actual = pd.read_excel(
- "testskiprows" + read_ext, "skiprows_list", skiprows=np.array([0, 2])
+ "testskiprows" + read_ext,
+ sheet_name="skiprows_list",
+ skiprows=np.array([0, 2]),
)
tm.assert_frame_equal(actual, expected)
@@ -902,19 +955,25 @@ def test_read_excel_squeeze(self, read_ext):
# GH 12157
f = "test_squeeze" + read_ext
- actual = pd.read_excel(f, "two_columns", index_col=0, squeeze=True)
+ actual = pd.read_excel(f, sheet_name="two_columns", index_col=0, squeeze=True)
expected = pd.Series([2, 3, 4], [4, 5, 6], name="b")
expected.index.name = "a"
tm.assert_series_equal(actual, expected)
- actual = pd.read_excel(f, "two_columns", squeeze=True)
+ actual = pd.read_excel(f, sheet_name="two_columns", squeeze=True)
expected = pd.DataFrame({"a": [4, 5, 6], "b": [2, 3, 4]})
tm.assert_frame_equal(actual, expected)
- actual = pd.read_excel(f, "one_column", squeeze=True)
+ actual = pd.read_excel(f, sheet_name="one_column", squeeze=True)
expected = pd.Series([1, 2, 3], name="a")
tm.assert_series_equal(actual, expected)
+ def test_deprecated_kwargs(self, read_ext):
+ with tm.assert_produces_warning(FutureWarning, raise_on_extra_warnings=False):
+ pd.read_excel("test1" + read_ext, "Sheet1", 0)
+
+ pd.read_excel("test1" + read_ext)
+
class TestExcelFileRead:
@pytest.fixture(autouse=True)
@@ -929,7 +988,7 @@ def cd_and_set_engine(self, engine, datapath, monkeypatch):
def test_excel_passes_na(self, read_ext):
with pd.ExcelFile("test4" + read_ext) as excel:
parsed = pd.read_excel(
- excel, "Sheet1", keep_default_na=False, na_values=["apple"]
+ excel, sheet_name="Sheet1", keep_default_na=False, na_values=["apple"]
)
expected = DataFrame(
[["NA"], [1], ["NA"], [np.nan], ["rabbit"]], columns=["Test"]
@@ -938,7 +997,7 @@ def test_excel_passes_na(self, read_ext):
with pd.ExcelFile("test4" + read_ext) as excel:
parsed = pd.read_excel(
- excel, "Sheet1", keep_default_na=True, na_values=["apple"]
+ excel, sheet_name="Sheet1", keep_default_na=True, na_values=["apple"]
)
expected = DataFrame(
[[np.nan], [1], [np.nan], [np.nan], ["rabbit"]], columns=["Test"]
@@ -948,7 +1007,7 @@ def test_excel_passes_na(self, read_ext):
# 13967
with pd.ExcelFile("test5" + read_ext) as excel:
parsed = pd.read_excel(
- excel, "Sheet1", keep_default_na=False, na_values=["apple"]
+ excel, sheet_name="Sheet1", keep_default_na=False, na_values=["apple"]
)
expected = DataFrame(
[["1.#QNAN"], [1], ["nan"], [np.nan], ["rabbit"]], columns=["Test"]
@@ -957,7 +1016,7 @@ def test_excel_passes_na(self, read_ext):
with pd.ExcelFile("test5" + read_ext) as excel:
parsed = pd.read_excel(
- excel, "Sheet1", keep_default_na=True, na_values=["apple"]
+ excel, sheet_name="Sheet1", keep_default_na=True, na_values=["apple"]
)
expected = DataFrame(
[[np.nan], [1], [np.nan], [np.nan], ["rabbit"]], columns=["Test"]
@@ -974,7 +1033,11 @@ def test_excel_passes_na_filter(self, read_ext, na_filter):
with pd.ExcelFile("test5" + read_ext) as excel:
parsed = pd.read_excel(
- excel, "Sheet1", keep_default_na=True, na_values=["apple"], **kwargs
+ excel,
+ sheet_name="Sheet1",
+ keep_default_na=True,
+ na_values=["apple"],
+ **kwargs,
)
if na_filter is False:
@@ -1003,8 +1066,8 @@ def test_excel_table_sheet_by_index(self, read_ext, df_ref):
pytest.xfail("Sheets containing datetimes not supported by pyxlsb")
with pd.ExcelFile("test1" + read_ext) as excel:
- df1 = pd.read_excel(excel, 0, index_col=0)
- df2 = pd.read_excel(excel, 1, skiprows=[1], index_col=0)
+ df1 = pd.read_excel(excel, sheet_name=0, index_col=0)
+ df2 = pd.read_excel(excel, sheet_name=1, skiprows=[1], index_col=0)
tm.assert_frame_equal(df1, df_ref, check_names=False)
tm.assert_frame_equal(df2, df_ref, check_names=False)
@@ -1015,7 +1078,7 @@ def test_excel_table_sheet_by_index(self, read_ext, df_ref):
tm.assert_frame_equal(df2, df_ref, check_names=False)
with pd.ExcelFile("test1" + read_ext) as excel:
- df3 = pd.read_excel(excel, 0, index_col=0, skipfooter=1)
+ df3 = pd.read_excel(excel, sheet_name=0, index_col=0, skipfooter=1)
tm.assert_frame_equal(df3, df1.iloc[:-1])
with pd.ExcelFile("test1" + read_ext) as excel:
@@ -1043,11 +1106,11 @@ def test_sheet_name(self, read_ext, df_ref):
def test_excel_read_buffer(self, engine, read_ext):
pth = "test1" + read_ext
- expected = pd.read_excel(pth, "Sheet1", index_col=0, engine=engine)
+ expected = pd.read_excel(pth, sheet_name="Sheet1", index_col=0, engine=engine)
with open(pth, "rb") as f:
with pd.ExcelFile(f) as xls:
- actual = pd.read_excel(xls, "Sheet1", index_col=0)
+ actual = pd.read_excel(xls, sheet_name="Sheet1", index_col=0)
tm.assert_frame_equal(expected, actual)
@@ -1055,7 +1118,7 @@ def test_reader_closes_file(self, engine, read_ext):
with open("test1" + read_ext, "rb") as f:
with pd.ExcelFile(f) as xlsx:
# parses okay
- pd.read_excel(xlsx, "Sheet1", index_col=0, engine=engine)
+ pd.read_excel(xlsx, sheet_name="Sheet1", index_col=0, engine=engine)
assert f.closed
diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py
index 1692e1a8a0dd3..65d22f2f943e5 100644
--- a/pandas/tests/io/excel/test_writers.py
+++ b/pandas/tests/io/excel/test_writers.py
@@ -64,7 +64,9 @@ def test_read_one_empty_col_no_header(self, ext, header, expected):
with tm.ensure_clean(ext) as path:
df.to_excel(path, filename, index=False, header=False)
- result = pd.read_excel(path, filename, usecols=[0], header=header)
+ result = pd.read_excel(
+ path, sheet_name=filename, usecols=[0], header=header
+ )
tm.assert_frame_equal(result, expected)
@@ -80,7 +82,9 @@ def test_read_one_empty_col_with_header(self, ext, header, expected):
with tm.ensure_clean(ext) as path:
df.to_excel(path, "with_header", index=False, header=True)
- result = pd.read_excel(path, filename, usecols=[0], header=header)
+ result = pd.read_excel(
+ path, sheet_name=filename, usecols=[0], header=header
+ )
tm.assert_frame_equal(result, expected)
@@ -100,10 +104,13 @@ def test_set_column_names_in_parameter(self, ext):
with ExcelFile(pth) as reader:
xlsdf_no_head = pd.read_excel(
- reader, "Data_no_head", header=None, names=["A", "B"]
+ reader, sheet_name="Data_no_head", header=None, names=["A", "B"]
)
xlsdf_with_head = pd.read_excel(
- reader, "Data_with_head", index_col=None, names=["A", "B"]
+ reader,
+ sheet_name="Data_with_head",
+ index_col=None,
+ names=["A", "B"],
)
tm.assert_frame_equal(xlsdf_no_head, refdf)
@@ -326,13 +333,13 @@ def test_excel_sheet_by_name_raise(self, path):
gt.to_excel(path)
xl = ExcelFile(path)
- df = pd.read_excel(xl, 0, index_col=0)
+ df = pd.read_excel(xl, sheet_name=0, index_col=0)
tm.assert_frame_equal(gt, df)
msg = "No sheet named <'0'>"
with pytest.raises(xlrd.XLRDError, match=msg):
- pd.read_excel(xl, "0")
+ pd.read_excel(xl, sheet_name="0")
def test_excel_writer_context_manager(self, frame, path):
with ExcelWriter(path) as writer:
@@ -342,8 +349,8 @@ def test_excel_writer_context_manager(self, frame, path):
frame2.to_excel(writer, "Data2")
with ExcelFile(path) as reader:
- found_df = pd.read_excel(reader, "Data1", index_col=0)
- found_df2 = pd.read_excel(reader, "Data2", index_col=0)
+ found_df = pd.read_excel(reader, sheet_name="Data1", index_col=0)
+ found_df2 = pd.read_excel(reader, sheet_name="Data2", index_col=0)
tm.assert_frame_equal(found_df, frame)
tm.assert_frame_equal(found_df2, frame2)
@@ -359,25 +366,27 @@ def test_roundtrip(self, frame, path):
# test roundtrip
frame.to_excel(path, "test1")
- recons = pd.read_excel(path, "test1", index_col=0)
+ recons = pd.read_excel(path, sheet_name="test1", index_col=0)
tm.assert_frame_equal(frame, recons)
frame.to_excel(path, "test1", index=False)
- recons = pd.read_excel(path, "test1", index_col=None)
+ recons = pd.read_excel(path, sheet_name="test1", index_col=None)
recons.index = frame.index
tm.assert_frame_equal(frame, recons)
frame.to_excel(path, "test1", na_rep="NA")
- recons = pd.read_excel(path, "test1", index_col=0, na_values=["NA"])
+ recons = pd.read_excel(path, sheet_name="test1", index_col=0, na_values=["NA"])
tm.assert_frame_equal(frame, recons)
# GH 3611
frame.to_excel(path, "test1", na_rep="88")
- recons = pd.read_excel(path, "test1", index_col=0, na_values=["88"])
+ recons = pd.read_excel(path, sheet_name="test1", index_col=0, na_values=["88"])
tm.assert_frame_equal(frame, recons)
frame.to_excel(path, "test1", na_rep="88")
- recons = pd.read_excel(path, "test1", index_col=0, na_values=[88, 88.0])
+ recons = pd.read_excel(
+ path, sheet_name="test1", index_col=0, na_values=[88, 88.0]
+ )
tm.assert_frame_equal(frame, recons)
# GH 6573
@@ -401,7 +410,7 @@ def test_mixed(self, frame, path):
mixed_frame.to_excel(path, "test1")
reader = ExcelFile(path)
- recons = pd.read_excel(reader, "test1", index_col=0)
+ 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):
@@ -414,7 +423,7 @@ def test_ts_frame(self, tsframe, path):
df.to_excel(path, "test1")
reader = ExcelFile(path)
- recons = pd.read_excel(reader, "test1", index_col=0)
+ 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):
@@ -433,17 +442,19 @@ def test_int_types(self, np_type, path):
df.to_excel(path, "test1")
reader = ExcelFile(path)
- recons = pd.read_excel(reader, "test1", index_col=0)
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
int_frame = df.astype(np.int64)
tm.assert_frame_equal(int_frame, recons)
- recons2 = pd.read_excel(path, "test1", index_col=0)
+ recons2 = pd.read_excel(path, sheet_name="test1", index_col=0)
tm.assert_frame_equal(int_frame, recons2)
# Test with convert_float=False comes back as float.
float_frame = df.astype(float)
- recons = pd.read_excel(path, "test1", convert_float=False, index_col=0)
+ recons = pd.read_excel(
+ path, sheet_name="test1", convert_float=False, index_col=0
+ )
tm.assert_frame_equal(
recons, float_frame, check_index_type=False, check_column_type=False
)
@@ -455,7 +466,7 @@ def test_float_types(self, np_type, path):
df.to_excel(path, "test1")
reader = ExcelFile(path)
- recons = pd.read_excel(reader, "test1", index_col=0).astype(np_type)
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(np_type)
tm.assert_frame_equal(df, recons)
@@ -466,7 +477,7 @@ def test_bool_types(self, np_type, path):
df.to_excel(path, "test1")
reader = ExcelFile(path)
- recons = pd.read_excel(reader, "test1", index_col=0).astype(np_type)
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0).astype(np_type)
tm.assert_frame_equal(df, recons)
@@ -475,7 +486,7 @@ def test_inf_roundtrip(self, path):
df.to_excel(path, "test1")
reader = ExcelFile(path)
- recons = pd.read_excel(reader, "test1", index_col=0)
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
tm.assert_frame_equal(df, recons)
@@ -499,9 +510,9 @@ def test_sheets(self, frame, tsframe, path):
tsframe.to_excel(writer, "test2")
writer.save()
reader = ExcelFile(path)
- recons = pd.read_excel(reader, "test1", index_col=0)
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
tm.assert_frame_equal(frame, recons)
- recons = pd.read_excel(reader, "test2", index_col=0)
+ 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]
@@ -520,7 +531,7 @@ def test_colaliases(self, frame, path):
col_aliases = Index(["AA", "X", "Y", "Z"])
frame.to_excel(path, "test1", header=col_aliases)
reader = ExcelFile(path)
- rs = pd.read_excel(reader, "test1", index_col=0)
+ rs = pd.read_excel(reader, sheet_name="test1", index_col=0)
xp = frame.copy()
xp.columns = col_aliases
tm.assert_frame_equal(xp, rs)
@@ -538,7 +549,7 @@ def test_roundtrip_indexlabels(self, merge_cells, frame, path):
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, "test1", index_col=0).astype(np.int64)
+ 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
@@ -550,14 +561,14 @@ def test_roundtrip_indexlabels(self, merge_cells, frame, path):
merge_cells=merge_cells,
)
reader = ExcelFile(path)
- recons = pd.read_excel(reader, "test1", index_col=0).astype(np.int64)
+ 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, "test1", index_col=0).astype(np.int64)
+ 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))
@@ -573,7 +584,7 @@ def test_roundtrip_indexlabels(self, merge_cells, frame, path):
df = df.set_index(["A", "B"])
reader = ExcelFile(path)
- recons = pd.read_excel(reader, "test1", index_col=[0, 1])
+ 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):
@@ -583,7 +594,7 @@ 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, xf.sheet_names[0], index_col=0)
+ 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"
@@ -601,7 +612,7 @@ def test_excel_roundtrip_datetime(self, merge_cells, tsframe, path):
tsf.to_excel(path, "test1", merge_cells=merge_cells)
reader = ExcelFile(path)
- recons = pd.read_excel(reader, "test1", index_col=0)
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
tm.assert_frame_equal(tsframe, recons)
@@ -643,8 +654,8 @@ def test_excel_date_datetime_format(self, engine, ext, path):
reader1 = ExcelFile(path)
reader2 = ExcelFile(filename2)
- rs1 = pd.read_excel(reader1, "test1", index_col=0)
- rs2 = pd.read_excel(reader2, "test1", index_col=0)
+ rs1 = pd.read_excel(reader1, sheet_name="test1", index_col=0)
+ rs2 = pd.read_excel(reader2, sheet_name="test1", index_col=0)
tm.assert_frame_equal(rs1, rs2)
@@ -665,7 +676,7 @@ def test_to_excel_interval_no_labels(self, path):
df.to_excel(path, "test1")
reader = ExcelFile(path)
- recons = pd.read_excel(reader, "test1", index_col=0)
+ 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):
@@ -683,7 +694,7 @@ def test_to_excel_interval_labels(self, path):
df.to_excel(path, "test1")
reader = ExcelFile(path)
- recons = pd.read_excel(reader, "test1", index_col=0)
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=0)
tm.assert_frame_equal(expected, recons)
def test_to_excel_timedelta(self, path):
@@ -703,7 +714,7 @@ def test_to_excel_timedelta(self, path):
df.to_excel(path, "test1")
reader = ExcelFile(path)
- recons = pd.read_excel(reader, "test1", index_col=0)
+ 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):
@@ -712,7 +723,7 @@ def test_to_excel_periodindex(self, tsframe, path):
xp.to_excel(path, "sht1")
reader = ExcelFile(path)
- rs = pd.read_excel(reader, "sht1", index_col=0)
+ 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):
@@ -726,7 +737,7 @@ 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, "test1", index_col=[0, 1])
+ df = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1])
tm.assert_frame_equal(frame, df)
# GH13511
@@ -757,7 +768,7 @@ 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, "test1", header=header, index_col=[0, 1])
+ 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)]
@@ -771,7 +782,7 @@ 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, "test1", index_col=[0, 1])
+ recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1])
tm.assert_frame_equal(tsframe, recons)
assert recons.index.names == ("time", "foo")
@@ -792,7 +803,7 @@ def test_to_excel_multiindex_no_write_index(self, path):
# Read it back in.
reader = ExcelFile(path)
- frame3 = pd.read_excel(reader, "test1")
+ frame3 = pd.read_excel(reader, sheet_name="test1")
# Test that it is the same as the initial frame.
tm.assert_frame_equal(frame1, frame3)
@@ -806,7 +817,7 @@ def test_to_excel_float_format(self, path):
df.to_excel(path, "test1", float_format="%.2f")
reader = ExcelFile(path)
- result = pd.read_excel(reader, "test1", index_col=0)
+ 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]],
@@ -825,7 +836,9 @@ def test_to_excel_output_encoding(self, ext):
with tm.ensure_clean("__tmp_to_excel_float_format__." + ext) as filename:
df.to_excel(filename, sheet_name="TestSheet", encoding="utf8")
- result = pd.read_excel(filename, "TestSheet", encoding="utf8", index_col=0)
+ result = pd.read_excel(
+ filename, sheet_name="TestSheet", encoding="utf8", index_col=0
+ )
tm.assert_frame_equal(result, df)
def test_to_excel_unicode_filename(self, ext, path):
@@ -845,7 +858,7 @@ def test_to_excel_unicode_filename(self, ext, path):
df.to_excel(filename, "test1", float_format="%.2f")
reader = ExcelFile(filename)
- result = pd.read_excel(reader, "test1", index_col=0)
+ 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]],
@@ -965,7 +978,7 @@ 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, xf.sheet_names[0], header=parser_hdr)
+ return pd.read_excel(xf, sheet_name=xf.sheet_names[0], header=parser_hdr)
# Basic test.
parser_header = 0 if use_headers else None
@@ -1017,18 +1030,20 @@ def test_duplicated_columns(self, path):
)
# By default, we mangle.
- result = pd.read_excel(path, "test1", index_col=0)
+ result = pd.read_excel(path, sheet_name="test1", index_col=0)
tm.assert_frame_equal(result, expected)
# Explicitly, we pass in the parameter.
- result = pd.read_excel(path, "test1", index_col=0, mangle_dupe_cols=True)
+ result = pd.read_excel(
+ path, sheet_name="test1", index_col=0, mangle_dupe_cols=True
+ )
tm.assert_frame_equal(result, expected)
# see gh-11007, gh-10970
df = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "A", "B"])
df.to_excel(path, "test1")
- result = pd.read_excel(path, "test1", index_col=0)
+ result = pd.read_excel(path, sheet_name="test1", index_col=0)
expected = DataFrame(
[[1, 2, 3, 4], [5, 6, 7, 8]], columns=["A", "B", "A.1", "B.1"]
)
@@ -1036,21 +1051,21 @@ def test_duplicated_columns(self, path):
# see gh-10982
df.to_excel(path, "test1", index=False, header=False)
- result = pd.read_excel(path, "test1", header=None)
+ result = pd.read_excel(path, sheet_name="test1", header=None)
expected = DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]])
tm.assert_frame_equal(result, expected)
msg = "Setting mangle_dupe_cols=False is not supported yet"
with pytest.raises(ValueError, match=msg):
- pd.read_excel(path, "test1", header=None, mangle_dupe_cols=False)
+ pd.read_excel(path, sheet_name="test1", header=None, mangle_dupe_cols=False)
def test_swapped_columns(self, path):
# Test for issue #5427.
write_frame = DataFrame({"A": [1, 1, 1], "B": [2, 2, 2]})
write_frame.to_excel(path, "test1", columns=["B", "A"])
- read_frame = pd.read_excel(path, "test1", header=0)
+ read_frame = pd.read_excel(path, sheet_name="test1", header=0)
tm.assert_series_equal(write_frame["A"], read_frame["A"])
tm.assert_series_equal(write_frame["B"], read_frame["B"])
@@ -1083,7 +1098,7 @@ def test_write_subset_columns(self, path, to_excel_index, read_excel_index_col):
expected = write_frame[["A", "B"]]
read_frame = pd.read_excel(
- path, "col_subset_bug", index_col=read_excel_index_col
+ path, sheet_name="col_subset_bug", index_col=read_excel_index_col
)
tm.assert_frame_equal(expected, read_frame)
@@ -1098,13 +1113,13 @@ def test_comment_arg(self, path):
df.to_excel(path, "test_c")
# Read file without comment arg.
- result1 = pd.read_excel(path, "test_c", index_col=0)
+ result1 = pd.read_excel(path, sheet_name="test_c", index_col=0)
result1.iloc[1, 0] = None
result1.iloc[1, 1] = None
result1.iloc[2, 1] = None
- result2 = pd.read_excel(path, "test_c", comment="#", index_col=0)
+ result2 = pd.read_excel(path, sheet_name="test_c", comment="#", index_col=0)
tm.assert_frame_equal(result1, result2)
def test_comment_default(self, path):
@@ -1116,8 +1131,8 @@ def test_comment_default(self, path):
df.to_excel(path, "test_c")
# Read file with default and explicit comment=None
- result1 = pd.read_excel(path, "test_c")
- result2 = pd.read_excel(path, "test_c", comment=None)
+ result1 = pd.read_excel(path, sheet_name="test_c")
+ result2 = pd.read_excel(path, sheet_name="test_c", comment=None)
tm.assert_frame_equal(result1, result2)
def test_comment_used(self, path):
@@ -1131,7 +1146,7 @@ def test_comment_used(self, path):
# Test read_frame_comment against manually produced expected output.
expected = DataFrame({"A": ["one", None, "one"], "B": ["two", None, None]})
- result = pd.read_excel(path, "test_c", comment="#", index_col=0)
+ result = pd.read_excel(path, sheet_name="test_c", comment="#", index_col=0)
tm.assert_frame_equal(result, expected)
def test_comment_empty_line(self, path):
@@ -1165,7 +1180,7 @@ def test_datetimes(self, path):
write_frame = DataFrame({"A": datetimes})
write_frame.to_excel(path, "Sheet1")
- read_frame = pd.read_excel(path, "Sheet1", header=0)
+ read_frame = pd.read_excel(path, sheet_name="Sheet1", header=0)
tm.assert_series_equal(write_frame["A"], read_frame["A"])
@@ -1193,7 +1208,7 @@ def test_write_lists_dict(self, path):
}
)
df.to_excel(path, "Sheet1")
- read = pd.read_excel(path, "Sheet1", header=0, index_col=0)
+ read = pd.read_excel(path, sheet_name="Sheet1", header=0, index_col=0)
expected = df.copy()
expected.mixed = expected.mixed.apply(str)
diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py
index d456afe4ed351..1c9c514b20f46 100644
--- a/pandas/tests/io/excel/test_xlrd.py
+++ b/pandas/tests/io/excel/test_xlrd.py
@@ -28,7 +28,7 @@ def test_read_xlrd_book(read_ext, frame):
book = xlrd.open_workbook(pth)
with ExcelFile(book, engine=engine) as xl:
- result = pd.read_excel(xl, sheet_name, index_col=0)
+ result = pd.read_excel(xl, sheet_name=sheet_name, index_col=0)
tm.assert_frame_equal(df, result)
result = pd.read_excel(book, sheet_name=sheet_name, engine=engine, index_col=0)
@@ -40,4 +40,4 @@ def test_excel_table_sheet_by_index(datapath, read_ext):
path = datapath("io", "data", "excel", f"test1{read_ext}")
with pd.ExcelFile(path) as excel:
with pytest.raises(xlrd.XLRDError):
- pd.read_excel(excel, "asdf")
+ pd.read_excel(excel, sheet_name="asdf")
| Follow-up to #27573.
Allows two non-keyword arguments, ``io`` and ``sheet_name``. I think ``sheet_name`` is quite often (e.g. Interactively) supplied without being a keyword argument and requiring it will just be needlessly annoying.
Also some clean-up in pandas/tests/io/excel. | https://api.github.com/repos/pandas-dev/pandas/pulls/34418 | 2020-05-27T23:15:39Z | 2020-05-29T01:00:45Z | 2020-05-29T01:00:44Z | 2020-05-29T06:12:00Z |
TST closes #28980 Certain comparison operations misbehaving for period dtype | diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py
index 9fc6568a019b6..d206622521816 100644
--- a/pandas/tests/arithmetic/test_period.py
+++ b/pandas/tests/arithmetic/test_period.py
@@ -1522,3 +1522,11 @@ def test_pi_sub_period_nat(self):
exp = pd.TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name="idx")
tm.assert_index_equal(idx - pd.Period("NaT", freq="M"), exp)
tm.assert_index_equal(pd.Period("NaT", freq="M") - idx, exp)
+
+ @pytest.mark.parametrize("scalars", ["a", False, 1, 1.0, None])
+ def test_comparison_operations(self, scalars):
+ # GH 28980
+ expected = Series([False, False])
+ s = Series([pd.Period("2019"), pd.Period("2020")], dtype="period[A-DEC]")
+ result = s == scalars
+ tm.assert_series_equal(result, expected)
| I've added test to compare `pd.Series([...], dtype="period[A-DEC]")` to dtype `str`, `bool`, `int`, `float` and `None`.
- [ x ] closes #28980
- [ 5 ] 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/34417 | 2020-05-27T20:54:29Z | 2020-05-28T17:17:44Z | 2020-05-28T17:17:44Z | 2020-06-11T17:30:42Z |
Macpython 32 bit build fixup | diff --git a/pandas/_libs/hashtable_func_helper.pxi.in b/pandas/_libs/hashtable_func_helper.pxi.in
index c63f368dfae43..326ae36c6a12c 100644
--- a/pandas/_libs/hashtable_func_helper.pxi.in
+++ b/pandas/_libs/hashtable_func_helper.pxi.in
@@ -84,7 +84,8 @@ cpdef value_count_{{dtype}}({{c_type}}[:] values, bint dropna):
int64_t[:] result_counts
{{endif}}
- Py_ssize_t k
+ # Don't use Py_ssize_t, since table.n_buckets is unsigned
+ khiter_t k
table = kh_init_{{ttype}}()
{{if dtype == 'object'}}
@@ -132,7 +133,8 @@ def duplicated_{{dtype}}(const {{c_type}}[:] values, object keep='first'):
{{if dtype != 'object'}}
{{dtype}}_t value
{{endif}}
- Py_ssize_t k, i, n = len(values)
+ Py_ssize_t i, n = len(values)
+ khiter_t k
kh_{{ttype}}_t *table = kh_init_{{ttype}}()
ndarray[uint8_t, ndim=1, cast=True] out = np.empty(n, dtype='bool')
@@ -222,7 +224,8 @@ def ismember_{{dtype}}(const {{c_type}}[:] arr, {{c_type}}[:] values):
boolean ndarry len of (arr)
"""
cdef:
- Py_ssize_t i, n, k
+ Py_ssize_t i, n
+ khiter_t k
int ret = 0
ndarray[uint8_t] result
{{c_type}} val
@@ -295,7 +298,8 @@ def mode_{{dtype}}({{ctype}}[:] values, bint dropna):
cdef:
int count, max_count = 1
int j = -1 # so you can do +=
- Py_ssize_t k
+ # Don't use Py_ssize_t, since table.n_buckets is unsigned
+ khiter_t k
kh_{{table_type}}_t *table
ndarray[{{ctype}}] modes
diff --git a/pandas/_libs/src/parser/tokenizer.c b/pandas/_libs/src/parser/tokenizer.c
index 7ba1a6cd398c9..a195c0daf5271 100644
--- a/pandas/_libs/src/parser/tokenizer.c
+++ b/pandas/_libs/src/parser/tokenizer.c
@@ -709,7 +709,7 @@ int skip_this_line(parser_t *self, int64_t rownum) {
}
int tokenize_bytes(parser_t *self,
- size_t line_limit, int64_t start_lines) {
+ size_t line_limit, uint64_t start_lines) {
int64_t i;
uint64_t slen;
int should_skip;
@@ -1348,7 +1348,7 @@ int parser_trim_buffers(parser_t *self) {
int _tokenize_helper(parser_t *self, size_t nrows, int all) {
int status = 0;
- int64_t start_lines = self->lines;
+ uint64_t start_lines = self->lines;
if (self->state == FINISHED) {
return 0;
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx
index 9757c4d36d5fa..aadf2c41f7941 100644
--- a/pandas/_libs/tslibs/period.pyx
+++ b/pandas/_libs/tslibs/period.pyx
@@ -76,7 +76,7 @@ from pandas._libs.tslibs.tzconversion cimport tz_convert_utc_to_tzlocal
cdef:
enum:
- INT32_MIN = -2_147_483_648
+ INT32_MIN = -2_147_483_648LL
ctypedef struct asfreq_info:
@@ -108,9 +108,11 @@ cdef extern from *:
#define FR_UND -10000 /* Undefined */
// must use npy typedef b/c int64_t is aliased in cython-generated c
+ // unclear why we need LL for that row.
+ // see https://github.com/pandas-dev/pandas/pull/34416/
static npy_int64 daytime_conversion_factor_matrix[7][7] = {
{1, 24, 1440, 86400, 86400000, 86400000000, 86400000000000},
- {0, 1, 60, 3600, 3600000, 3600000000, 3600000000000},
+ {0LL, 1LL, 60LL, 3600LL, 3600000LL, 3600000000LL, 3600000000000LL},
{0, 0, 1, 60, 60000, 60000000, 60000000000},
{0, 0, 0, 1, 1000, 1000000, 1000000000},
{0, 0, 0, 0, 1, 1000, 1000000},
| Closes #34114
cc @jbrockmendel and @WillAyd. I have no idea if this is correct, but it builds. | https://api.github.com/repos/pandas-dev/pandas/pulls/34416 | 2020-05-27T20:00:26Z | 2020-05-29T19:05:41Z | 2020-05-29T19:05:40Z | 2020-05-29T19:05:45Z |
BUG: merge between partial index and index fails when result is empty | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 9d1b3eaebdf8b..968db9de97093 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -293,6 +293,7 @@ Groupby/resample/rolling
Reshaping
^^^^^^^^^
+- Bug in :func:`merge` raising error when performing an inner join with partial index and ``right_index`` when no overlap between indices (:issue:`33814`)
- Bug in :meth:`DataFrame.unstack` with missing levels led to incorrect index names (:issue:`37510`)
- Bug in :func:`concat` incorrectly casting to ``object`` dtype in some cases when one or more of the operands is empty (:issue:`38843`)
-
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 1354e72cadc5a..ac5fc7cddf82a 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -864,9 +864,9 @@ def _maybe_add_join_keys(self, result, left_indexer, right_indexer):
mask_left = left_indexer == -1
mask_right = right_indexer == -1
if mask_left.all():
- key_col = rvals
+ key_col = Index(rvals)
elif right_indexer is not None and mask_right.all():
- key_col = lvals
+ key_col = Index(lvals)
else:
key_col = Index(lvals).where(~mask_left, rvals)
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index d430856776269..da3ac81c4aa17 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -2375,3 +2375,15 @@ def test_merge_right_left_index():
}
)
tm.assert_frame_equal(result, expected)
+
+
+def test_merge_result_empty_index_and_on():
+ # GH#33814
+ df1 = DataFrame({"a": [1], "b": [2]}).set_index(["a", "b"])
+ df2 = DataFrame({"b": [1]}).set_index(["b"])
+ expected = DataFrame({"a": [], "b": []}, dtype=np.int64).set_index(["a", "b"])
+ result = merge(df1, df2, left_on=["b"], right_index=True)
+ tm.assert_frame_equal(result, expected)
+
+ result = merge(df2, df1, left_index=True, right_on=["b"])
+ tm.assert_frame_equal(result, expected)
| - [x] closes #33814
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
The Issue was caused when setting the name of an numpy array. | https://api.github.com/repos/pandas-dev/pandas/pulls/34414 | 2020-05-27T18:35:11Z | 2021-01-03T23:21:42Z | 2021-01-03T23:21:41Z | 2021-01-03T23:23:12Z |
Initialize variables in pqyear, pquarter | diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx
index cc6c4d06ae562..fa8c0414aa8d0 100644
--- a/pandas/_libs/tslibs/period.pyx
+++ b/pandas/_libs/tslibs/period.pyx
@@ -1281,14 +1281,16 @@ cdef int pyear(int64_t ordinal, int freq):
@cython.cdivision
cdef int pqyear(int64_t ordinal, int freq):
cdef:
- int year, quarter
+ int year = 0
+ int quarter = 0
get_yq(ordinal, freq, &quarter, &year)
return year
cdef int pquarter(int64_t ordinal, int freq):
cdef:
- int year, quarter
+ int year = 0
+ int quarter = 0
get_yq(ordinal, freq, &quarter, &year)
return quarter
| This resolves the `-Wmaybe-uninitialized` warning observed when building with the manylinux1 docker image
```
gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -DNPY_NO_DEPRECATED_API=0 -Ipandas/_libs/tslibs -I./pandas/_libs/tslibs -I/opt/python/cp38-cp38/lib/python3.8/site-packages/numpy/core/include -I/opt/python/cp38-cp38/include/python3.8 -c pandas/_libs/tslibs/period.c -o build/temp.linux-x86_64-3.8/pandas/_libs/tslibs/period.o
pandas/_libs/tslibs/period.c: In function ‘__pyx_f_6pandas_5_libs_6tslibs_6period_pqyear’:
pandas/_libs/tslibs/period.c:12464:3: warning: ‘__pyx_v_year’ may be used uninitialized in this function [-Wmaybe-uninitialized]
return __pyx_r;
^
pandas/_libs/tslibs/period.c: In function ‘__pyx_f_6pandas_5_libs_6tslibs_6period_pquarter’:
pandas/_libs/tslibs/period.c:12512:3: warning: ‘__pyx_v_quarter’ may be used uninitialized in this function [-Wmaybe-uninitialized]
return __pyx_r;
```
Hopefully this doesn't break anything. IIUC, these pointers are just used to set the result, so it shouldn't matter what the value is going in?
Closes https://github.com/pandas-dev/pandas/issues/34114
| https://api.github.com/repos/pandas-dev/pandas/pulls/34409 | 2020-05-27T15:38:05Z | 2020-05-27T16:25:05Z | 2020-05-27T16:25:05Z | 2020-05-27T16:30:08Z |
DOC: add link to benchmarks page in developer docs | diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst
index d02896f777348..457aabcff0c17 100644
--- a/doc/source/development/contributing.rst
+++ b/doc/source/development/contributing.rst
@@ -1275,8 +1275,8 @@ Performance matters and it is worth considering whether your code has introduced
performance regressions. pandas is in the process of migrating to
`asv benchmarks <https://github.com/spacetelescope/asv>`__
to enable easy monitoring of the performance of critical pandas operations.
-These benchmarks are all found in the ``pandas/asv_bench`` directory. asv
-supports both python2 and python3.
+These benchmarks are all found in the ``pandas/asv_bench`` directory, and the
+test results can be found `here <https://pandas.pydata.org/speed/pandas/#/>`__.
To use all features of asv, you will need either ``conda`` or
``virtualenv``. For more details please check the `asv installation
| - [x] closes #34405
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew
@jreback
| https://api.github.com/repos/pandas-dev/pandas/pulls/34408 | 2020-05-27T15:33:41Z | 2020-05-27T23:12:06Z | 2020-05-27T23:12:06Z | 2020-05-27T23:12:11Z |
REGR: revert "CLN: _consolidate_inplace less" / fix regression in fillna() | diff --git a/doc/source/whatsnew/v1.1.5.rst b/doc/source/whatsnew/v1.1.5.rst
index a8bbf692a72e5..29b0e99a3a356 100644
--- a/doc/source/whatsnew/v1.1.5.rst
+++ b/doc/source/whatsnew/v1.1.5.rst
@@ -21,6 +21,7 @@ Fixed regressions
- Fixed regression in metadata propagation for ``groupby`` iterator (:issue:`37343`)
- Fixed regression in indexing on a :class:`Series` with ``CategoricalDtype`` after unpickling (:issue:`37631`)
- Fixed regression in ``df.groupby(..).rolling(..)`` with the resulting :class:`MultiIndex` when grouping by a label that is in the index (:issue:`37641`)
+- Fixed regression in :meth:`DataFrame.fillna` not filling ``NaN`` after other operations such as :meth:`DataFrame.pivot` (:issue:`36495`).
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index e866314f00639..d6a2480cf688d 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -3709,6 +3709,8 @@ class animal locomotion
else:
index = self.index
+ self._consolidate_inplace()
+
if isinstance(index, MultiIndex):
try:
loc, new_index = index._get_loc_level(
@@ -6327,6 +6329,8 @@ def fillna(
inplace = validate_bool_kwarg(inplace, "inplace")
value, method = validate_fillna_kwargs(value, method)
+ self._consolidate_inplace()
+
# set the default here, so functions examining the signaure
# can detect if something was set (e.g. in groupby) (GH9221)
if axis is None:
@@ -6749,6 +6753,8 @@ def replace(
if not is_bool(regex) and to_replace is not None:
raise ValueError("'to_replace' must be 'None' if 'regex' is not a bool")
+ self._consolidate_inplace()
+
if value is None:
# passing a single value that is scalar like
# when value is None (GH5319), for compat
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 760765e3a20e6..b13368ca5af18 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -442,6 +442,7 @@ def apply(
def quantile(
self,
axis: int = 0,
+ consolidate: bool = True,
transposed: bool = False,
interpolation="linear",
qs=None,
@@ -455,6 +456,8 @@ def quantile(
Parameters
----------
axis: reduction axis, default 0
+ consolidate: bool, default True. Join together blocks having same
+ dtype
transposed: bool, default False
we are holding transposed data
interpolation : type of interpolation, default 'linear'
@@ -469,6 +472,9 @@ def quantile(
# simplify some of the code here and in the blocks
assert self.ndim >= 2
+ if consolidate:
+ self._consolidate_inplace()
+
def get_axe(block, qs, axes):
# Because Series dispatches to DataFrame, we will always have
# block.ndim == 2
diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py
index bbb57da39705b..d59b70fa91a57 100644
--- a/pandas/tests/frame/methods/test_fillna.py
+++ b/pandas/tests/frame/methods/test_fillna.py
@@ -524,3 +524,18 @@ def test_fill_corner(self, float_frame, float_string_frame):
# TODO(wesm): unused?
result = empty_float.fillna(value=0) # noqa
+
+
+def test_fillna_nonconsolidated_frame():
+ # https://github.com/pandas-dev/pandas/issues/36495
+ df = DataFrame(
+ [
+ [1, 1, 1, 1.0],
+ [2, 2, 2, 2.0],
+ [3, 3, 3, 3.0],
+ ],
+ columns=["i1", "i2", "i3", "f1"],
+ )
+ df_nonconsol = df.pivot("i1", "i2")
+ result = df_nonconsol.fillna(0)
+ assert result.isna().sum().sum() == 0
| Reverts pandas-dev/pandas#34389
Closes #36495 | https://api.github.com/repos/pandas-dev/pandas/pulls/34407 | 2020-05-27T14:09:47Z | 2020-11-26T17:00:20Z | 2020-11-26T17:00:20Z | 2020-11-28T19:55:32Z |
BUG/API: other object type check in Series/DataFrame.equals | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 814dbe999d5c1..43b117a2bc35f 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -1162,6 +1162,8 @@ Other
- Bug in :meth:`DataFrame.__dir__` caused a segfault when using unicode surrogates in a column name (:issue:`25509`)
- Bug in :meth:`DataFrame.plot.scatter` caused an error when plotting variable marker sizes (:issue:`32904`)
- :class:`IntegerArray` now implements the ``sum`` operation (:issue:`33172`)
+- Bug in :meth:`DataFrame.equals` and :meth:`Series.equals` in allowing subclasses
+ to be equal (:issue:`34402`).
- Bug in :class:`Tick` comparisons raising ``TypeError`` when comparing against timedelta-like objects (:issue:`34088`)
- Bug in :class:`Tick` multiplication raising ``TypeError`` when multiplying by a float (:issue:`34486`)
- Passing a `set` as `names` argument to :func:`pandas.read_csv`, :func:`pandas.read_table`, or :func:`pandas.read_fwf` will raise ``ValueError: Names should be an ordered collection.`` (:issue:`34946`)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index eb55369d83593..e46fde1f59f16 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1278,7 +1278,7 @@ def equals(self, other):
>>> df.equals(different_data_type)
False
"""
- if not isinstance(other, self._constructor):
+ if not (isinstance(other, type(self)) or isinstance(self, type(other))):
return False
return self._mgr.equals(other._mgr)
diff --git a/pandas/tests/frame/test_subclass.py b/pandas/tests/frame/test_subclass.py
index 08920cf7fceeb..2b462d5a10c51 100644
--- a/pandas/tests/frame/test_subclass.py
+++ b/pandas/tests/frame/test_subclass.py
@@ -696,3 +696,11 @@ def test_idxmax_preserves_subclass(self):
df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]})
result = df.idxmax()
assert isinstance(result, tm.SubclassedSeries)
+
+ def test_equals_subclass(self):
+ # https://github.com/pandas-dev/pandas/pull/34402
+ # allow subclass in both directions
+ df1 = pd.DataFrame({"a": [1, 2, 3]})
+ df2 = tm.SubclassedDataFrame({"a": [1, 2, 3]})
+ assert df1.equals(df2)
+ assert df2.equals(df1)
diff --git a/pandas/tests/series/test_subclass.py b/pandas/tests/series/test_subclass.py
index a596ed49c1df2..86330b7cc6993 100644
--- a/pandas/tests/series/test_subclass.py
+++ b/pandas/tests/series/test_subclass.py
@@ -51,3 +51,11 @@ def test_explode(self):
s = tm.SubclassedSeries([[1, 2, 3], "foo", [], [3, 4]])
result = s.explode()
assert isinstance(result, tm.SubclassedSeries)
+
+ def test_equals(self):
+ # https://github.com/pandas-dev/pandas/pull/34402
+ # allow subclass in both directions
+ s1 = pd.Series([1, 2, 3])
+ s2 = tm.SubclassedSeries([1, 2, 3])
+ assert s1.equals(s2)
+ assert s2.equals(s1)
| xref https://github.com/geopandas/geopandas/issues/1420
First, this PR is fixing the "bug" that we shouldn't rely on `_constructor` being a class that can be used in `isinstance` (see https://github.com/pandas-dev/pandas/issues/32638 for the general discussion about this, this is the only place in our code where `_constructor` is used like this, AFAIK).
And even if `_constructor` would be a class, it wouldn't necessarily be the correct class to check with (or not more correct than `type(self)`)
But, so this also brings up the API question: what are the "requirements" we put on the type of `other` ? Should it be the same type? (as then could also change it to `if not type(self) is type(other): ...`)
Or is a subclass sufficient (with `isinstance`) ?
The problem with an isinstance checks with subclasses is that then the order matters (eg `subdf.equals(df)` would not necessarily give the same answer as `df.equals(subdf)`)
| https://api.github.com/repos/pandas-dev/pandas/pulls/34402 | 2020-05-27T07:56:20Z | 2020-07-15T22:25:23Z | 2020-07-15T22:25:23Z | 2020-07-15T22:25:27Z |
CI: Remove unused import in offsets.py | diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py
index c5de4533955ff..fd304dc2425a3 100644
--- a/pandas/tseries/offsets.py
+++ b/pandas/tseries/offsets.py
@@ -1,5 +1,4 @@
from datetime import datetime, timedelta
-import operator
import numpy as np
| https://api.github.com/repos/pandas-dev/pandas/pulls/34401 | 2020-05-27T03:00:13Z | 2020-05-27T03:28:58Z | 2020-05-27T03:28:58Z | 2020-05-27T03:29:18Z | |
CLN: de-duplicate paths in tslibs | diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx
index bf895f155fc59..3a1af9fdb1e8f 100644
--- a/pandas/_libs/tslibs/parsing.pyx
+++ b/pandas/_libs/tslibs/parsing.pyx
@@ -376,7 +376,7 @@ cpdef bint _does_string_look_like_datetime(str py_string):
return True
-cdef inline object _parse_dateabbr_string(object date_string, object default,
+cdef inline object _parse_dateabbr_string(object date_string, datetime default,
object freq):
cdef:
object ret
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx
index cc6c4d06ae562..b5488e3d6d5a3 100644
--- a/pandas/_libs/tslibs/period.pyx
+++ b/pandas/_libs/tslibs/period.pyx
@@ -955,35 +955,6 @@ cdef inline int month_to_quarter(int month) nogil:
# ----------------------------------------------------------------------
# Period logic
-@cython.wraparound(False)
-@cython.boundscheck(False)
-def dt64arr_to_periodarr(const int64_t[:] dtarr, int freq, tz=None):
- """
- Convert array of datetime64 values (passed in as 'i8' dtype) to a set of
- periods corresponding to desired frequency, per period convention.
- """
- cdef:
- int64_t[:] out
- Py_ssize_t i, l
- npy_datetimestruct dts
-
- l = len(dtarr)
-
- out = np.empty(l, dtype='i8')
-
- if tz is None:
- with nogil:
- for i in range(l):
- if dtarr[i] == NPY_NAT:
- out[i] = NPY_NAT
- continue
- dt64_to_dtstruct(dtarr[i], &dts)
- out[i] = get_period_ordinal(&dts, freq)
- else:
- out = localize_dt64arr_to_period(dtarr, freq, tz)
- return out.base # .base to access underlying np.ndarray
-
-
@cython.wraparound(False)
@cython.boundscheck(False)
def periodarr_to_dt64arr(const int64_t[:] periodarr, int freq):
@@ -1471,8 +1442,7 @@ def extract_freq(ndarray[object] values):
@cython.wraparound(False)
@cython.boundscheck(False)
-cdef int64_t[:] localize_dt64arr_to_period(const int64_t[:] stamps,
- int freq, object tz):
+def dt64arr_to_periodarr(const int64_t[:] stamps, int freq, object tz):
cdef:
Py_ssize_t n = len(stamps)
int64_t[:] result = np.empty(n, dtype=np.int64)
@@ -1521,7 +1491,7 @@ cdef int64_t[:] localize_dt64arr_to_period(const int64_t[:] stamps,
dt64_to_dtstruct(stamps[i] + deltas[pos[i]], &dts)
result[i] = get_period_ordinal(&dts, freq)
- return result
+ return result.base # .base to get underlying ndarray
DIFFERENT_FREQ = ("Input has different freq={other_freq} "
diff --git a/pandas/_libs/tslibs/resolution.pyx b/pandas/_libs/tslibs/resolution.pyx
index 3d76483f76600..2133573ee7554 100644
--- a/pandas/_libs/tslibs/resolution.pyx
+++ b/pandas/_libs/tslibs/resolution.pyx
@@ -28,27 +28,19 @@ cdef:
# ----------------------------------------------------------------------
-cpdef resolution(const int64_t[:] stamps, tz=None):
+def resolution(const int64_t[:] stamps, tz=None):
cdef:
Py_ssize_t i, n = len(stamps)
npy_datetimestruct dts
int reso = RESO_DAY, curr_reso
-
- if tz is not None:
- tz = maybe_get_tz(tz)
- return _reso_local(stamps, tz)
-
-
-cdef _reso_local(const int64_t[:] stamps, object tz):
- cdef:
- Py_ssize_t i, n = len(stamps)
- int reso = RESO_DAY, curr_reso
ndarray[int64_t] trans
int64_t[:] deltas
Py_ssize_t[:] pos
- npy_datetimestruct dts
int64_t local_val, delta
+ if tz is not None:
+ tz = maybe_get_tz(tz)
+
if is_utc(tz) or tz is None:
for i in range(n):
if stamps[i] == NPY_NAT:
| https://api.github.com/repos/pandas-dev/pandas/pulls/34400 | 2020-05-27T02:34:59Z | 2020-05-27T17:23:34Z | 2020-05-27T17:23:34Z | 2020-05-27T17:32:17Z | |
CLN: GH29547 format with f-strings | diff --git a/pandas/util/_validators.py b/pandas/util/_validators.py
index fbb44408f01be..bb6c6de441558 100644
--- a/pandas/util/_validators.py
+++ b/pandas/util/_validators.py
@@ -295,13 +295,13 @@ def validate_axis_style_args(data, args, kwargs, arg_name, method_name):
raise TypeError(msg)
msg = (
- "Interpreting call\n\t'.{method_name}(a, b)' as "
- "\n\t'.{method_name}(index=a, columns=b)'.\nUse named "
+ f"Interpreting call\n\t'.{method_name}(a, b)' as "
+ f"\n\t'.{method_name}(index=a, columns=b)'.\nUse named "
"arguments to remove any ambiguity. In the future, using "
"positional arguments for 'index' or 'columns' will raise "
"a 'TypeError'."
)
- warnings.warn(msg.format(method_name=method_name), FutureWarning, stacklevel=4)
+ warnings.warn(msg, FutureWarning, stacklevel=4)
out[data._get_axis_name(0)] = args[0]
out[data._get_axis_name(1)] = args[1]
else:
@@ -370,12 +370,15 @@ def validate_percentile(q: Union[float, Iterable[float]]) -> np.ndarray:
------
ValueError if percentiles are not in given interval([0, 1]).
"""
- msg = "percentiles should all be in the interval [0, 1]. Try {0} instead."
q_arr = np.asarray(q)
+ msg = (
+ "percentiles should all be in the interval [0, 1]."
+ f"Try {q_arr / 100.0} instead."
+ )
if q_arr.ndim == 0:
if not 0 <= q_arr <= 1:
- raise ValueError(msg.format(q_arr / 100.0))
+ raise ValueError(msg)
else:
if not all(0 <= qs <= 1 for qs in q_arr):
- raise ValueError(msg.format(q_arr / 100.0))
+ raise ValueError(msg)
return q_arr
| Sorry all, new PR. Didn't branch off master for the last one.
#29547 | https://api.github.com/repos/pandas-dev/pandas/pulls/34399 | 2020-05-27T02:20:12Z | 2020-05-28T17:15:01Z | 2020-05-28T17:15:00Z | 2020-05-28T19:17:24Z |
REF: move remaining offsets into liboffsets | diff --git a/doc/source/reference/offset_frequency.rst b/doc/source/reference/offset_frequency.rst
index bb0dae3d5dece..fed23e48e43e9 100644
--- a/doc/source/reference/offset_frequency.rst
+++ b/doc/source/reference/offset_frequency.rst
@@ -134,6 +134,7 @@ Methods
.. autosummary::
:toctree: api/
+ CustomBusinessDay.apply_index
CustomBusinessDay.apply
CustomBusinessDay.copy
CustomBusinessDay.isAnchored
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx
index f8b7e527cac01..660cd3af1b35e 100644
--- a/pandas/_libs/tslibs/offsets.pyx
+++ b/pandas/_libs/tslibs/offsets.pyx
@@ -1008,7 +1008,7 @@ def delta_to_tick(delta: timedelta) -> Tick:
# --------------------------------------------------------------------
-class RelativeDeltaOffset(BaseOffset):
+cdef class RelativeDeltaOffset(BaseOffset):
"""
DateOffset subclass backed by a dateutil relativedelta object.
"""
@@ -1123,6 +1123,120 @@ class RelativeDeltaOffset(BaseOffset):
return True
+class OffsetMeta(type):
+ """
+ Metaclass that allows us to pretend that all BaseOffset subclasses
+ inherit from DateOffset (which is needed for backward-compatibility).
+ """
+
+ @classmethod
+ def __instancecheck__(cls, obj) -> bool:
+ return isinstance(obj, BaseOffset)
+
+ @classmethod
+ def __subclasscheck__(cls, obj) -> bool:
+ return issubclass(obj, BaseOffset)
+
+
+# TODO: figure out a way to use a metaclass with a cdef class
+class DateOffset(RelativeDeltaOffset, metaclass=OffsetMeta):
+ """
+ Standard kind of date increment used for a date range.
+
+ Works exactly like relativedelta in terms of the keyword args you
+ pass in, use of the keyword n is discouraged-- you would be better
+ off specifying n in the keywords you use, but regardless it is
+ there for you. n is needed for DateOffset subclasses.
+
+ DateOffset work as follows. Each offset specify a set of dates
+ that conform to the DateOffset. For example, Bday defines this
+ set to be the set of dates that are weekdays (M-F). To test if a
+ date is in the set of a DateOffset dateOffset we can use the
+ is_on_offset method: dateOffset.is_on_offset(date).
+
+ If a date is not on a valid date, the rollback and rollforward
+ methods can be used to roll the date to the nearest valid date
+ before/after the date.
+
+ DateOffsets can be created to move dates forward a given number of
+ valid dates. For example, Bday(2) can be added to a date to move
+ it two business days forward. If the date does not start on a
+ valid date, first it is moved to a valid date. Thus pseudo code
+ is:
+
+ def __add__(date):
+ date = rollback(date) # does nothing if date is valid
+ return date + <n number of periods>
+
+ When a date offset is created for a negative number of periods,
+ the date is first rolled forward. The pseudo code is:
+
+ def __add__(date):
+ date = rollforward(date) # does nothing is date is valid
+ return date + <n number of periods>
+
+ Zero presents a problem. Should it roll forward or back? We
+ arbitrarily have it rollforward:
+
+ date + BDay(0) == BDay.rollforward(date)
+
+ Since 0 is a bit weird, we suggest avoiding its use.
+
+ Parameters
+ ----------
+ n : int, default 1
+ The number of time periods the offset represents.
+ normalize : bool, default False
+ Whether to round the result of a DateOffset addition down to the
+ previous midnight.
+ **kwds
+ Temporal parameter that add to or replace the offset value.
+
+ Parameters that **add** to the offset (like Timedelta):
+
+ - years
+ - months
+ - weeks
+ - days
+ - hours
+ - minutes
+ - seconds
+ - microseconds
+ - nanoseconds
+
+ Parameters that **replace** the offset value:
+
+ - year
+ - month
+ - day
+ - weekday
+ - hour
+ - minute
+ - second
+ - microsecond
+ - nanosecond.
+
+ See Also
+ --------
+ dateutil.relativedelta.relativedelta : The relativedelta type is designed
+ to be applied to an existing datetime an can replace specific components of
+ that datetime, or represents an interval of time.
+
+ Examples
+ --------
+ >>> from pandas.tseries.offsets import DateOffset
+ >>> ts = pd.Timestamp('2017-01-01 09:10:11')
+ >>> ts + DateOffset(months=3)
+ Timestamp('2017-04-01 09:10:11')
+
+ >>> ts = pd.Timestamp('2017-01-01 09:10:11')
+ >>> ts + DateOffset(months=2)
+ Timestamp('2017-03-01 09:10:11')
+ """
+
+ pass
+
+
# --------------------------------------------------------------------
@@ -3134,6 +3248,292 @@ cdef class Easter(SingleConstructorOffset):
return date(dt.year, dt.month, dt.day) == easter(dt.year)
+# ----------------------------------------------------------------------
+# Custom Offset classes
+
+
+class CustomBusinessDay(CustomMixin, BusinessDay):
+ """
+ DateOffset subclass representing custom business days excluding holidays.
+
+ Parameters
+ ----------
+ n : int, default 1
+ normalize : bool, default False
+ Normalize start/end dates to midnight before generating date range.
+ weekmask : str, Default 'Mon Tue Wed Thu Fri'
+ Weekmask of valid business days, passed to ``numpy.busdaycalendar``.
+ holidays : list
+ List/array of dates to exclude from the set of valid business days,
+ passed to ``numpy.busdaycalendar``.
+ calendar : pd.HolidayCalendar or np.busdaycalendar
+ offset : timedelta, default timedelta(0)
+ """
+
+ _prefix = "C"
+ _attributes = frozenset(
+ ["n", "normalize", "weekmask", "holidays", "calendar", "offset"]
+ )
+
+ def __reduce__(self):
+ # np.holidaycalendar cant be pickled, so pass None there and
+ # it will be re-constructed within __init__
+ tup = (self.n, self.normalize, self.weekmask, self.holidays, None, self.offset)
+ return type(self), tup
+
+ def __init__(
+ self,
+ n=1,
+ normalize=False,
+ weekmask="Mon Tue Wed Thu Fri",
+ holidays=None,
+ calendar=None,
+ offset=timedelta(0),
+ ):
+ BusinessDay.__init__(self, n, normalize, offset)
+ CustomMixin.__init__(self, weekmask, holidays, calendar)
+
+ def __setstate__(self, state):
+ self.holidays = state.pop("holidays")
+ self.weekmask = state.pop("weekmask")
+ super().__setstate__(state)
+
+ @apply_wraps
+ def apply(self, other):
+ if self.n <= 0:
+ roll = "forward"
+ else:
+ roll = "backward"
+
+ if isinstance(other, datetime):
+ date_in = other
+ np_dt = np.datetime64(date_in.date())
+
+ np_incr_dt = np.busday_offset(
+ np_dt, self.n, roll=roll, busdaycal=self.calendar
+ )
+
+ dt_date = np_incr_dt.astype(datetime)
+ result = datetime.combine(dt_date, date_in.time())
+
+ if self.offset:
+ result = result + self.offset
+ return result
+
+ elif isinstance(other, (timedelta, Tick)):
+ return BDay(self.n, offset=self.offset + other, normalize=self.normalize)
+ else:
+ raise ApplyTypeError(
+ "Only know how to combine trading day with "
+ "datetime, datetime64 or timedelta."
+ )
+
+ def apply_index(self, i):
+ raise NotImplementedError
+
+ def is_on_offset(self, dt: datetime) -> bool:
+ if self.normalize and not is_normalized(dt):
+ return False
+ day64 = to_dt64D(dt)
+ return np.is_busday(day64, busdaycal=self.calendar)
+
+
+class CustomBusinessHour(CustomMixin, BusinessHour):
+ """
+ DateOffset subclass representing possibly n custom business days.
+ """
+
+ _prefix = "CBH"
+ _anchor = 0
+ _attributes = frozenset(
+ ["n", "normalize", "weekmask", "holidays", "calendar", "start", "end", "offset"]
+ )
+
+ def __init__(
+ self,
+ n=1,
+ normalize=False,
+ weekmask="Mon Tue Wed Thu Fri",
+ holidays=None,
+ calendar=None,
+ start="09:00",
+ end="17:00",
+ offset=timedelta(0),
+ ):
+ BusinessHour.__init__(self, n, normalize, start=start, end=end, offset=offset)
+ CustomMixin.__init__(self, weekmask, holidays, calendar)
+
+ def __reduce__(self):
+ # None for self.calendar bc np.busdaycalendar doesnt pickle nicely
+ return (
+ type(self),
+ (
+ self.n,
+ self.normalize,
+ self.weekmask,
+ self.holidays,
+ None,
+ self.start,
+ self.end,
+ self.offset,
+ ),
+ )
+
+
+class _CustomBusinessMonth(CustomMixin, BusinessMixin, MonthOffset):
+ """
+ DateOffset subclass representing custom business month(s).
+
+ Increments between beginning/end of month dates.
+
+ Parameters
+ ----------
+ n : int, default 1
+ The number of months represented.
+ normalize : bool, default False
+ Normalize start/end dates to midnight before generating date range.
+ weekmask : str, Default 'Mon Tue Wed Thu Fri'
+ Weekmask of valid business days, passed to ``numpy.busdaycalendar``.
+ holidays : list
+ List/array of dates to exclude from the set of valid business days,
+ passed to ``numpy.busdaycalendar``.
+ calendar : pd.HolidayCalendar or np.busdaycalendar
+ Calendar to integrate.
+ offset : timedelta, default timedelta(0)
+ Time offset to apply.
+ """
+
+ _attributes = frozenset(
+ ["n", "normalize", "weekmask", "holidays", "calendar", "offset"]
+ )
+
+ is_on_offset = BaseOffset.is_on_offset # override MonthOffset method
+ apply_index = BaseOffset.apply_index # override MonthOffset method
+
+ def __init__(
+ self,
+ n=1,
+ normalize=False,
+ weekmask="Mon Tue Wed Thu Fri",
+ holidays=None,
+ calendar=None,
+ offset=timedelta(0),
+ ):
+ BusinessMixin.__init__(self, n, normalize, offset)
+ CustomMixin.__init__(self, weekmask, holidays, calendar)
+
+ def __reduce__(self):
+ # None for self.calendar bc np.busdaycalendar doesnt pickle nicely
+ return (
+ type(self),
+ (self.n, self.normalize, self.weekmask, self.holidays, None, self.offset),
+ )
+
+ @cache_readonly
+ def cbday_roll(self):
+ """
+ Define default roll function to be called in apply method.
+ """
+ cbday = CustomBusinessDay(n=self.n, normalize=False, **self.kwds)
+
+ if self._prefix.endswith("S"):
+ # MonthBegin
+ roll_func = cbday.rollforward
+ else:
+ # MonthEnd
+ roll_func = cbday.rollback
+ return roll_func
+
+ @cache_readonly
+ def m_offset(self):
+ if self._prefix.endswith("S"):
+ # MonthBegin
+ moff = MonthBegin(n=1, normalize=False)
+ else:
+ # MonthEnd
+ moff = MonthEnd(n=1, normalize=False)
+ return moff
+
+ @cache_readonly
+ def month_roll(self):
+ """
+ Define default roll function to be called in apply method.
+ """
+ if self._prefix.endswith("S"):
+ # MonthBegin
+ roll_func = self.m_offset.rollback
+ else:
+ # MonthEnd
+ roll_func = self.m_offset.rollforward
+ return roll_func
+
+ @apply_wraps
+ def apply(self, other):
+ # First move to month offset
+ cur_month_offset_date = self.month_roll(other)
+
+ # Find this custom month offset
+ compare_date = self.cbday_roll(cur_month_offset_date)
+ n = roll_convention(other.day, self.n, compare_date.day)
+
+ new = cur_month_offset_date + n * self.m_offset
+ result = self.cbday_roll(new)
+ return result
+
+
+class CustomBusinessMonthEnd(_CustomBusinessMonth):
+ _prefix = "CBM"
+
+
+class CustomBusinessMonthBegin(_CustomBusinessMonth):
+ _prefix = "CBMS"
+
+
+BDay = BusinessDay
+BMonthEnd = BusinessMonthEnd
+BMonthBegin = BusinessMonthBegin
+CBMonthEnd = CustomBusinessMonthEnd
+CBMonthBegin = CustomBusinessMonthBegin
+CDay = CustomBusinessDay
+
+prefix_mapping = {
+ offset._prefix: offset
+ for offset in [
+ YearBegin, # 'AS'
+ YearEnd, # 'A'
+ BYearBegin, # 'BAS'
+ BYearEnd, # 'BA'
+ BusinessDay, # 'B'
+ BusinessMonthBegin, # 'BMS'
+ BusinessMonthEnd, # 'BM'
+ BQuarterEnd, # 'BQ'
+ BQuarterBegin, # 'BQS'
+ BusinessHour, # 'BH'
+ CustomBusinessDay, # 'C'
+ CustomBusinessMonthEnd, # 'CBM'
+ CustomBusinessMonthBegin, # 'CBMS'
+ CustomBusinessHour, # 'CBH'
+ MonthEnd, # 'M'
+ MonthBegin, # 'MS'
+ Nano, # 'N'
+ SemiMonthEnd, # 'SM'
+ SemiMonthBegin, # 'SMS'
+ Week, # 'W'
+ Second, # 'S'
+ Minute, # 'T'
+ Micro, # 'U'
+ QuarterEnd, # 'Q'
+ QuarterBegin, # 'QS'
+ Milli, # 'L'
+ Hour, # 'H'
+ Day, # 'D'
+ WeekOfMonth, # 'WOM'
+ FY5253,
+ FY5253Quarter,
+ ]
+}
+
+
# ----------------------------------------------------------------------
# RelativeDelta Arithmetic
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index 9a1e750c5de93..877d19ef68558 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -8,6 +8,7 @@
from pandas._libs import NaT, Period, Timestamp, index as libindex, lib, tslib
from pandas._libs.tslibs import fields, parsing, resolution as libresolution, timezones
from pandas._libs.tslibs.frequencies import get_freq_group
+from pandas._libs.tslibs.offsets import prefix_mapping
from pandas._typing import DtypeObj, Label
from pandas.util._decorators import cache_readonly
@@ -30,7 +31,6 @@
from pandas.core.tools.times import to_time
from pandas.tseries.frequencies import to_offset
-from pandas.tseries.offsets import prefix_mapping
def _new_DatetimeIndex(cls, d):
diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py
index e1936fa819baf..9d867df147096 100644
--- a/pandas/tests/indexes/datetimes/test_date_range.py
+++ b/pandas/tests/indexes/datetimes/test_date_range.py
@@ -10,6 +10,7 @@
from pytz import timezone
from pandas._libs.tslibs import timezones
+from pandas._libs.tslibs.offsets import BDay, CDay, DateOffset, MonthEnd, prefix_mapping
from pandas.errors import OutOfBoundsDatetime
import pandas.util._test_decorators as td
@@ -18,8 +19,6 @@
import pandas._testing as tm
from pandas.core.arrays.datetimes import generate_range
-from pandas.tseries.offsets import BDay, CDay, DateOffset, MonthEnd, prefix_mapping
-
START, END = datetime(2009, 1, 1), datetime(2010, 1, 1)
diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py
index 84113afdb0969..084ad4294f9d0 100644
--- a/pandas/tseries/frequencies.py
+++ b/pandas/tseries/frequencies.py
@@ -10,7 +10,18 @@
from pandas._libs.tslibs.ccalendar import MONTH_ALIASES, MONTH_NUMBERS, int_to_weekday
from pandas._libs.tslibs.fields import build_field_sarray
import pandas._libs.tslibs.frequencies as libfreqs
-from pandas._libs.tslibs.offsets import _offset_to_period_map
+from pandas._libs.tslibs.offsets import (
+ DateOffset,
+ Day,
+ Hour,
+ Micro,
+ Milli,
+ Minute,
+ Nano,
+ Second,
+ _offset_to_period_map,
+ prefix_mapping,
+)
from pandas._libs.tslibs.parsing import get_rule_month
from pandas._libs.tslibs.resolution import Resolution, month_position_check
from pandas._libs.tslibs.timezones import UTC
@@ -26,18 +37,6 @@
from pandas.core.algorithms import unique
-from pandas.tseries.offsets import (
- DateOffset,
- Day,
- Hour,
- Micro,
- Milli,
- Minute,
- Nano,
- Second,
- prefix_mapping,
-)
-
_ONE_MICRO = 1000
_ONE_MILLI = _ONE_MICRO * 1000
_ONE_SECOND = _ONE_MILLI * 1000
diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py
index fd304dc2425a3..cee99d23f8d90 100644
--- a/pandas/tseries/offsets.py
+++ b/pandas/tseries/offsets.py
@@ -1,22 +1,25 @@
-from datetime import datetime, timedelta
-
-import numpy as np
-
-from pandas._libs.tslibs import offsets as liboffsets
from pandas._libs.tslibs.offsets import ( # noqa:F401
FY5253,
- ApplyTypeError,
BaseOffset,
+ BDay,
+ BMonthBegin,
+ BMonthEnd,
BQuarterBegin,
BQuarterEnd,
BusinessDay,
BusinessHour,
- BusinessMixin,
BusinessMonthBegin,
BusinessMonthEnd,
BYearBegin,
BYearEnd,
- CustomMixin,
+ CBMonthBegin,
+ CBMonthEnd,
+ CDay,
+ CustomBusinessDay,
+ CustomBusinessHour,
+ CustomBusinessMonthBegin,
+ CustomBusinessMonthEnd,
+ DateOffset,
Day,
Easter,
FY5253Quarter,
@@ -33,19 +36,12 @@
Second,
SemiMonthBegin,
SemiMonthEnd,
- SingleConstructorOffset,
Tick,
Week,
WeekOfMonth,
YearBegin,
YearEnd,
- apply_index_wraps,
- apply_wraps,
- is_normalized,
- shift_month,
- to_dt64D,
)
-from pandas.util._decorators import cache_readonly, doc
__all__ = [
"Day",
@@ -85,411 +81,3 @@
"Nano",
"DateOffset",
]
-
-
-# ---------------------------------------------------------------------
-# DateOffset
-
-
-class OffsetMeta(type):
- """
- Metaclass that allows us to pretend that all BaseOffset subclasses
- inherit from DateOffset (which is needed for backward-compatibility).
- """
-
- @classmethod
- def __instancecheck__(cls, obj) -> bool:
- return isinstance(obj, BaseOffset)
-
- @classmethod
- def __subclasscheck__(cls, obj) -> bool:
- return issubclass(obj, BaseOffset)
-
-
-class DateOffset(liboffsets.RelativeDeltaOffset, metaclass=OffsetMeta):
- """
- Standard kind of date increment used for a date range.
-
- Works exactly like relativedelta in terms of the keyword args you
- pass in, use of the keyword n is discouraged-- you would be better
- off specifying n in the keywords you use, but regardless it is
- there for you. n is needed for DateOffset subclasses.
-
- DateOffset work as follows. Each offset specify a set of dates
- that conform to the DateOffset. For example, Bday defines this
- set to be the set of dates that are weekdays (M-F). To test if a
- date is in the set of a DateOffset dateOffset we can use the
- is_on_offset method: dateOffset.is_on_offset(date).
-
- If a date is not on a valid date, the rollback and rollforward
- methods can be used to roll the date to the nearest valid date
- before/after the date.
-
- DateOffsets can be created to move dates forward a given number of
- valid dates. For example, Bday(2) can be added to a date to move
- it two business days forward. If the date does not start on a
- valid date, first it is moved to a valid date. Thus pseudo code
- is:
-
- def __add__(date):
- date = rollback(date) # does nothing if date is valid
- return date + <n number of periods>
-
- When a date offset is created for a negative number of periods,
- the date is first rolled forward. The pseudo code is:
-
- def __add__(date):
- date = rollforward(date) # does nothing is date is valid
- return date + <n number of periods>
-
- Zero presents a problem. Should it roll forward or back? We
- arbitrarily have it rollforward:
-
- date + BDay(0) == BDay.rollforward(date)
-
- Since 0 is a bit weird, we suggest avoiding its use.
-
- Parameters
- ----------
- n : int, default 1
- The number of time periods the offset represents.
- normalize : bool, default False
- Whether to round the result of a DateOffset addition down to the
- previous midnight.
- **kwds
- Temporal parameter that add to or replace the offset value.
-
- Parameters that **add** to the offset (like Timedelta):
-
- - years
- - months
- - weeks
- - days
- - hours
- - minutes
- - seconds
- - microseconds
- - nanoseconds
-
- Parameters that **replace** the offset value:
-
- - year
- - month
- - day
- - weekday
- - hour
- - minute
- - second
- - microsecond
- - nanosecond.
-
- See Also
- --------
- dateutil.relativedelta.relativedelta : The relativedelta type is designed
- to be applied to an existing datetime an can replace specific components of
- that datetime, or represents an interval of time.
-
- Examples
- --------
- >>> from pandas.tseries.offsets import DateOffset
- >>> ts = pd.Timestamp('2017-01-01 09:10:11')
- >>> ts + DateOffset(months=3)
- Timestamp('2017-04-01 09:10:11')
-
- >>> ts = pd.Timestamp('2017-01-01 09:10:11')
- >>> ts + DateOffset(months=2)
- Timestamp('2017-03-01 09:10:11')
- """
-
- pass
-
-
-class CustomBusinessDay(CustomMixin, BusinessDay):
- """
- DateOffset subclass representing custom business days excluding holidays.
-
- Parameters
- ----------
- n : int, default 1
- normalize : bool, default False
- Normalize start/end dates to midnight before generating date range.
- weekmask : str, Default 'Mon Tue Wed Thu Fri'
- Weekmask of valid business days, passed to ``numpy.busdaycalendar``.
- holidays : list
- List/array of dates to exclude from the set of valid business days,
- passed to ``numpy.busdaycalendar``.
- calendar : pd.HolidayCalendar or np.busdaycalendar
- offset : timedelta, default timedelta(0)
- """
-
- _prefix = "C"
- _attributes = frozenset(
- ["n", "normalize", "weekmask", "holidays", "calendar", "offset"]
- )
-
- def __reduce__(self):
- # np.holidaycalendar cant be pickled, so pass None there and
- # it will be re-constructed within __init__
- tup = (self.n, self.normalize, self.weekmask, self.holidays, None, self.offset)
- return type(self), tup
-
- def __init__(
- self,
- n=1,
- normalize=False,
- weekmask="Mon Tue Wed Thu Fri",
- holidays=None,
- calendar=None,
- offset=timedelta(0),
- ):
- BusinessDay.__init__(self, n, normalize, offset)
- CustomMixin.__init__(self, weekmask, holidays, calendar)
-
- def __setstate__(self, state):
- self.holidays = state.pop("holidays")
- self.weekmask = state.pop("weekmask")
- super().__setstate__(state)
-
- @apply_wraps
- def apply(self, other):
- if self.n <= 0:
- roll = "forward"
- else:
- roll = "backward"
-
- if isinstance(other, datetime):
- date_in = other
- np_dt = np.datetime64(date_in.date())
-
- np_incr_dt = np.busday_offset(
- np_dt, self.n, roll=roll, busdaycal=self.calendar
- )
-
- dt_date = np_incr_dt.astype(datetime)
- result = datetime.combine(dt_date, date_in.time())
-
- if self.offset:
- result = result + self.offset
- return result
-
- elif isinstance(other, (timedelta, Tick)):
- return BDay(self.n, offset=self.offset + other, normalize=self.normalize)
- else:
- raise ApplyTypeError(
- "Only know how to combine trading day with "
- "datetime, datetime64 or timedelta."
- )
-
- def apply_index(self, i):
- raise NotImplementedError
-
- def is_on_offset(self, dt: datetime) -> bool:
- if self.normalize and not is_normalized(dt):
- return False
- day64 = to_dt64D(dt)
- return np.is_busday(day64, busdaycal=self.calendar)
-
-
-class CustomBusinessHour(CustomMixin, BusinessHour):
- """
- DateOffset subclass representing possibly n custom business days.
- """
-
- _prefix = "CBH"
- _anchor = 0
- _attributes = frozenset(
- ["n", "normalize", "weekmask", "holidays", "calendar", "start", "end", "offset"]
- )
-
- def __init__(
- self,
- n=1,
- normalize=False,
- weekmask="Mon Tue Wed Thu Fri",
- holidays=None,
- calendar=None,
- start="09:00",
- end="17:00",
- offset=timedelta(0),
- ):
- BusinessHour.__init__(self, n, normalize, start=start, end=end, offset=offset)
- CustomMixin.__init__(self, weekmask, holidays, calendar)
-
- def __reduce__(self):
- # None for self.calendar bc np.busdaycalendar doesnt pickle nicely
- return (
- type(self),
- (
- self.n,
- self.normalize,
- self.weekmask,
- self.holidays,
- None,
- self.start,
- self.end,
- self.offset,
- ),
- )
-
-
-# ---------------------------------------------------------------------
-# Month-Based Offset Classes
-
-
-@doc(bound="bound")
-class _CustomBusinessMonth(CustomMixin, BusinessMixin, liboffsets.MonthOffset):
- """
- DateOffset subclass representing custom business month(s).
-
- Increments between {bound} of month dates.
-
- Parameters
- ----------
- n : int, default 1
- The number of months represented.
- normalize : bool, default False
- Normalize start/end dates to midnight before generating date range.
- weekmask : str, Default 'Mon Tue Wed Thu Fri'
- Weekmask of valid business days, passed to ``numpy.busdaycalendar``.
- holidays : list
- List/array of dates to exclude from the set of valid business days,
- passed to ``numpy.busdaycalendar``.
- calendar : pd.HolidayCalendar or np.busdaycalendar
- Calendar to integrate.
- offset : timedelta, default timedelta(0)
- Time offset to apply.
- """
-
- _attributes = frozenset(
- ["n", "normalize", "weekmask", "holidays", "calendar", "offset"]
- )
-
- is_on_offset = BaseOffset.is_on_offset # override MonthOffset method
- apply_index = BaseOffset.apply_index # override MonthOffset method
-
- def __init__(
- self,
- n=1,
- normalize=False,
- weekmask="Mon Tue Wed Thu Fri",
- holidays=None,
- calendar=None,
- offset=timedelta(0),
- ):
- BusinessMixin.__init__(self, n, normalize, offset)
- CustomMixin.__init__(self, weekmask, holidays, calendar)
-
- def __reduce__(self):
- # None for self.calendar bc np.busdaycalendar doesnt pickle nicely
- return (
- type(self),
- (self.n, self.normalize, self.weekmask, self.holidays, None, self.offset),
- )
-
- @cache_readonly
- def cbday_roll(self):
- """
- Define default roll function to be called in apply method.
- """
- cbday = CustomBusinessDay(n=self.n, normalize=False, **self.kwds)
-
- if self._prefix.endswith("S"):
- # MonthBegin
- roll_func = cbday.rollforward
- else:
- # MonthEnd
- roll_func = cbday.rollback
- return roll_func
-
- @cache_readonly
- def m_offset(self):
- if self._prefix.endswith("S"):
- # MonthBegin
- moff = MonthBegin(n=1, normalize=False)
- else:
- # MonthEnd
- moff = MonthEnd(n=1, normalize=False)
- return moff
-
- @cache_readonly
- def month_roll(self):
- """
- Define default roll function to be called in apply method.
- """
- if self._prefix.endswith("S"):
- # MonthBegin
- roll_func = self.m_offset.rollback
- else:
- # MonthEnd
- roll_func = self.m_offset.rollforward
- return roll_func
-
- @apply_wraps
- def apply(self, other):
- # First move to month offset
- cur_month_offset_date = self.month_roll(other)
-
- # Find this custom month offset
- compare_date = self.cbday_roll(cur_month_offset_date)
- n = liboffsets.roll_convention(other.day, self.n, compare_date.day)
-
- new = cur_month_offset_date + n * self.m_offset
- result = self.cbday_roll(new)
- return result
-
-
-@doc(_CustomBusinessMonth, bound="end")
-class CustomBusinessMonthEnd(_CustomBusinessMonth):
- _prefix = "CBM"
-
-
-@doc(_CustomBusinessMonth, bound="beginning")
-class CustomBusinessMonthBegin(_CustomBusinessMonth):
- _prefix = "CBMS"
-
-
-# ---------------------------------------------------------------------
-
-BDay = BusinessDay
-BMonthEnd = BusinessMonthEnd
-BMonthBegin = BusinessMonthBegin
-CBMonthEnd = CustomBusinessMonthEnd
-CBMonthBegin = CustomBusinessMonthBegin
-CDay = CustomBusinessDay
-
-prefix_mapping = {
- offset._prefix: offset
- for offset in [
- YearBegin, # 'AS'
- YearEnd, # 'A'
- BYearBegin, # 'BAS'
- BYearEnd, # 'BA'
- BusinessDay, # 'B'
- BusinessMonthBegin, # 'BMS'
- BusinessMonthEnd, # 'BM'
- BQuarterEnd, # 'BQ'
- BQuarterBegin, # 'BQS'
- BusinessHour, # 'BH'
- CustomBusinessDay, # 'C'
- CustomBusinessMonthEnd, # 'CBM'
- CustomBusinessMonthBegin, # 'CBMS'
- CustomBusinessHour, # 'CBH'
- MonthEnd, # 'M'
- MonthBegin, # 'MS'
- Nano, # 'N'
- SemiMonthEnd, # 'SM'
- SemiMonthBegin, # 'SMS'
- Week, # 'W'
- Second, # 'S'
- Minute, # 'T'
- Micro, # 'U'
- QuarterEnd, # 'Q'
- QuarterBegin, # 'QS'
- Milli, # 'L'
- Hour, # 'H'
- Day, # 'D'
- WeekOfMonth, # 'WOM'
- FY5253,
- FY5253Quarter,
- ]
-}
| this _doesnt_ make them all cdef classes yet; need to get #34345 figured out before that is doable. | https://api.github.com/repos/pandas-dev/pandas/pulls/34398 | 2020-05-27T00:51:00Z | 2020-05-27T17:23:51Z | 2020-05-27T17:23:51Z | 2020-05-27T17:32:54Z |
DOC: added D-Tale to the visualizations section of Ecosystem page | diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst
index 6c6a7f42d4b7e..62065f016e438 100644
--- a/doc/source/ecosystem.rst
+++ b/doc/source/ecosystem.rst
@@ -153,6 +153,23 @@ A good implementation for Python users is `has2k1/plotnine <https://github.com/h
Spun off from the main pandas library, the `qtpandas <https://github.com/draperjames/qtpandas>`__
library enables DataFrame visualization and manipulation in PyQt4 and PySide applications.
+`D-Tale <https://github.com/man-group/dtale>`__
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+D-Tale is a lightweight web client for visualizing pandas data structures. It
+provides a rich spreadsheet-style grid which acts as a wrapper for a lot of
+pandas functionality (query, sort, describe, corr...) so users can quickly
+manipulate their data. There is also an interactive chart-builder using Plotly
+Dash allowing users to build nice portable visualizations. D-Tale can be
+invoked with the following command
+
+.. code:: python
+
+ import dtale; dtale.show(df)
+
+D-Tale integrates seamlessly with jupyter notebooks, python terminals, kaggle
+& Google Colab. Here are some demos of the `grid <http://alphatechadmin.pythonanywhere.com/>`__
+and `chart-builder <http://alphatechadmin.pythonanywhere.com/charts/4?chart_type=surface&query=&x=date&z=Col0&agg=raw&cpg=false&y=%5B%22security_id%22%5D>`__.
.. _ecosystem.ide:
| - [x] closes #34376
Added [D-Tale](https://github.com/man-group/dtale) to the visualizations section of [Pandas Ecosystem](https://pandas.pydata.org/docs/ecosystem.html) doc
| https://api.github.com/repos/pandas-dev/pandas/pulls/34396 | 2020-05-26T22:02:51Z | 2020-05-27T18:28:32Z | 2020-05-27T18:28:32Z | 2020-05-27T18:34:13Z |
DOC: "Setting layouts" plots' label size GH34305 | diff --git a/doc/source/user_guide/visualization.rst b/doc/source/user_guide/visualization.rst
index 451ddf046416e..a813348a342c2 100644
--- a/doc/source/user_guide/visualization.rst
+++ b/doc/source/user_guide/visualization.rst
@@ -1332,7 +1332,7 @@ otherwise you will see a warning.
.. ipython:: python
- fig, axes = plt.subplots(4, 4, figsize=(6, 6))
+ fig, axes = plt.subplots(4, 4, figsize=(9, 9))
plt.subplots_adjust(wspace=0.5, hspace=0.5)
target1 = [axes[0][0], axes[1][1], axes[2][2], axes[3][3]]
target2 = [axes[3][0], axes[2][1], axes[1][2], axes[0][3]]
@@ -1369,6 +1369,7 @@ Another option is passing an ``ax`` argument to :meth:`Series.plot` to plot on a
.. ipython:: python
fig, axes = plt.subplots(nrows=2, ncols=2)
+ plt.subplots_adjust(wspace=0.2, hspace=0.5)
df['A'].plot(ax=axes[0, 0]);
axes[0, 0].set_title('A');
df['B'].plot(ax=axes[0, 1]);
| - [X] closes #34305
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/34394 | 2020-05-26T20:19:42Z | 2020-06-07T21:23:10Z | 2020-06-07T21:23:10Z | 2020-06-07T21:23:16Z |
DOC: add a semicolon to hide long matplotlib axes return value | diff --git a/doc/source/user_guide/visualization.rst b/doc/source/user_guide/visualization.rst
index 451ddf046416e..814627043cfc8 100644
--- a/doc/source/user_guide/visualization.rst
+++ b/doc/source/user_guide/visualization.rst
@@ -821,7 +821,7 @@ You can create a scatter plot matrix using the
df = pd.DataFrame(np.random.randn(1000, 4), columns=['a', 'b', 'c', 'd'])
@savefig scatter_matrix_kde.png
- scatter_matrix(df, alpha=0.2, figsize=(6, 6), diagonal='kde')
+ scatter_matrix(df, alpha=0.2, figsize=(6, 6), diagonal='kde');
.. ipython:: python
:suppress:
@@ -1683,4 +1683,4 @@ to generate the plots. Some libraries implementing a backend for pandas are list
on the ecosystem :ref:`ecosystem.visualization` page.
Developers guide can be found at
-https://dev.pandas.io/docs/development/extending.html#plotting-backends
\ No newline at end of file
+https://pandas.pydata.org/docs/dev/development/extending.html#plotting-backends
| add a semicolon to hide debug messages like:
Out[85]:
array([[<matplotlib.axes._subplots.AxesSubplot object at 0x7f3d0ad6e3d0>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7f3d0ad4a350>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7f3d0aa10250>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7f3d0a6367d0>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x7f3d088c2d50>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7f3d089ea310>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7f3d08d89890>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7f3d0a76ae10>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x7f3d0a756090>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7f3d0a8dd750>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7f3d096aaed0>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7f3d0937d490>],
[<matplotlib.axes._subplots.AxesSubplot object at 0x7f3d09f49a10>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7f3d0a0551d0>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7f3d0a418550>,
<matplotlib.axes._subplots.AxesSubplot object at 0x7f3d0a6f0ad0>]],
dtype=object)
which you can see here:
https://pandas.pydata.org/docs/user_guide/visualization.html
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/34393 | 2020-05-26T18:51:37Z | 2020-05-28T20:24:31Z | 2020-05-28T20:24:31Z | 2020-05-28T21:17:00Z |
ENH: Set index of returned dataframe in DatetimeIndex.isocalendar | diff --git a/doc/source/user_guide/timeseries.rst b/doc/source/user_guide/timeseries.rst
index a4e458032b787..5351c3ee6b624 100644
--- a/doc/source/user_guide/timeseries.rst
+++ b/doc/source/user_guide/timeseries.rst
@@ -793,6 +793,7 @@ You may obtain the year, week and day components of the ISO year from the ISO 86
.. ipython:: python
idx = pd.date_range(start='2019-12-29', freq='D', periods=4)
+ idx.isocalendar()
idx.to_series().dt.isocalendar()
.. _timeseries.offsets:
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index c33cd505d0948..8b141965bbfe1 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -209,7 +209,7 @@ Other enhancements
- :class:`Series.str` now has a `fullmatch` method that matches a regular expression against the entire string in each row of the series, similar to `re.fullmatch` (:issue:`32806`).
- :meth:`DataFrame.sample` will now also allow array-like and BitGenerator objects to be passed to ``random_state`` as seeds (:issue:`32503`)
- :meth:`MultiIndex.union` will now raise `RuntimeWarning` if the object inside are unsortable, pass `sort=False` to suppress this warning (:issue:`33015`)
-- :class:`Series.dt` and :class:`DatatimeIndex` now have an `isocalendar` method that returns a :class:`DataFrame` with year, week, and day calculated according to the ISO 8601 calendar (:issue:`33206`).
+- :class:`Series.dt` and :class:`DatatimeIndex` now have an `isocalendar` method that returns a :class:`DataFrame` with year, week, and day calculated according to the ISO 8601 calendar (:issue:`33206`, :issue:`34392`).
- The :meth:`DataFrame.to_feather` method now supports additional keyword
arguments (e.g. to set the compression) that are added in pyarrow 0.17
(:issue:`33422`).
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index 50d792aeb12f4..894a519cb693e 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -1272,17 +1272,17 @@ def isocalendar(self):
--------
>>> idx = pd.date_range(start='2019-12-29', freq='D', periods=4)
>>> idx.isocalendar()
- year week day
- 0 2019 52 7
- 1 2020 1 1
- 2 2020 1 2
- 3 2020 1 3
+ year week day
+ 2019-12-29 2019 52 7
+ 2019-12-30 2020 1 1
+ 2019-12-31 2020 1 2
+ 2020-01-01 2020 1 3
>>> idx.isocalendar().week
- 0 52
- 1 1
- 2 1
- 3 1
- Name: week, dtype: UInt32
+ 2019-12-29 52
+ 2019-12-30 1
+ 2019-12-31 1
+ 2020-01-01 1
+ Freq: D, Name: week, dtype: UInt32
"""
from pandas import DataFrame
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index 47c50dd2c7b14..9a1e750c5de93 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -66,7 +66,7 @@ def _new_DatetimeIndex(cls, d):
@inherit_names(
- ["to_period", "to_perioddelta", "to_julian_date", "strftime"]
+ ["to_period", "to_perioddelta", "to_julian_date", "strftime", "isocalendar"]
+ DatetimeArray._field_ops
+ DatetimeArray._datetimelike_methods,
DatetimeArray,
@@ -90,7 +90,6 @@ def _new_DatetimeIndex(cls, d):
"date",
"time",
"timetz",
- "isocalendar",
]
+ DatetimeArray._bool_ops,
DatetimeArray,
diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py
index badf6502aa723..c9367b7e2ee1d 100644
--- a/pandas/core/indexes/extension.py
+++ b/pandas/core/indexes/extension.py
@@ -10,7 +10,7 @@
from pandas.util._decorators import cache_readonly, doc
from pandas.core.dtypes.common import is_dtype_equal, is_object_dtype
-from pandas.core.dtypes.generic import ABCSeries
+from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
from pandas.core.arrays import ExtensionArray
from pandas.core.indexers import deprecate_ndim_indexing
@@ -55,6 +55,8 @@ def fget(self):
if wrap:
if isinstance(result, type(self._data)):
return type(self)._simple_new(result, name=self.name)
+ elif isinstance(result, ABCDataFrame):
+ return result.set_index(self)
return Index(result, name=self.name)
return result
@@ -77,6 +79,8 @@ def method(self, *args, **kwargs):
if wrap:
if isinstance(result, type(self._data)):
return type(self)._simple_new(result, name=self.name)
+ elif isinstance(result, ABCDataFrame):
+ return result.set_index(self)
return Index(result, name=self.name)
return result
diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py
index 7997247ca0307..b3347b3c64e6c 100644
--- a/pandas/tests/groupby/transform/test_transform.py
+++ b/pandas/tests/groupby/transform/test_transform.py
@@ -1022,7 +1022,7 @@ def test_groupby_transform_with_datetimes(func, values):
dates = pd.date_range("1/1/2011", periods=10, freq="D")
stocks = pd.DataFrame({"price": np.arange(10.0)}, index=dates)
- stocks["week_id"] = dates.isocalendar().set_index(dates).week
+ stocks["week_id"] = dates.isocalendar().week
result = stocks.groupby(stocks["week_id"])["price"].transform(func)
diff --git a/pandas/tests/indexes/datetimes/test_misc.py b/pandas/tests/indexes/datetimes/test_misc.py
index b9373328eb87f..51841727d510b 100644
--- a/pandas/tests/indexes/datetimes/test_misc.py
+++ b/pandas/tests/indexes/datetimes/test_misc.py
@@ -404,6 +404,7 @@ def test_isocalendar_returns_correct_values_close_to_new_year_with_tz():
expected_data_frame = pd.DataFrame(
[[2013, 52, 7], [2014, 1, 1], [2014, 1, 2]],
columns=["year", "week", "day"],
+ index=dates,
dtype="UInt32",
)
tm.assert_frame_equal(result, expected_data_frame)
| This is a followup on #33595, (specifically [here](https://github.com/pandas-dev/pandas/pull/33595#issuecomment-614888200) and [here](https://github.com/pandas-dev/pandas/pull/33595#issuecomment-614897268)), where it was noted that `DatetimeIndex.isocalendar` should set the index of the
returned dataframe. | https://api.github.com/repos/pandas-dev/pandas/pulls/34392 | 2020-05-26T18:36:43Z | 2020-05-27T12:36:13Z | 2020-05-27T12:36:13Z | 2021-10-29T14:22:50Z |
REF: BusinessDay, BusinessHour to liboffsets | diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx
index 4cf8eeb52475b..984c0c702c28d 100644
--- a/pandas/_libs/tslibs/offsets.pyx
+++ b/pandas/_libs/tslibs/offsets.pyx
@@ -1,5 +1,6 @@
import cython
+import operator
import time
from typing import Any
import warnings
@@ -1163,7 +1164,140 @@ cdef class BusinessMixin(SingleConstructorOffset):
BaseOffset.__setstate__(self, state)
-cdef class BusinessHourMixin(BusinessMixin):
+cdef class BusinessDay(BusinessMixin):
+ """
+ DateOffset subclass representing possibly n business days.
+ """
+
+ _prefix = "B"
+ _attributes = frozenset(["n", "normalize", "offset"])
+
+ cpdef __setstate__(self, state):
+ self.n = state.pop("n")
+ self.normalize = state.pop("normalize")
+ if "_offset" in state:
+ self._offset = state.pop("_offset")
+ elif "offset" in state:
+ self._offset = state.pop("offset")
+
+ def __reduce__(self):
+ tup = (self.n, self.normalize, self.offset)
+ return type(self), tup
+
+ @property
+ def _params(self):
+ # FIXME: using cache_readonly breaks a pytables test
+ return BaseOffset._params.func(self)
+
+ def _offset_str(self) -> str:
+ def get_str(td):
+ off_str = ""
+ if td.days > 0:
+ off_str += str(td.days) + "D"
+ if td.seconds > 0:
+ s = td.seconds
+ hrs = int(s / 3600)
+ if hrs != 0:
+ off_str += str(hrs) + "H"
+ s -= hrs * 3600
+ mts = int(s / 60)
+ if mts != 0:
+ off_str += str(mts) + "Min"
+ s -= mts * 60
+ if s != 0:
+ off_str += str(s) + "s"
+ if td.microseconds > 0:
+ off_str += str(td.microseconds) + "us"
+ return off_str
+
+ if isinstance(self.offset, timedelta):
+ zero = timedelta(0, 0, 0)
+ if self.offset >= zero:
+ off_str = "+" + get_str(self.offset)
+ else:
+ off_str = "-" + get_str(-self.offset)
+ return off_str
+ else:
+ return "+" + repr(self.offset)
+
+ @apply_wraps
+ def apply(self, other):
+ if isinstance(other, datetime):
+ n = self.n
+ wday = other.weekday()
+
+ # avoid slowness below by operating on weeks first
+ weeks = n // 5
+ if n <= 0 and wday > 4:
+ # roll forward
+ n += 1
+
+ n -= 5 * weeks
+
+ # n is always >= 0 at this point
+ if n == 0 and wday > 4:
+ # roll back
+ days = 4 - wday
+ elif wday > 4:
+ # roll forward
+ days = (7 - wday) + (n - 1)
+ elif wday + n <= 4:
+ # shift by n days without leaving the current week
+ days = n
+ else:
+ # shift by n days plus 2 to get past the weekend
+ days = n + 2
+
+ result = other + timedelta(days=7 * weeks + days)
+ if self.offset:
+ result = result + self.offset
+ return result
+
+ elif isinstance(other, (timedelta, Tick)):
+ return BusinessDay(
+ self.n, offset=self.offset + other, normalize=self.normalize
+ )
+ else:
+ raise ApplyTypeError(
+ "Only know how to combine business day with datetime or timedelta."
+ )
+
+ @apply_index_wraps
+ def apply_index(self, dtindex):
+ time = dtindex.to_perioddelta("D")
+ # to_period rolls forward to next BDay; track and
+ # reduce n where it does when rolling forward
+ asper = dtindex.to_period("B")
+
+ if self.n > 0:
+ shifted = (dtindex.to_perioddelta("B") - time).asi8 != 0
+
+ # Integer-array addition is deprecated, so we use
+ # _time_shift directly
+ roll = np.where(shifted, self.n - 1, self.n)
+ shifted = asper._addsub_int_array(roll, operator.add)
+ else:
+ # Integer addition is deprecated, so we use _time_shift directly
+ roll = self.n
+ shifted = asper._time_shift(roll)
+
+ result = shifted.to_timestamp() + time
+ return result
+
+ def is_on_offset(self, dt) -> bool:
+ if self.normalize and not is_normalized(dt):
+ return False
+ return dt.weekday() < 5
+
+
+cdef class BusinessHour(BusinessMixin):
+ """
+ DateOffset subclass representing possibly n business hours.
+ """
+
+ _prefix = "BH"
+ _anchor = 0
+ _attributes = frozenset(["n", "normalize", "start", "end", "offset"])
_adjust_dst = False
cdef readonly:
@@ -1218,6 +1352,18 @@ cdef class BusinessHourMixin(BusinessMixin):
self.start = start
self.end = end
+ cpdef __setstate__(self, state):
+ start = state.pop("start")
+ start = (start,) if np.ndim(start) == 0 else tuple(start)
+ end = state.pop("end")
+ end = (end,) if np.ndim(end) == 0 else tuple(end)
+ self.start = start
+ self.end = end
+
+ state.pop("kwds", {})
+ state.pop("next_bday", None)
+ BusinessMixin.__setstate__(self, state)
+
def __reduce__(self):
return type(self), (self.n, self.normalize, self.start, self.end, self.offset)
@@ -1262,6 +1408,267 @@ cdef class BusinessHourMixin(BusinessMixin):
)
assert False
+ @cache_readonly
+ def next_bday(self):
+ """
+ Used for moving to next business day.
+ """
+ if self.n >= 0:
+ nb_offset = 1
+ else:
+ nb_offset = -1
+ if self._prefix.startswith("C"):
+ # CustomBusinessHour
+ from pandas.tseries.offsets import CustomBusinessDay
+ return CustomBusinessDay(
+ n=nb_offset,
+ weekmask=self.weekmask,
+ holidays=self.holidays,
+ calendar=self.calendar,
+ )
+ else:
+ return BusinessDay(n=nb_offset)
+
+ def _next_opening_time(self, other, sign=1):
+ """
+ If self.n and sign have the same sign, return the earliest opening time
+ later than or equal to current time.
+ Otherwise the latest opening time earlier than or equal to current
+ time.
+
+ Opening time always locates on BusinessDay.
+ However, closing time may not if business hour extends over midnight.
+
+ Parameters
+ ----------
+ other : datetime
+ Current time.
+ sign : int, default 1.
+ Either 1 or -1. Going forward in time if it has the same sign as
+ self.n. Going backward in time otherwise.
+
+ Returns
+ -------
+ result : datetime
+ Next opening time.
+ """
+ earliest_start = self.start[0]
+ latest_start = self.start[-1]
+
+ if not self.next_bday.is_on_offset(other):
+ # today is not business day
+ other = other + sign * self.next_bday
+ if self.n * sign >= 0:
+ hour, minute = earliest_start.hour, earliest_start.minute
+ else:
+ hour, minute = latest_start.hour, latest_start.minute
+ else:
+ if self.n * sign >= 0:
+ if latest_start < other.time():
+ # current time is after latest starting time in today
+ other = other + sign * self.next_bday
+ hour, minute = earliest_start.hour, earliest_start.minute
+ else:
+ # find earliest starting time no earlier than current time
+ for st in self.start:
+ if other.time() <= st:
+ hour, minute = st.hour, st.minute
+ break
+ else:
+ if other.time() < earliest_start:
+ # current time is before earliest starting time in today
+ other = other + sign * self.next_bday
+ hour, minute = latest_start.hour, latest_start.minute
+ else:
+ # find latest starting time no later than current time
+ for st in reversed(self.start):
+ if other.time() >= st:
+ hour, minute = st.hour, st.minute
+ break
+
+ return datetime(other.year, other.month, other.day, hour, minute)
+
+ def _prev_opening_time(self, other):
+ """
+ If n is positive, return the latest opening time earlier than or equal
+ to current time.
+ Otherwise the earliest opening time later than or equal to current
+ time.
+
+ Parameters
+ ----------
+ other : datetime
+ Current time.
+
+ Returns
+ -------
+ result : datetime
+ Previous opening time.
+ """
+ return self._next_opening_time(other, sign=-1)
+
+ @apply_wraps
+ def rollback(self, dt):
+ """
+ Roll provided date backward to next offset only if not on offset.
+ """
+ if not self.is_on_offset(dt):
+ if self.n >= 0:
+ dt = self._prev_opening_time(dt)
+ else:
+ dt = self._next_opening_time(dt)
+ return self._get_closing_time(dt)
+ return dt
+
+ @apply_wraps
+ def rollforward(self, dt):
+ """
+ Roll provided date forward to next offset only if not on offset.
+ """
+ if not self.is_on_offset(dt):
+ if self.n >= 0:
+ return self._next_opening_time(dt)
+ else:
+ return self._prev_opening_time(dt)
+ return dt
+
+ @apply_wraps
+ def apply(self, other):
+ if isinstance(other, datetime):
+ # used for detecting edge condition
+ nanosecond = getattr(other, "nanosecond", 0)
+ # reset timezone and nanosecond
+ # other may be a Timestamp, thus not use replace
+ other = datetime(
+ other.year,
+ other.month,
+ other.day,
+ other.hour,
+ other.minute,
+ other.second,
+ other.microsecond,
+ )
+ n = self.n
+
+ # adjust other to reduce number of cases to handle
+ if n >= 0:
+ if other.time() in self.end or not self._is_on_offset(other):
+ other = self._next_opening_time(other)
+ else:
+ if other.time() in self.start:
+ # adjustment to move to previous business day
+ other = other - timedelta(seconds=1)
+ if not self._is_on_offset(other):
+ other = self._next_opening_time(other)
+ other = self._get_closing_time(other)
+
+ # get total business hours by sec in one business day
+ businesshours = sum(
+ self._get_business_hours_by_sec(st, en)
+ for st, en in zip(self.start, self.end)
+ )
+
+ bd, r = divmod(abs(n * 60), businesshours // 60)
+ if n < 0:
+ bd, r = -bd, -r
+
+ # adjust by business days first
+ if bd != 0:
+ if self._prefix.startswith("C"):
+ # GH#30593 this is a Custom offset
+ from pandas.tseries.offsets import CustomBusinessDay
+ skip_bd = CustomBusinessDay(
+ n=bd,
+ weekmask=self.weekmask,
+ holidays=self.holidays,
+ calendar=self.calendar,
+ )
+ else:
+ skip_bd = BusinessDay(n=bd)
+ # midnight business hour may not on BusinessDay
+ if not self.next_bday.is_on_offset(other):
+ prev_open = self._prev_opening_time(other)
+ remain = other - prev_open
+ other = prev_open + skip_bd + remain
+ else:
+ other = other + skip_bd
+
+ # remaining business hours to adjust
+ bhour_remain = timedelta(minutes=r)
+
+ if n >= 0:
+ while bhour_remain != timedelta(0):
+ # business hour left in this business time interval
+ bhour = (
+ self._get_closing_time(self._prev_opening_time(other)) - other
+ )
+ if bhour_remain < bhour:
+ # finish adjusting if possible
+ other += bhour_remain
+ bhour_remain = timedelta(0)
+ else:
+ # go to next business time interval
+ bhour_remain -= bhour
+ other = self._next_opening_time(other + bhour)
+ else:
+ while bhour_remain != timedelta(0):
+ # business hour left in this business time interval
+ bhour = self._next_opening_time(other) - other
+ if (
+ bhour_remain > bhour
+ or bhour_remain == bhour
+ and nanosecond != 0
+ ):
+ # finish adjusting if possible
+ other += bhour_remain
+ bhour_remain = timedelta(0)
+ else:
+ # go to next business time interval
+ bhour_remain -= bhour
+ other = self._get_closing_time(
+ self._next_opening_time(
+ other + bhour - timedelta(seconds=1)
+ )
+ )
+
+ return other
+ else:
+ raise ApplyTypeError("Only know how to combine business hour with datetime")
+
+ def is_on_offset(self, dt):
+ if self.normalize and not is_normalized(dt):
+ return False
+
+ if dt.tzinfo is not None:
+ dt = datetime(
+ dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond
+ )
+ # Valid BH can be on the different BusinessDay during midnight
+ # Distinguish by the time spent from previous opening time
+ return self._is_on_offset(dt)
+
+ def _is_on_offset(self, dt):
+ """
+ Slight speedups using calculated values.
+ """
+ # if self.normalize and not is_normalized(dt):
+ # return False
+ # Valid BH can be on the different BusinessDay during midnight
+ # Distinguish by the time spent from previous opening time
+ if self.n >= 0:
+ op = self._prev_opening_time(dt)
+ else:
+ op = self._next_opening_time(dt)
+ span = (dt - op).total_seconds()
+ businesshours = 0
+ for i, st in enumerate(self.start):
+ if op.hour == st.hour and op.minute == st.minute:
+ businesshours = self._get_business_hours_by_sec(st, self.end[i])
+ if span <= businesshours:
+ return True
+ else:
+ return False
+
class CustomMixin:
"""
diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py
index c3ad48d5ce34d..5cf70229cd5e7 100644
--- a/pandas/tseries/offsets.py
+++ b/pandas/tseries/offsets.py
@@ -17,6 +17,8 @@
BaseOffset,
BQuarterBegin,
BQuarterEnd,
+ BusinessDay,
+ BusinessHour,
BusinessMixin,
BusinessMonthBegin,
BusinessMonthEnd,
@@ -204,385 +206,6 @@ def __add__(date):
pass
-class BusinessDay(BusinessMixin):
- """
- DateOffset subclass representing possibly n business days.
- """
-
- _prefix = "B"
- _attributes = frozenset(["n", "normalize", "offset"])
-
- def __reduce__(self):
- tup = (self.n, self.normalize, self.offset)
- return type(self), tup
-
- def _offset_str(self) -> str:
- def get_str(td):
- off_str = ""
- if td.days > 0:
- off_str += str(td.days) + "D"
- if td.seconds > 0:
- s = td.seconds
- hrs = int(s / 3600)
- if hrs != 0:
- off_str += str(hrs) + "H"
- s -= hrs * 3600
- mts = int(s / 60)
- if mts != 0:
- off_str += str(mts) + "Min"
- s -= mts * 60
- if s != 0:
- off_str += str(s) + "s"
- if td.microseconds > 0:
- off_str += str(td.microseconds) + "us"
- return off_str
-
- if isinstance(self.offset, timedelta):
- zero = timedelta(0, 0, 0)
- if self.offset >= zero:
- off_str = "+" + get_str(self.offset)
- else:
- off_str = "-" + get_str(-self.offset)
- return off_str
- else:
- return "+" + repr(self.offset)
-
- @apply_wraps
- def apply(self, other):
- if isinstance(other, datetime):
- n = self.n
- wday = other.weekday()
-
- # avoid slowness below by operating on weeks first
- weeks = n // 5
- if n <= 0 and wday > 4:
- # roll forward
- n += 1
-
- n -= 5 * weeks
-
- # n is always >= 0 at this point
- if n == 0 and wday > 4:
- # roll back
- days = 4 - wday
- elif wday > 4:
- # roll forward
- days = (7 - wday) + (n - 1)
- elif wday + n <= 4:
- # shift by n days without leaving the current week
- days = n
- else:
- # shift by n days plus 2 to get past the weekend
- days = n + 2
-
- result = other + timedelta(days=7 * weeks + days)
- if self.offset:
- result = result + self.offset
- return result
-
- elif isinstance(other, (timedelta, Tick)):
- return BDay(self.n, offset=self.offset + other, normalize=self.normalize)
- else:
- raise ApplyTypeError(
- "Only know how to combine business day with datetime or timedelta."
- )
-
- @apply_index_wraps
- def apply_index(self, i):
- time = i.to_perioddelta("D")
- # to_period rolls forward to next BDay; track and
- # reduce n where it does when rolling forward
- asper = i.to_period("B")
-
- if self.n > 0:
- shifted = (i.to_perioddelta("B") - time).asi8 != 0
-
- # Integer-array addition is deprecated, so we use
- # _time_shift directly
- roll = np.where(shifted, self.n - 1, self.n)
- shifted = asper._addsub_int_array(roll, operator.add)
- else:
- # Integer addition is deprecated, so we use _time_shift directly
- roll = self.n
- shifted = asper._time_shift(roll)
-
- result = shifted.to_timestamp() + time
- return result
-
- def is_on_offset(self, dt: datetime) -> bool:
- if self.normalize and not is_normalized(dt):
- return False
- return dt.weekday() < 5
-
-
-class BusinessHour(liboffsets.BusinessHourMixin):
- """
- DateOffset subclass representing possibly n business hours.
- """
-
- _prefix = "BH"
- _anchor = 0
- _attributes = frozenset(["n", "normalize", "start", "end", "offset"])
-
- @cache_readonly
- def next_bday(self):
- """
- Used for moving to next business day.
- """
- if self.n >= 0:
- nb_offset = 1
- else:
- nb_offset = -1
- if self._prefix.startswith("C"):
- # CustomBusinessHour
- return CustomBusinessDay(
- n=nb_offset,
- weekmask=self.weekmask,
- holidays=self.holidays,
- calendar=self.calendar,
- )
- else:
- return BusinessDay(n=nb_offset)
-
- def _next_opening_time(self, other, sign=1):
- """
- If self.n and sign have the same sign, return the earliest opening time
- later than or equal to current time.
- Otherwise the latest opening time earlier than or equal to current
- time.
-
- Opening time always locates on BusinessDay.
- However, closing time may not if business hour extends over midnight.
-
- Parameters
- ----------
- other : datetime
- Current time.
- sign : int, default 1.
- Either 1 or -1. Going forward in time if it has the same sign as
- self.n. Going backward in time otherwise.
-
- Returns
- -------
- result : datetime
- Next opening time.
- """
- earliest_start = self.start[0]
- latest_start = self.start[-1]
-
- if not self.next_bday.is_on_offset(other):
- # today is not business day
- other = other + sign * self.next_bday
- if self.n * sign >= 0:
- hour, minute = earliest_start.hour, earliest_start.minute
- else:
- hour, minute = latest_start.hour, latest_start.minute
- else:
- if self.n * sign >= 0:
- if latest_start < other.time():
- # current time is after latest starting time in today
- other = other + sign * self.next_bday
- hour, minute = earliest_start.hour, earliest_start.minute
- else:
- # find earliest starting time no earlier than current time
- for st in self.start:
- if other.time() <= st:
- hour, minute = st.hour, st.minute
- break
- else:
- if other.time() < earliest_start:
- # current time is before earliest starting time in today
- other = other + sign * self.next_bday
- hour, minute = latest_start.hour, latest_start.minute
- else:
- # find latest starting time no later than current time
- for st in reversed(self.start):
- if other.time() >= st:
- hour, minute = st.hour, st.minute
- break
-
- return datetime(other.year, other.month, other.day, hour, minute)
-
- def _prev_opening_time(self, other):
- """
- If n is positive, return the latest opening time earlier than or equal
- to current time.
- Otherwise the earliest opening time later than or equal to current
- time.
-
- Parameters
- ----------
- other : datetime
- Current time.
-
- Returns
- -------
- result : datetime
- Previous opening time.
- """
- return self._next_opening_time(other, sign=-1)
-
- @apply_wraps
- def rollback(self, dt):
- """
- Roll provided date backward to next offset only if not on offset.
- """
- if not self.is_on_offset(dt):
- if self.n >= 0:
- dt = self._prev_opening_time(dt)
- else:
- dt = self._next_opening_time(dt)
- return self._get_closing_time(dt)
- return dt
-
- @apply_wraps
- def rollforward(self, dt):
- """
- Roll provided date forward to next offset only if not on offset.
- """
- if not self.is_on_offset(dt):
- if self.n >= 0:
- return self._next_opening_time(dt)
- else:
- return self._prev_opening_time(dt)
- return dt
-
- @apply_wraps
- def apply(self, other):
- if isinstance(other, datetime):
- # used for detecting edge condition
- nanosecond = getattr(other, "nanosecond", 0)
- # reset timezone and nanosecond
- # other may be a Timestamp, thus not use replace
- other = datetime(
- other.year,
- other.month,
- other.day,
- other.hour,
- other.minute,
- other.second,
- other.microsecond,
- )
- n = self.n
-
- # adjust other to reduce number of cases to handle
- if n >= 0:
- if other.time() in self.end or not self._is_on_offset(other):
- other = self._next_opening_time(other)
- else:
- if other.time() in self.start:
- # adjustment to move to previous business day
- other = other - timedelta(seconds=1)
- if not self._is_on_offset(other):
- other = self._next_opening_time(other)
- other = self._get_closing_time(other)
-
- # get total business hours by sec in one business day
- businesshours = sum(
- self._get_business_hours_by_sec(st, en)
- for st, en in zip(self.start, self.end)
- )
-
- bd, r = divmod(abs(n * 60), businesshours // 60)
- if n < 0:
- bd, r = -bd, -r
-
- # adjust by business days first
- if bd != 0:
- if isinstance(self, CustomMixin): # GH 30593
- skip_bd = CustomBusinessDay(
- n=bd,
- weekmask=self.weekmask,
- holidays=self.holidays,
- calendar=self.calendar,
- )
- else:
- skip_bd = BusinessDay(n=bd)
- # midnight business hour may not on BusinessDay
- if not self.next_bday.is_on_offset(other):
- prev_open = self._prev_opening_time(other)
- remain = other - prev_open
- other = prev_open + skip_bd + remain
- else:
- other = other + skip_bd
-
- # remaining business hours to adjust
- bhour_remain = timedelta(minutes=r)
-
- if n >= 0:
- while bhour_remain != timedelta(0):
- # business hour left in this business time interval
- bhour = (
- self._get_closing_time(self._prev_opening_time(other)) - other
- )
- if bhour_remain < bhour:
- # finish adjusting if possible
- other += bhour_remain
- bhour_remain = timedelta(0)
- else:
- # go to next business time interval
- bhour_remain -= bhour
- other = self._next_opening_time(other + bhour)
- else:
- while bhour_remain != timedelta(0):
- # business hour left in this business time interval
- bhour = self._next_opening_time(other) - other
- if (
- bhour_remain > bhour
- or bhour_remain == bhour
- and nanosecond != 0
- ):
- # finish adjusting if possible
- other += bhour_remain
- bhour_remain = timedelta(0)
- else:
- # go to next business time interval
- bhour_remain -= bhour
- other = self._get_closing_time(
- self._next_opening_time(
- other + bhour - timedelta(seconds=1)
- )
- )
-
- return other
- else:
- raise ApplyTypeError("Only know how to combine business hour with datetime")
-
- def is_on_offset(self, dt):
- if self.normalize and not is_normalized(dt):
- return False
-
- if dt.tzinfo is not None:
- dt = datetime(
- dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond
- )
- # Valid BH can be on the different BusinessDay during midnight
- # Distinguish by the time spent from previous opening time
- return self._is_on_offset(dt)
-
- def _is_on_offset(self, dt):
- """
- Slight speedups using calculated values.
- """
- # if self.normalize and not is_normalized(dt):
- # return False
- # Valid BH can be on the different BusinessDay during midnight
- # Distinguish by the time spent from previous opening time
- if self.n >= 0:
- op = self._prev_opening_time(dt)
- else:
- op = self._next_opening_time(dt)
- span = (dt - op).total_seconds()
- businesshours = 0
- for i, st in enumerate(self.start):
- if op.hour == st.hour and op.minute == st.minute:
- businesshours = self._get_business_hours_by_sec(st, self.end[i])
- if span <= businesshours:
- return True
- else:
- return False
-
-
class CustomBusinessDay(CustomMixin, BusinessDay):
"""
DateOffset subclass representing custom business days excluding holidays.
@@ -624,6 +247,11 @@ def __init__(
BusinessDay.__init__(self, n, normalize, offset)
CustomMixin.__init__(self, weekmask, holidays, calendar)
+ def __setstate__(self, state):
+ self.holidays = state.pop("holidays")
+ self.weekmask = state.pop("weekmask")
+ super().__setstate__(state)
+
@apply_wraps
def apply(self, other):
if self.n <= 0:
| https://api.github.com/repos/pandas-dev/pandas/pulls/34391 | 2020-05-26T18:04:15Z | 2020-05-26T22:14:43Z | 2020-05-26T22:14:43Z | 2020-05-26T22:20:16Z | |
DOC: Fix docstring for read_sql_table | diff --git a/pandas/io/sql.py b/pandas/io/sql.py
index aaface5415384..02fba52eac7f7 100644
--- a/pandas/io/sql.py
+++ b/pandas/io/sql.py
@@ -182,26 +182,29 @@ def execute(sql, con, cur=None, params=None):
def read_sql_table(table_name, con, schema=None, index_col=None,
coerce_float=True, parse_dates=None, columns=None,
chunksize=None):
- """Read SQL database table into a DataFrame.
+ """
+ Read SQL database table into a DataFrame.
Given a table name and a SQLAlchemy connectable, returns a DataFrame.
This function does not support DBAPI connections.
Parameters
----------
- table_name : string
+ table_name : str
Name of SQL table in database.
- con : SQLAlchemy connectable (or database string URI)
+ con : SQLAlchemy connectable or str
+ A database URI could be provided as as str.
SQLite DBAPI connection mode not supported.
- schema : string, default None
+ schema : str, default None
Name of SQL schema in database to query (if database flavor
supports this). Uses default schema if None (default).
- index_col : string or list of strings, optional, default: None
+ index_col : str or list of str, 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. Can result in loss of Precision.
- parse_dates : list or dict, default: None
+ parse_dates : list or dict, default None
+ The behavior is as follows:
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times or is one of
@@ -210,8 +213,8 @@ def read_sql_table(table_name, con, schema=None, index_col=None,
to the keyword arguments of :func:`pandas.to_datetime`
Especially useful with databases without native Datetime support,
such as SQLite.
- columns : list, default: None
- List of column names to select from SQL table
+ columns : list, default None
+ List of column names to select from SQL table.
chunksize : int, default None
If specified, returns an iterator where `chunksize` is the number of
rows to include in each chunk.
@@ -219,15 +222,21 @@ def read_sql_table(table_name, con, schema=None, index_col=None,
Returns
-------
DataFrame
+ A SQL table is returned as two-dimensional data structure with labeled
+ axes.
See Also
--------
read_sql_query : Read SQL query into a DataFrame.
- read_sql
+ read_sql : Read SQL query or database table into a DataFrame.
Notes
-----
Any datetime values with time zone information will be converted to UTC.
+
+ Examples
+ --------
+ >>> pd.read_sql_table('table_name', 'postgres:///db_name') # doctest:+SKIP
"""
con = _engine_builder(con)
| - [ ] closes #xxxx
- [ ] tests added / passed
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
```
################################################################################
###################### Docstring (pandas.read_sql_table) ######################
################################################################################
Read SQL database table into a DataFrame.
Given a table name and a SQLAlchemy connectable, returns a DataFrame.
This function does not support DBAPI connections.
Parameters
----------
table_name : str
Name of SQL table in database.
con : SQLAlchemy connectable or database URI str
SQLite DBAPI connection mode not supported.
schema : str, default None
Name of SQL schema in database to query (if database flavor
supports this). Uses default schema if None (default).
index_col : str or list of str, 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
decimal.Decimal) to floating point. Can result in loss of Precision.
parse_dates : list or dict, default None
The behavior is as follows:
- List of column names to parse as dates.
- Dict of ``{column_name: format string}`` where format string is
strftime compatible in case of parsing string times or is one of
(D, s, ns, ms, us) in case of parsing integer timestamps.
- Dict of ``{column_name: arg dict}``, where the arg dict corresponds
to the keyword arguments of :func:`pandas.to_datetime`
Especially useful with databases without native Datetime support,
such as SQLite.
columns : list, default None
List of column names to select from SQL table.
chunksize : int, default None
If specified, returns an iterator where `chunksize` is the number of
rows to include in each chunk.
Returns
-------
DataFrame
A SQL table is returned as two-dimensional data structure with labeled
axes.
See Also
--------
read_sql_query : Read SQL query into a DataFrame.
read_sql : Read SQL query or database table into a DataFrame.
Notes
-----
Any datetime values with time zone information will be converted to UTC.
Examples
--------
>>> pd.read_sql_table('table_name', 'postgres:///db_name') # doctest:+SKIP
################################################################################
################################## Validation ##################################
################################################################################
Docstring for "pandas.read_sql_table" correct. :)
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/25465 | 2019-02-27T20:56:36Z | 2019-02-28T20:00:31Z | 2019-02-28T20:00:31Z | 2019-03-01T10:14:40Z |
Remove return values for asserts | diff --git a/pandas/tests/arrays/test_integer.py b/pandas/tests/arrays/test_integer.py
index b88ba1cf01426..759dacd7f221e 100644
--- a/pandas/tests/arrays/test_integer.py
+++ b/pandas/tests/arrays/test_integer.py
@@ -159,7 +159,7 @@ def _check_op(self, s, op_name, other, exc=None):
# integer result type
else:
- rs = pd.Series(s.values._data)
+ rs = pd.Series(s.values._data, name=s.name)
expected = op(rs, other)
self._check_op_integer(result, expected, mask, s, op_name, other)
diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py
index 19e42b4621b3a..a22210268e5aa 100644
--- a/pandas/tests/indexes/interval/test_interval.py
+++ b/pandas/tests/indexes/interval/test_interval.py
@@ -566,12 +566,12 @@ def test_get_loc_datetimelike_overlapping(self, arrays):
value = index[0].mid + Timedelta('12 hours')
result = np.sort(index.get_loc(value))
expected = np.array([0, 1], dtype='intp')
- assert tm.assert_numpy_array_equal(result, expected)
+ tm.assert_numpy_array_equal(result, expected)
interval = Interval(index[0].left, index[1].right)
result = np.sort(index.get_loc(interval))
expected = np.array([0, 1, 2], dtype='intp')
- assert tm.assert_numpy_array_equal(result, expected)
+ tm.assert_numpy_array_equal(result, expected)
# To be removed, replaced by test_interval_new.py (see #16316, #16386)
def test_get_indexer(self):
diff --git a/pandas/tests/io/parser/test_textreader.py b/pandas/tests/io/parser/test_textreader.py
index eb3789bb72910..2177d6bb93108 100644
--- a/pandas/tests/io/parser/test_textreader.py
+++ b/pandas/tests/io/parser/test_textreader.py
@@ -345,5 +345,5 @@ def test_empty_csv_input(self):
def assert_array_dicts_equal(left, right):
for k, v in left.items():
- assert tm.assert_numpy_array_equal(np.asarray(v),
- np.asarray(right[k]))
+ tm.assert_numpy_array_equal(np.asarray(v),
+ np.asarray(right[k]))
diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py
index 76ac5353c5916..c91233e9317b7 100644
--- a/pandas/tests/reductions/test_reductions.py
+++ b/pandas/tests/reductions/test_reductions.py
@@ -147,7 +147,7 @@ def test_same_tz_min_max_axis_1(self, op, expected_col):
columns=['a'])
df['b'] = df.a.subtract(pd.Timedelta(seconds=3600))
result = getattr(df, op)(axis=1)
- expected = df[expected_col]
+ expected = df[expected_col].rename(None)
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index 5376cb3696012..fd90a87c553c4 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -1058,7 +1058,7 @@ def test_fromDict(self):
data = {'a': 0, 'b': 1, 'c': 2, 'd': 3}
series = Series(data)
- assert tm.is_sorted(series.index)
+ tm.assert_is_sorted(series.index)
data = {'a': 0, 'b': '1', 'c': '2', 'd': datetime.now()}
series = Series(data)
diff --git a/pandas/tests/tools/test_numeric.py b/pandas/tests/tools/test_numeric.py
index ee2c2c0c3cdfa..5d3903cb93bd5 100644
--- a/pandas/tests/tools/test_numeric.py
+++ b/pandas/tests/tools/test_numeric.py
@@ -240,7 +240,7 @@ def test_really_large_scalar(large_val, signed, transform, errors):
else:
expected = float(val) if (errors == "coerce" and
val_is_string) else val
- assert tm.assert_almost_equal(to_numeric(val, **kwargs), expected)
+ tm.assert_almost_equal(to_numeric(val, **kwargs), expected)
def test_really_large_in_arr(large_val, signed, transform,
diff --git a/pandas/util/testing.py b/pandas/util/testing.py
index 70c06efa30fee..5ef68dcefdf8b 100644
--- a/pandas/util/testing.py
+++ b/pandas/util/testing.py
@@ -281,25 +281,25 @@ def assert_almost_equal(left, right, check_dtype="equiv",
"""
if isinstance(left, pd.Index):
- return assert_index_equal(left, right,
- check_exact=False,
- exact=check_dtype,
- check_less_precise=check_less_precise,
- **kwargs)
+ assert_index_equal(left, right,
+ check_exact=False,
+ exact=check_dtype,
+ check_less_precise=check_less_precise,
+ **kwargs)
elif isinstance(left, pd.Series):
- return assert_series_equal(left, right,
- check_exact=False,
- check_dtype=check_dtype,
- check_less_precise=check_less_precise,
- **kwargs)
+ assert_series_equal(left, right,
+ check_exact=False,
+ check_dtype=check_dtype,
+ check_less_precise=check_less_precise,
+ **kwargs)
elif isinstance(left, pd.DataFrame):
- return assert_frame_equal(left, right,
- check_exact=False,
- check_dtype=check_dtype,
- check_less_precise=check_less_precise,
- **kwargs)
+ assert_frame_equal(left, right,
+ check_exact=False,
+ check_dtype=check_dtype,
+ check_less_precise=check_less_precise,
+ **kwargs)
else:
# Other sequences.
@@ -317,7 +317,7 @@ def assert_almost_equal(left, right, check_dtype="equiv",
else:
obj = "Input"
assert_class_equal(left, right, obj=obj)
- return _testing.assert_almost_equal(
+ _testing.assert_almost_equal(
left, right,
check_dtype=check_dtype,
check_less_precise=check_less_precise,
@@ -355,7 +355,7 @@ def _check_isinstance(left, right, cls):
def assert_dict_equal(left, right, compare_keys=True):
_check_isinstance(left, right, dict)
- return _testing.assert_dict_equal(left, right, compare_keys=compare_keys)
+ _testing.assert_dict_equal(left, right, compare_keys=compare_keys)
def randbool(size=(), p=0.5):
@@ -717,11 +717,12 @@ def isiterable(obj):
return hasattr(obj, '__iter__')
-def is_sorted(seq):
+def assert_is_sorted(seq):
+ """Assert that the sequence is sorted."""
if isinstance(seq, (Index, Series)):
seq = seq.values
# sorting does not change precisions
- return assert_numpy_array_equal(seq, np.sort(np.array(seq)))
+ assert_numpy_array_equal(seq, np.sort(np.array(seq)))
def assert_categorical_equal(left, right, check_dtype=True,
@@ -911,8 +912,6 @@ def _raise(left, right, err_msg):
if isinstance(left, np.ndarray) and isinstance(right, np.ndarray):
assert_attr_equal('dtype', left, right, obj=obj)
- return True
-
def assert_extension_array_equal(left, right, check_dtype=True,
check_less_precise=False,
@@ -1073,12 +1072,10 @@ def assert_series_equal(left, right, check_dtype=True,
# .values is an ndarray, but ._values is the ExtensionArray.
# TODO: Use .array
assert is_extension_array_dtype(right.dtype)
- return assert_extension_array_equal(left._values, right._values)
-
+ assert_extension_array_equal(left._values, right._values)
elif (is_extension_array_dtype(left) and not is_categorical_dtype(left) and
is_extension_array_dtype(right) and not is_categorical_dtype(right)):
- return assert_extension_array_equal(left.array, right.array)
-
+ assert_extension_array_equal(left.array, right.array)
else:
_testing.assert_almost_equal(left.get_values(), right.get_values(),
check_less_precise=check_less_precise,
| Unless they are context managers.
- [X] closes #25135
- [X] tests added / passed (not applicable)
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25462 | 2019-02-27T18:54:51Z | 2019-05-07T00:56:44Z | 2019-05-07T00:56:44Z | 2019-05-07T01:00:36Z |
Fix minor typo | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index eb84a9a5810f4..523543ada235c 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1815,7 +1815,7 @@ def __hash__(self):
' hashed'.format(self.__class__.__name__))
def __iter__(self):
- """Iterate over infor axis"""
+ """Iterate over info axis"""
return iter(self._info_axis)
# can we get a better explanation of this?
| Signed-off-by: Philippe Ombredanne <pombredanne@nexb.com>
| https://api.github.com/repos/pandas-dev/pandas/pulls/25458 | 2019-02-27T10:06:04Z | 2019-02-28T12:45:16Z | 2019-02-28T12:45:16Z | 2019-02-28T14:13:58Z |
CI: add __init__.py to isort skip list | diff --git a/ci/deps/azure-27-compat.yaml b/ci/deps/azure-27-compat.yaml
index 986855c464852..c68b51fbd6644 100644
--- a/ci/deps/azure-27-compat.yaml
+++ b/ci/deps/azure-27-compat.yaml
@@ -21,6 +21,7 @@ dependencies:
- pytest
- pytest-xdist
- pytest-mock
+ - isort
- pip:
- html5lib==1.0b2
- beautifulsoup4==4.2.1
diff --git a/ci/deps/azure-27-locale.yaml b/ci/deps/azure-27-locale.yaml
index f73079ecbe3d2..5679c503caddc 100644
--- a/ci/deps/azure-27-locale.yaml
+++ b/ci/deps/azure-27-locale.yaml
@@ -24,6 +24,7 @@ dependencies:
- pytest-xdist
- pytest-mock
- hypothesis>=3.58.0
+ - isort
- pip:
- html5lib==1.0b2
- beautifulsoup4==4.2.1
diff --git a/ci/deps/azure-36-locale_slow.yaml b/ci/deps/azure-36-locale_slow.yaml
index 6b8d38fd25082..de1f4ad0e9a76 100644
--- a/ci/deps/azure-36-locale_slow.yaml
+++ b/ci/deps/azure-36-locale_slow.yaml
@@ -30,5 +30,6 @@ dependencies:
- pytest-xdist
- pytest-mock
- moto
+ - isort
- pip:
- hypothesis>=3.58.0
diff --git a/ci/deps/azure-37-locale.yaml b/ci/deps/azure-37-locale.yaml
index 569b71dae003b..a89e63a2b7d3a 100644
--- a/ci/deps/azure-37-locale.yaml
+++ b/ci/deps/azure-37-locale.yaml
@@ -28,6 +28,7 @@ dependencies:
- pytest
- pytest-xdist
- pytest-mock
+ - isort
- pip:
- hypothesis>=3.58.0
- moto # latest moto in conda-forge fails with 3.7, move to conda dependencies when this is fixed
diff --git a/ci/deps/azure-37-numpydev.yaml b/ci/deps/azure-37-numpydev.yaml
index a37be124cc546..3132de891299c 100644
--- a/ci/deps/azure-37-numpydev.yaml
+++ b/ci/deps/azure-37-numpydev.yaml
@@ -10,6 +10,7 @@ dependencies:
- pytest-xdist
- pytest-mock
- hypothesis>=3.58.0
+ - isort
- pip:
- "git+git://github.com/dateutil/dateutil.git"
- "-f https://7933911d6844c6c53a7d-47bd50c35cd79bd838daf386af554a83.ssl.cf2.rackcdn.com"
diff --git a/ci/deps/azure-macos-35.yaml b/ci/deps/azure-macos-35.yaml
index d1fe926744ecd..9710bcb5bf43d 100644
--- a/ci/deps/azure-macos-35.yaml
+++ b/ci/deps/azure-macos-35.yaml
@@ -25,6 +25,7 @@ dependencies:
- pytest
- pytest-xdist
- pytest-mock
+ - isort
- pip:
- python-dateutil==2.5.3
- hypothesis>=3.58.0
diff --git a/ci/deps/azure-windows-27.yaml b/ci/deps/azure-windows-27.yaml
index 74faeed83c387..093c055e69553 100644
--- a/ci/deps/azure-windows-27.yaml
+++ b/ci/deps/azure-windows-27.yaml
@@ -30,3 +30,4 @@ dependencies:
- pytest-mock
- moto
- hypothesis>=3.58.0
+ - isort
diff --git a/ci/deps/azure-windows-36.yaml b/ci/deps/azure-windows-36.yaml
index 94d67b3d37788..e9db271a75d9d 100644
--- a/ci/deps/azure-windows-36.yaml
+++ b/ci/deps/azure-windows-36.yaml
@@ -27,3 +27,4 @@ dependencies:
- pytest-xdist
- pytest-mock
- hypothesis>=3.58.0
+ - isort
diff --git a/ci/deps/travis-27.yaml b/ci/deps/travis-27.yaml
index 4915c003bce4e..71b224b2c68c2 100644
--- a/ci/deps/travis-27.yaml
+++ b/ci/deps/travis-27.yaml
@@ -44,6 +44,7 @@ dependencies:
- pytest-mock
- moto==1.3.4
- hypothesis>=3.58.0
+ - isort
- pip:
- backports.lzma
- pandas-gbq
diff --git a/ci/deps/travis-36-doc.yaml b/ci/deps/travis-36-doc.yaml
index 26f3a17432ab2..1a65d292ef085 100644
--- a/ci/deps/travis-36-doc.yaml
+++ b/ci/deps/travis-36-doc.yaml
@@ -43,3 +43,4 @@ dependencies:
# universal
- pytest
- pytest-xdist
+ - isort
diff --git a/ci/deps/travis-36-locale.yaml b/ci/deps/travis-36-locale.yaml
index 2a7692f10752c..36dbb8013104a 100644
--- a/ci/deps/travis-36-locale.yaml
+++ b/ci/deps/travis-36-locale.yaml
@@ -32,5 +32,6 @@ dependencies:
- pytest-xdist
- pytest-mock
- moto
+ - isort
- pip:
- hypothesis>=3.58.0
diff --git a/ci/deps/travis-36-slow.yaml b/ci/deps/travis-36-slow.yaml
index 7934d179c8618..f4b9091c4300b 100644
--- a/ci/deps/travis-36-slow.yaml
+++ b/ci/deps/travis-36-slow.yaml
@@ -30,3 +30,4 @@ dependencies:
- pytest-mock
- moto
- hypothesis>=3.58.0
+ - isort
diff --git a/ci/deps/travis-36.yaml b/ci/deps/travis-36.yaml
index 857c3fadfdaeb..e22529784b5ec 100644
--- a/ci/deps/travis-36.yaml
+++ b/ci/deps/travis-36.yaml
@@ -38,6 +38,7 @@ dependencies:
- pytest-cov
- pytest-mock
- hypothesis>=3.58.0
+ - isort
- pip:
- brotlipy
- coverage
diff --git a/ci/deps/travis-37.yaml b/ci/deps/travis-37.yaml
index 125750191de7d..a8a5df5894ba5 100644
--- a/ci/deps/travis-37.yaml
+++ b/ci/deps/travis-37.yaml
@@ -17,5 +17,6 @@ dependencies:
- pytest-mock
- hypothesis>=3.58.0
- s3fs
+ - isort
- pip:
- moto
diff --git a/setup.cfg b/setup.cfg
index b15c3ce8a110a..956aa23839e73 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -152,3 +152,23 @@ skip=
asv_bench/benchmarks/dtypes.py
asv_bench/benchmarks/strings.py
asv_bench/benchmarks/period.py
+ pandas/__init__.py
+ pandas/plotting/__init__.py
+ pandas/tests/extension/decimal/__init__.py
+ pandas/tests/extension/base/__init__.py
+ pandas/io/msgpack/__init__.py
+ pandas/io/json/__init__.py
+ pandas/io/clipboard/__init__.py
+ pandas/io/excel/__init__.py
+ pandas/compat/__init__.py
+ pandas/compat/numpy/__init__.py
+ pandas/core/arrays/__init__.py
+ pandas/core/groupby/__init__.py
+ pandas/core/internals/__init__.py
+ pandas/api/__init__.py
+ pandas/api/extensions/__init__.py
+ pandas/api/types/__init__.py
+ pandas/_libs/__init__.py
+ pandas/_libs/tslibs/__init__.py
+ pandas/util/__init__.py
+ pandas/arrays/__init__.py
| 4.3.5 - February 24, 2019 - last Python 2.7 Maintenance Release
This is the final Python 2.x release of isort, and includes the following major changes:
Potentially Interface Breaking:
The -r option for removing imports has been renamed -rm to avoid accidental deletions and confusion with the -rc recursive option.
__init__.py has been removed from the default ignore list. The default ignore list is now empty - with all items needing to be explicitly ignored.... | https://api.github.com/repos/pandas-dev/pandas/pulls/25455 | 2019-02-26T19:56:42Z | 2019-02-27T22:26:54Z | 2019-02-27T22:26:54Z | 2019-03-12T09:17:12Z |
STY: use pytest.raises context manager (tests/test_*) | diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index cb7426ce2f7c9..c56bf944699e2 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -11,7 +11,7 @@
from pandas._libs import (
algos as libalgos, groupby as libgroupby, hashtable as ht)
-from pandas.compat import lrange, range
+from pandas.compat import PY2, lrange, range
from pandas.compat.numpy import np_array_datetime64_compat
import pandas.util._test_decorators as td
@@ -224,11 +224,16 @@ def test_factorize_tuple_list(self, data, expected_label, expected_level):
dtype=object)
tm.assert_numpy_array_equal(result[1], expected_level_array)
+ @pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
def test_complex_sorting(self):
# gh 12666 - check no segfault
x17 = np.array([complex(i) for i in range(17)], dtype=object)
- pytest.raises(TypeError, algos.factorize, x17[::-1], sort=True)
+ msg = ("'<' not supported between instances of 'complex' and"
+ r" 'complex'|"
+ r"unorderable types: complex\(\) > complex\(\)")
+ with pytest.raises(TypeError, match=msg):
+ algos.factorize(x17[::-1], sort=True)
def test_float64_factorize(self, writable):
data = np.array([1.0, 1e8, 1.0, 1e-8, 1e8, 1.0], dtype=np.float64)
@@ -589,9 +594,14 @@ class TestIsin(object):
def test_invalid(self):
- pytest.raises(TypeError, lambda: algos.isin(1, 1))
- pytest.raises(TypeError, lambda: algos.isin(1, [1]))
- pytest.raises(TypeError, lambda: algos.isin([1], 1))
+ msg = (r"only list-like objects are allowed to be passed to isin\(\),"
+ r" you passed a \[int\]")
+ with pytest.raises(TypeError, match=msg):
+ algos.isin(1, 1)
+ with pytest.raises(TypeError, match=msg):
+ algos.isin(1, [1])
+ with pytest.raises(TypeError, match=msg):
+ algos.isin([1], 1)
def test_basic(self):
@@ -819,8 +829,9 @@ def test_value_counts_dtypes(self):
result = algos.value_counts(Series([1, 1., '1'])) # object
assert len(result) == 2
- pytest.raises(TypeError, lambda s: algos.value_counts(s, bins=1),
- ['1', 1])
+ msg = "bins argument only works with numeric data"
+ with pytest.raises(TypeError, match=msg):
+ algos.value_counts(['1', 1], bins=1)
def test_value_counts_nat(self):
td = Series([np.timedelta64(10000), pd.NaT], dtype='timedelta64[ns]')
diff --git a/pandas/tests/test_config.py b/pandas/tests/test_config.py
index 54db3887850ea..baca66e0361ad 100644
--- a/pandas/tests/test_config.py
+++ b/pandas/tests/test_config.py
@@ -3,7 +3,10 @@
import pytest
+from pandas.compat import PY2
+
import pandas as pd
+from pandas.core.config import OptionError
class TestConfig(object):
@@ -48,26 +51,35 @@ def test_is_one_of_factory(self):
v(12)
v(None)
- pytest.raises(ValueError, v, 1.1)
+ msg = r"Value must be one of None\|12"
+ with pytest.raises(ValueError, match=msg):
+ v(1.1)
def test_register_option(self):
self.cf.register_option('a', 1, 'doc')
# can't register an already registered option
- pytest.raises(KeyError, self.cf.register_option, 'a', 1, 'doc')
+ msg = "Option 'a' has already been registered"
+ with pytest.raises(OptionError, match=msg):
+ self.cf.register_option('a', 1, 'doc')
# can't register an already registered option
- pytest.raises(KeyError, self.cf.register_option, 'a.b.c.d1', 1,
- 'doc')
- pytest.raises(KeyError, self.cf.register_option, 'a.b.c.d2', 1,
- 'doc')
+ msg = "Path prefix to option 'a' is already an option"
+ with pytest.raises(OptionError, match=msg):
+ self.cf.register_option('a.b.c.d1', 1, 'doc')
+ with pytest.raises(OptionError, match=msg):
+ self.cf.register_option('a.b.c.d2', 1, 'doc')
# no python keywords
- pytest.raises(ValueError, self.cf.register_option, 'for', 0)
- pytest.raises(ValueError, self.cf.register_option, 'a.for.b', 0)
+ msg = "for is a python keyword"
+ with pytest.raises(ValueError, match=msg):
+ self.cf.register_option('for', 0)
+ with pytest.raises(ValueError, match=msg):
+ self.cf.register_option('a.for.b', 0)
# must be valid identifier (ensure attribute access works)
- pytest.raises(ValueError, self.cf.register_option,
- 'Oh my Goddess!', 0)
+ msg = "oh my goddess! is not a valid identifier"
+ with pytest.raises(ValueError, match=msg):
+ self.cf.register_option('Oh my Goddess!', 0)
# we can register options several levels deep
# without predefining the intermediate steps
@@ -90,7 +102,9 @@ def test_describe_option(self):
self.cf.register_option('l', "foo")
# non-existent keys raise KeyError
- pytest.raises(KeyError, self.cf.describe_option, 'no.such.key')
+ msg = r"No such keys\(s\)"
+ with pytest.raises(OptionError, match=msg):
+ self.cf.describe_option('no.such.key')
# we can get the description for any key we registered
assert 'doc' in self.cf.describe_option('a', _print_desc=False)
@@ -122,7 +136,9 @@ def test_case_insensitive(self):
assert self.cf.get_option('kAnBaN') == 2
# gets of non-existent keys fail
- pytest.raises(KeyError, self.cf.get_option, 'no_such_option')
+ msg = r"No such keys\(s\): 'no_such_option'"
+ with pytest.raises(OptionError, match=msg):
+ self.cf.get_option('no_such_option')
self.cf.deprecate_option('KanBan')
assert self.cf._is_deprecated('kAnBaN')
@@ -138,7 +154,9 @@ def test_get_option(self):
assert self.cf.get_option('b.b') is None
# gets of non-existent keys fail
- pytest.raises(KeyError, self.cf.get_option, 'no_such_option')
+ msg = r"No such keys\(s\): 'no_such_option'"
+ with pytest.raises(OptionError, match=msg):
+ self.cf.get_option('no_such_option')
def test_set_option(self):
self.cf.register_option('a', 1, 'doc')
@@ -157,16 +175,24 @@ def test_set_option(self):
assert self.cf.get_option('b.c') == 'wurld'
assert self.cf.get_option('b.b') == 1.1
- pytest.raises(KeyError, self.cf.set_option, 'no.such.key', None)
+ msg = r"No such keys\(s\): 'no.such.key'"
+ with pytest.raises(OptionError, match=msg):
+ self.cf.set_option('no.such.key', None)
def test_set_option_empty_args(self):
- pytest.raises(ValueError, self.cf.set_option)
+ msg = "Must provide an even number of non-keyword arguments"
+ with pytest.raises(ValueError, match=msg):
+ self.cf.set_option()
def test_set_option_uneven_args(self):
- pytest.raises(ValueError, self.cf.set_option, 'a.b', 2, 'b.c')
+ msg = "Must provide an even number of non-keyword arguments"
+ with pytest.raises(ValueError, match=msg):
+ self.cf.set_option('a.b', 2, 'b.c')
def test_set_option_invalid_single_argument_type(self):
- pytest.raises(ValueError, self.cf.set_option, 2)
+ msg = "Must provide an even number of non-keyword arguments"
+ with pytest.raises(ValueError, match=msg):
+ self.cf.set_option(2)
def test_set_option_multiple(self):
self.cf.register_option('a', 1, 'doc')
@@ -183,27 +209,36 @@ def test_set_option_multiple(self):
assert self.cf.get_option('b.c') is None
assert self.cf.get_option('b.b') == 10.0
+ @pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
def test_validation(self):
self.cf.register_option('a', 1, 'doc', validator=self.cf.is_int)
self.cf.register_option('b.c', 'hullo', 'doc2',
validator=self.cf.is_text)
- pytest.raises(ValueError, self.cf.register_option, 'a.b.c.d2',
- 'NO', 'doc', validator=self.cf.is_int)
+ msg = "Value must have type '<class 'int'>'"
+ with pytest.raises(ValueError, match=msg):
+ self.cf.register_option(
+ 'a.b.c.d2', 'NO', 'doc', validator=self.cf.is_int)
self.cf.set_option('a', 2) # int is_int
self.cf.set_option('b.c', 'wurld') # str is_str
- pytest.raises(
- ValueError, self.cf.set_option, 'a', None) # None not is_int
- pytest.raises(ValueError, self.cf.set_option, 'a', 'ab')
- pytest.raises(ValueError, self.cf.set_option, 'b.c', 1)
+ # None not is_int
+ with pytest.raises(ValueError, match=msg):
+ self.cf.set_option('a', None)
+ with pytest.raises(ValueError, match=msg):
+ self.cf.set_option('a', 'ab')
+
+ msg = r"Value must be an instance of <class 'str'>\|<class 'bytes'>"
+ with pytest.raises(ValueError, match=msg):
+ self.cf.set_option('b.c', 1)
validator = self.cf.is_one_of_factory([None, self.cf.is_callable])
self.cf.register_option('b', lambda: None, 'doc',
validator=validator)
self.cf.set_option('b', '%.1f'.format) # Formatter is callable
self.cf.set_option('b', None) # Formatter is none (default)
- pytest.raises(ValueError, self.cf.set_option, 'b', '%.1f')
+ with pytest.raises(ValueError, match="Value must be a callable"):
+ self.cf.set_option('b', '%.1f')
def test_reset_option(self):
self.cf.register_option('a', 1, 'doc', validator=self.cf.is_int)
@@ -267,8 +302,9 @@ def test_deprecate_option(self):
assert 'eprecated' in str(w[-1]) # we get the default message
assert 'nifty_ver' in str(w[-1]) # with the removal_ver quoted
- pytest.raises(
- KeyError, self.cf.deprecate_option, 'a') # can't depr. twice
+ msg = "Option 'a' has already been defined as deprecated"
+ with pytest.raises(OptionError, match=msg):
+ self.cf.deprecate_option('a')
self.cf.deprecate_option('b.c', 'zounds!')
with warnings.catch_warnings(record=True) as w:
@@ -374,12 +410,6 @@ def eq(val):
def test_attribute_access(self):
holder = []
- def f():
- options.b = 1
-
- def f2():
- options.display = 1
-
def f3(key):
holder.append(True)
@@ -397,8 +427,11 @@ def f3(key):
self.cf.reset_option("a")
assert options.a == self.cf.get_option("a", 0)
- pytest.raises(KeyError, f)
- pytest.raises(KeyError, f2)
+ msg = "You can only set the value of existing options"
+ with pytest.raises(OptionError, match=msg):
+ options.b = 1
+ with pytest.raises(OptionError, match=msg):
+ options.display = 1
# make sure callback kicks when using this form of setting
options.c = 1
@@ -429,5 +462,6 @@ def test_option_context_scope(self):
def test_dictwrapper_getattr(self):
options = self.cf.options
# GH 19789
- pytest.raises(self.cf.OptionError, getattr, options, 'bananas')
+ with pytest.raises(OptionError, match="No such option"):
+ options.bananas
assert not hasattr(options, 'bananas')
diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py
index 4ea7e9b8ec9a4..a9a59c6d95373 100644
--- a/pandas/tests/test_multilevel.py
+++ b/pandas/tests/test_multilevel.py
@@ -886,8 +886,11 @@ def test_count(self):
tm.assert_series_equal(result, expect, check_names=False)
assert result.index.name == 'a'
- pytest.raises(KeyError, series.count, 'x')
- pytest.raises(KeyError, frame.count, level='x')
+ msg = "Level x not found"
+ with pytest.raises(KeyError, match=msg):
+ series.count('x')
+ with pytest.raises(KeyError, match=msg):
+ frame.count(level='x')
@pytest.mark.parametrize('op', AGG_FUNCTIONS)
@pytest.mark.parametrize('level', [0, 1])
@@ -1119,7 +1122,8 @@ def test_level_with_tuples(self):
tm.assert_series_equal(result, expected)
tm.assert_series_equal(result2, expected)
- pytest.raises(KeyError, series.__getitem__, (('foo', 'bar', 0), 2))
+ with pytest.raises(KeyError, match=r"^\(\('foo', 'bar', 0\), 2\)$"):
+ series[('foo', 'bar', 0), 2]
result = frame.loc[('foo', 'bar', 0)]
result2 = frame.xs(('foo', 'bar', 0))
diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py
index cf5ef6cf15eca..d1893b7efbc41 100644
--- a/pandas/tests/test_nanops.py
+++ b/pandas/tests/test_nanops.py
@@ -7,6 +7,7 @@
import numpy as np
import pytest
+from pandas.compat import PY2
from pandas.compat.numpy import _np_version_under1p13
import pandas.util._test_decorators as td
@@ -728,6 +729,7 @@ def test_numeric_values(self):
# Test complex
assert nanops._ensure_numeric(1 + 2j) == 1 + 2j
+ @pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
def test_ndarray(self):
# Test numeric ndarray
values = np.array([1, 2, 3])
@@ -743,7 +745,9 @@ def test_ndarray(self):
# Test non-convertible string ndarray
s_values = np.array(['foo', 'bar', 'baz'], dtype=object)
- pytest.raises(ValueError, lambda: nanops._ensure_numeric(s_values))
+ msg = r"could not convert string to float: '(foo|baz)'"
+ with pytest.raises(ValueError, match=msg):
+ nanops._ensure_numeric(s_values)
def test_convertable_values(self):
assert np.allclose(nanops._ensure_numeric('1'), 1.0)
@@ -751,9 +755,15 @@ def test_convertable_values(self):
assert np.allclose(nanops._ensure_numeric('1+1j'), 1 + 1j)
def test_non_convertable_values(self):
- pytest.raises(TypeError, lambda: nanops._ensure_numeric('foo'))
- pytest.raises(TypeError, lambda: nanops._ensure_numeric({}))
- pytest.raises(TypeError, lambda: nanops._ensure_numeric([]))
+ msg = "Could not convert foo to numeric"
+ with pytest.raises(TypeError, match=msg):
+ nanops._ensure_numeric('foo')
+ msg = "Could not convert {} to numeric"
+ with pytest.raises(TypeError, match=msg):
+ nanops._ensure_numeric({})
+ msg = r"Could not convert \[\] to numeric"
+ with pytest.raises(TypeError, match=msg):
+ nanops._ensure_numeric([])
class TestNanvarFixedValues(object):
diff --git a/pandas/tests/test_sorting.py b/pandas/tests/test_sorting.py
index 7500cbb3cfc3a..e83bdb1af9121 100644
--- a/pandas/tests/test_sorting.py
+++ b/pandas/tests/test_sorting.py
@@ -7,6 +7,8 @@
from numpy import nan
import pytest
+from pandas.compat import PY2
+
from pandas import DataFrame, MultiIndex, Series, compat, concat, merge
from pandas.core import common as com
from pandas.core.sorting import (
@@ -403,15 +405,21 @@ def test_mixed_integer_from_list(self):
expected = np.array([0, 0, 1, 'a', 'b', 'b'], dtype=object)
tm.assert_numpy_array_equal(result, expected)
+ @pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
def test_unsortable(self):
# GH 13714
arr = np.array([1, 2, datetime.now(), 0, 3], dtype=object)
+ msg = ("'<' not supported between instances of 'datetime.datetime'"
+ r" and 'int'|"
+ r"unorderable types: int\(\) > datetime.datetime\(\)")
if compat.PY2:
# RuntimeWarning: tp_compare didn't return -1 or -2 for exception
with warnings.catch_warnings():
- pytest.raises(TypeError, safe_sort, arr)
+ with pytest.raises(TypeError, match=msg):
+ safe_sort(arr)
else:
- pytest.raises(TypeError, safe_sort, arr)
+ with pytest.raises(TypeError, match=msg):
+ safe_sort(arr)
def test_exceptions(self):
with pytest.raises(TypeError,
diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py
index 7cea3be03d1a7..bbcdc24f58f9b 100644
--- a/pandas/tests/test_strings.py
+++ b/pandas/tests/test_strings.py
@@ -10,7 +10,7 @@
import pytest
import pandas.compat as compat
-from pandas.compat import PY3, range, u
+from pandas.compat import PY2, PY3, range, u
from pandas import DataFrame, Index, MultiIndex, Series, concat, isna, notna
import pandas.core.strings as strings
@@ -1002,11 +1002,13 @@ def test_replace(self):
tm.assert_series_equal(result, exp)
# GH 13438
+ msg = "repl must be a string or callable"
for klass in (Series, Index):
for repl in (None, 3, {'a': 'b'}):
for data in (['a', 'b', None], ['a', 'b', 'c', 'ad']):
values = klass(data)
- pytest.raises(TypeError, values.str.replace, 'a', repl)
+ with pytest.raises(TypeError, match=msg):
+ values.str.replace('a', repl)
def test_replace_callable(self):
# GH 15055
@@ -1123,10 +1125,14 @@ def test_replace_literal(self):
callable_repl = lambda m: m.group(0).swapcase()
compiled_pat = re.compile('[a-z][A-Z]{2}')
- pytest.raises(ValueError, values.str.replace, 'abc', callable_repl,
- regex=False)
- pytest.raises(ValueError, values.str.replace, compiled_pat, '',
- regex=False)
+ msg = "Cannot use a callable replacement when regex=False"
+ with pytest.raises(ValueError, match=msg):
+ values.str.replace('abc', callable_repl, regex=False)
+
+ msg = ("Cannot use a compiled regex as replacement pattern with"
+ " regex=False")
+ with pytest.raises(ValueError, match=msg):
+ values.str.replace(compiled_pat, '', regex=False)
def test_repeat(self):
values = Series(['a', 'b', NA, 'c', NA, 'd'])
@@ -1242,12 +1248,13 @@ def test_extract_expand_False(self):
for klass in [Series, Index]:
# no groups
s_or_idx = klass(['A1', 'B2', 'C3'])
- f = lambda: s_or_idx.str.extract('[ABC][123]', expand=False)
- pytest.raises(ValueError, f)
+ msg = "pattern contains no capture groups"
+ with pytest.raises(ValueError, match=msg):
+ s_or_idx.str.extract('[ABC][123]', expand=False)
# only non-capturing groups
- f = lambda: s_or_idx.str.extract('(?:[AB]).*', expand=False)
- pytest.raises(ValueError, f)
+ with pytest.raises(ValueError, match=msg):
+ s_or_idx.str.extract('(?:[AB]).*', expand=False)
# single group renames series/index properly
s_or_idx = klass(['A1', 'A2'])
@@ -1387,12 +1394,13 @@ def test_extract_expand_True(self):
for klass in [Series, Index]:
# no groups
s_or_idx = klass(['A1', 'B2', 'C3'])
- f = lambda: s_or_idx.str.extract('[ABC][123]', expand=True)
- pytest.raises(ValueError, f)
+ msg = "pattern contains no capture groups"
+ with pytest.raises(ValueError, match=msg):
+ s_or_idx.str.extract('[ABC][123]', expand=True)
# only non-capturing groups
- f = lambda: s_or_idx.str.extract('(?:[AB]).*', expand=True)
- pytest.raises(ValueError, f)
+ with pytest.raises(ValueError, match=msg):
+ s_or_idx.str.extract('(?:[AB]).*', expand=True)
# single group renames series/index properly
s_or_idx = klass(['A1', 'A2'])
@@ -3315,10 +3323,14 @@ def test_encode_decode(self):
tm.assert_series_equal(result, exp)
+ @pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
def test_encode_decode_errors(self):
encodeBase = Series([u('a'), u('b'), u('a\x9d')])
- pytest.raises(UnicodeEncodeError, encodeBase.str.encode, 'cp1252')
+ msg = (r"'charmap' codec can't encode character '\\x9d' in position 1:"
+ " character maps to <undefined>")
+ with pytest.raises(UnicodeEncodeError, match=msg):
+ encodeBase.str.encode('cp1252')
f = lambda x: x.encode('cp1252', 'ignore')
result = encodeBase.str.encode('cp1252', 'ignore')
@@ -3327,7 +3339,10 @@ def test_encode_decode_errors(self):
decodeBase = Series([b'a', b'b', b'a\x9d'])
- pytest.raises(UnicodeDecodeError, decodeBase.str.decode, 'cp1252')
+ msg = ("'charmap' codec can't decode byte 0x9d in position 1:"
+ " character maps to <undefined>")
+ with pytest.raises(UnicodeDecodeError, match=msg):
+ decodeBase.str.decode('cp1252')
f = lambda x: x.decode('cp1252', 'ignore')
result = decodeBase.str.decode('cp1252', 'ignore')
@@ -3418,7 +3433,8 @@ def test_method_on_bytes(self):
lhs = Series(np.array(list('abc'), 'S1').astype(object))
rhs = Series(np.array(list('def'), 'S1').astype(object))
if compat.PY3:
- pytest.raises(TypeError, lhs.str.cat, rhs)
+ with pytest.raises(TypeError, match="can't concat str to bytes"):
+ lhs.str.cat(rhs)
else:
result = lhs.str.cat(rhs)
expected = Series(np.array(
diff --git a/pandas/tests/test_window.py b/pandas/tests/test_window.py
index e816d4c04344a..ce9d1888b8e96 100644
--- a/pandas/tests/test_window.py
+++ b/pandas/tests/test_window.py
@@ -89,9 +89,8 @@ def test_getitem(self):
def test_select_bad_cols(self):
df = DataFrame([[1, 2]], columns=['A', 'B'])
g = df.rolling(window=5)
- pytest.raises(KeyError, g.__getitem__, ['C']) # g[['C']]
-
- pytest.raises(KeyError, g.__getitem__, ['A', 'C']) # g[['A', 'C']]
+ with pytest.raises(KeyError, match="Columns not found: 'C'"):
+ g[['C']]
with pytest.raises(KeyError, match='^[^A]+$'):
# A should not be referenced as a bad column...
# will have to rethink regex if you change message!
@@ -102,7 +101,9 @@ def test_attribute_access(self):
df = DataFrame([[1, 2]], columns=['A', 'B'])
r = df.rolling(window=5)
tm.assert_series_equal(r.A.sum(), r['A'].sum())
- pytest.raises(AttributeError, lambda: r.F)
+ msg = "'Rolling' object has no attribute 'F'"
+ with pytest.raises(AttributeError, match=msg):
+ r.F
def tests_skip_nuisance(self):
@@ -217,12 +218,11 @@ def test_agg_nested_dicts(self):
df = DataFrame({'A': range(5), 'B': range(0, 10, 2)})
r = df.rolling(window=3)
- def f():
+ msg = r"cannot perform renaming for (r1|r2) with a nested dictionary"
+ with pytest.raises(SpecificationError, match=msg):
r.aggregate({'r1': {'A': ['mean', 'sum']},
'r2': {'B': ['mean', 'sum']}})
- pytest.raises(SpecificationError, f)
-
expected = concat([r['A'].mean(), r['A'].std(),
r['B'].mean(), r['B'].std()], axis=1)
expected.columns = pd.MultiIndex.from_tuples([('ra', 'mean'), (
@@ -1806,26 +1806,38 @@ def test_ewm_alpha_arg(self):
def test_ewm_domain_checks(self):
# GH 12492
s = Series(self.arr)
- # com must satisfy: com >= 0
- pytest.raises(ValueError, s.ewm, com=-0.1)
+ msg = "comass must satisfy: comass >= 0"
+ with pytest.raises(ValueError, match=msg):
+ s.ewm(com=-0.1)
s.ewm(com=0.0)
s.ewm(com=0.1)
- # span must satisfy: span >= 1
- pytest.raises(ValueError, s.ewm, span=-0.1)
- pytest.raises(ValueError, s.ewm, span=0.0)
- pytest.raises(ValueError, s.ewm, span=0.9)
+
+ msg = "span must satisfy: span >= 1"
+ with pytest.raises(ValueError, match=msg):
+ s.ewm(span=-0.1)
+ with pytest.raises(ValueError, match=msg):
+ s.ewm(span=0.0)
+ with pytest.raises(ValueError, match=msg):
+ s.ewm(span=0.9)
s.ewm(span=1.0)
s.ewm(span=1.1)
- # halflife must satisfy: halflife > 0
- pytest.raises(ValueError, s.ewm, halflife=-0.1)
- pytest.raises(ValueError, s.ewm, halflife=0.0)
+
+ msg = "halflife must satisfy: halflife > 0"
+ with pytest.raises(ValueError, match=msg):
+ s.ewm(halflife=-0.1)
+ with pytest.raises(ValueError, match=msg):
+ s.ewm(halflife=0.0)
s.ewm(halflife=0.1)
- # alpha must satisfy: 0 < alpha <= 1
- pytest.raises(ValueError, s.ewm, alpha=-0.1)
- pytest.raises(ValueError, s.ewm, alpha=0.0)
+
+ msg = "alpha must satisfy: 0 < alpha <= 1"
+ with pytest.raises(ValueError, match=msg):
+ s.ewm(alpha=-0.1)
+ with pytest.raises(ValueError, match=msg):
+ s.ewm(alpha=0.0)
s.ewm(alpha=0.1)
s.ewm(alpha=1.0)
- pytest.raises(ValueError, s.ewm, alpha=1.1)
+ with pytest.raises(ValueError, match=msg):
+ s.ewm(alpha=1.1)
@pytest.mark.parametrize('method', ['mean', 'vol', 'var'])
def test_ew_empty_series(self, method):
@@ -2598,7 +2610,10 @@ def get_result(obj, obj2=None):
def test_flex_binary_moment(self):
# GH3155
# don't blow the stack
- pytest.raises(TypeError, rwindow._flex_binary_moment, 5, 6, None)
+ msg = ("arguments to moment function must be of type"
+ " np.ndarray/Series/DataFrame")
+ with pytest.raises(TypeError, match=msg):
+ rwindow._flex_binary_moment(5, 6, None)
def test_corr_sanity(self):
# GH 3155
@@ -2682,7 +2697,10 @@ def func(A, B, com, **kwargs):
Series([1.]), Series([1.]), 50, min_periods=min_periods)
tm.assert_series_equal(result, Series([np.NaN]))
- pytest.raises(Exception, func, A, randn(50), 20, min_periods=5)
+ msg = "Input arrays must be of the same type!"
+ # exception raised is Exception
+ with pytest.raises(Exception, match=msg):
+ func(A, randn(50), 20, min_periods=5)
def test_expanding_apply_args_kwargs(self, raw):
@@ -3266,9 +3284,9 @@ def setup_method(self, method):
def test_mutated(self):
- def f():
+ msg = r"group\(\) got an unexpected keyword argument 'foo'"
+ with pytest.raises(TypeError, match=msg):
self.frame.groupby('A', foo=1)
- pytest.raises(TypeError, f)
g = self.frame.groupby('A')
assert not g.mutated
| xref #24332 | https://api.github.com/repos/pandas-dev/pandas/pulls/25452 | 2019-02-26T17:57:03Z | 2019-02-28T13:34:22Z | 2019-02-28T13:34:22Z | 2019-03-01T12:48:56Z |
STY: use pytest.raises context manager (indexes) | diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py
index e4f25ff143273..ba451da10573a 100644
--- a/pandas/tests/indexes/interval/test_interval.py
+++ b/pandas/tests/indexes/interval/test_interval.py
@@ -403,13 +403,16 @@ def test_get_item(self, closed):
# To be removed, replaced by test_interval_new.py (see #16316, #16386)
def test_get_loc_value(self):
- pytest.raises(KeyError, self.index.get_loc, 0)
+ with pytest.raises(KeyError, match="^0$"):
+ self.index.get_loc(0)
assert self.index.get_loc(0.5) == 0
assert self.index.get_loc(1) == 0
assert self.index.get_loc(1.5) == 1
assert self.index.get_loc(2) == 1
- pytest.raises(KeyError, self.index.get_loc, -1)
- pytest.raises(KeyError, self.index.get_loc, 3)
+ with pytest.raises(KeyError, match="^-1$"):
+ self.index.get_loc(-1)
+ with pytest.raises(KeyError, match="^3$"):
+ self.index.get_loc(3)
idx = IntervalIndex.from_tuples([(0, 2), (1, 3)])
assert idx.get_loc(0.5) == 0
@@ -419,10 +422,12 @@ def test_get_loc_value(self):
tm.assert_numpy_array_equal(np.sort(idx.get_loc(2)),
np.array([0, 1], dtype='intp'))
assert idx.get_loc(3) == 1
- pytest.raises(KeyError, idx.get_loc, 3.5)
+ with pytest.raises(KeyError, match=r"^3\.5$"):
+ idx.get_loc(3.5)
idx = IntervalIndex.from_arrays([0, 2], [1, 3])
- pytest.raises(KeyError, idx.get_loc, 1.5)
+ with pytest.raises(KeyError, match=r"^1\.5$"):
+ idx.get_loc(1.5)
# To be removed, replaced by test_interval_new.py (see #16316, #16386)
def slice_locs_cases(self, breaks):
@@ -486,7 +491,9 @@ def test_slice_locs_decreasing_float64(self):
# To be removed, replaced by test_interval_new.py (see #16316, #16386)
def test_slice_locs_fails(self):
index = IntervalIndex.from_tuples([(1, 2), (0, 1), (2, 3)])
- with pytest.raises(KeyError):
+ 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):
index.slice_locs(1, 2)
# To be removed, replaced by test_interval_new.py (see #16316, #16386)
@@ -494,9 +501,12 @@ def test_get_loc_interval(self):
assert self.index.get_loc(Interval(0, 1)) == 0
assert self.index.get_loc(Interval(0, 0.5)) == 0
assert self.index.get_loc(Interval(0, 1, 'left')) == 0
- pytest.raises(KeyError, self.index.get_loc, Interval(2, 3))
- pytest.raises(KeyError, self.index.get_loc,
- Interval(-1, 0, 'left'))
+ msg = r"Interval\(2, 3, closed='right'\)"
+ with pytest.raises(KeyError, match=msg):
+ self.index.get_loc(Interval(2, 3))
+ msg = r"Interval\(-1, 0, closed='left'\)"
+ with pytest.raises(KeyError, match=msg):
+ self.index.get_loc(Interval(-1, 0, 'left'))
# Make consistent with test_interval_new.py (see #16316, #16386)
@pytest.mark.parametrize('item', [3, Interval(1, 4)])
@@ -981,9 +991,11 @@ def test_comparison(self):
self.index > 0
with pytest.raises(TypeError, match='unorderable types'):
self.index <= 0
- with pytest.raises(TypeError):
+ msg = r"unorderable types: Interval\(\) > int\(\)"
+ with pytest.raises(TypeError, match=msg):
self.index > np.arange(2)
- with pytest.raises(ValueError):
+ msg = "Lengths must match to compare"
+ with pytest.raises(ValueError, match=msg):
self.index > np.arange(3)
def test_missing_values(self, closed):
@@ -993,7 +1005,9 @@ def test_missing_values(self, closed):
[np.nan, 0, 1], [np.nan, 1, 2], closed=closed)
assert idx.equals(idx2)
- with pytest.raises(ValueError):
+ msg = ("missing values must be missing in the same location both left"
+ " and right sides")
+ with pytest.raises(ValueError, match=msg):
IntervalIndex.from_arrays(
[np.nan, 0, 1], np.array([0, 1, 2]), closed=closed)
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index 8415bab802239..26dcf7d6bc234 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -4,6 +4,7 @@
from datetime import datetime, timedelta
import math
import operator
+import re
import sys
import numpy as np
@@ -107,7 +108,10 @@ def test_constructor_copy(self):
def test_constructor_corner(self):
# corner case
- pytest.raises(TypeError, Index, 0)
+ msg = (r"Index\(\.\.\.\) must be called with a collection of some"
+ " kind, 0 was passed")
+ with pytest.raises(TypeError, match=msg):
+ Index(0)
@pytest.mark.parametrize("index_vals", [
[('A', 1), 'B'], ['B', ('A', 1)]])
@@ -488,21 +492,22 @@ def test_constructor_cast(self):
Index(["a", "b", "c"], dtype=float)
def test_view_with_args(self):
-
restricted = ['unicodeIndex', 'strIndex', 'catIndex', 'boolIndex',
'empty']
-
- for i in restricted:
- ind = self.indices[i]
-
- # with arguments
- pytest.raises(TypeError, lambda: ind.view('i8'))
-
- # these are ok
for i in list(set(self.indices.keys()) - set(restricted)):
ind = self.indices[i]
+ ind.view('i8')
- # with arguments
+ @pytest.mark.parametrize('index_type', [
+ 'unicodeIndex',
+ 'strIndex',
+ pytest.param('catIndex', marks=pytest.mark.xfail(reason="gh-25464")),
+ 'boolIndex',
+ 'empty'])
+ def test_view_with_args_object_array_raises(self, index_type):
+ ind = self.indices[index_type]
+ msg = "Cannot change data-type for object array"
+ with pytest.raises(TypeError, match=msg):
ind.view('i8')
def test_astype(self):
@@ -565,8 +570,8 @@ def test_delete(self, pos, expected):
def test_delete_raises(self):
index = Index(['a', 'b', 'c', 'd'], name='index')
- with pytest.raises((IndexError, ValueError)):
- # either depending on numpy version
+ msg = "index 5 is out of bounds for axis 0 with size 4"
+ with pytest.raises(IndexError, match=msg):
index.delete(5)
def test_identical(self):
@@ -683,7 +688,9 @@ def test_empty_fancy_raises(self, attr):
assert index[[]].identical(empty_index)
# np.ndarray only accepts ndarray of int & bool dtypes, so should Index
- pytest.raises(IndexError, index.__getitem__, empty_farr)
+ msg = r"arrays used as indices must be of integer \(or boolean\) type"
+ with pytest.raises(IndexError, match=msg):
+ index[empty_farr]
@pytest.mark.parametrize("sort", [None, False])
def test_intersection(self, sort):
@@ -1426,13 +1433,14 @@ def test_get_indexer_strings(self, method, expected):
def test_get_indexer_strings_raises(self):
index = pd.Index(['b', 'c'])
- with pytest.raises(TypeError):
+ msg = r"unsupported operand type\(s\) for -: 'str' and 'str'"
+ with pytest.raises(TypeError, match=msg):
index.get_indexer(['a', 'b', 'c', 'd'], method='nearest')
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError, match=msg):
index.get_indexer(['a', 'b', 'c', 'd'], method='pad', tolerance=2)
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError, match=msg):
index.get_indexer(['a', 'b', 'c', 'd'], method='pad',
tolerance=[2, 2, 2, 2])
@@ -1685,8 +1693,11 @@ def test_drop_tuple(self, values, to_drop):
tm.assert_index_equal(result, expected)
removed = index.drop(to_drop[1])
+ msg = r"\"\[{}\] not found in axis\"".format(
+ re.escape(to_drop[1].__repr__()))
for drop_me in to_drop[1], [to_drop[1]]:
- pytest.raises(KeyError, removed.drop, drop_me)
+ with pytest.raises(KeyError, match=msg):
+ removed.drop(drop_me)
@pytest.mark.parametrize("method,expected,sort", [
('intersection', np.array([(1, 'A'), (2, 'A'), (1, 'B'), (2, 'B')],
diff --git a/pandas/tests/indexes/test_category.py b/pandas/tests/indexes/test_category.py
index d889135160ae2..95fac2f6ae05b 100644
--- a/pandas/tests/indexes/test_category.py
+++ b/pandas/tests/indexes/test_category.py
@@ -181,18 +181,21 @@ def test_create_categorical(self):
expected = Categorical(['a', 'b', 'c'])
tm.assert_categorical_equal(result, expected)
- def test_disallow_set_ops(self):
-
+ @pytest.mark.parametrize('func,op_name', [
+ (lambda idx: idx - idx, '__sub__'),
+ (lambda idx: idx + idx, '__add__'),
+ (lambda idx: idx - ['a', 'b'], '__sub__'),
+ (lambda idx: idx + ['a', 'b'], '__add__'),
+ (lambda idx: ['a', 'b'] - idx, '__rsub__'),
+ (lambda idx: ['a', 'b'] + idx, '__radd__'),
+ ])
+ def test_disallow_set_ops(self, func, op_name):
# GH 10039
# set ops (+/-) raise TypeError
idx = pd.Index(pd.Categorical(['a', 'b']))
-
- pytest.raises(TypeError, lambda: idx - idx)
- pytest.raises(TypeError, lambda: idx + idx)
- pytest.raises(TypeError, lambda: idx - ['a', 'b'])
- pytest.raises(TypeError, lambda: idx + ['a', 'b'])
- pytest.raises(TypeError, lambda: ['a', 'b'] - idx)
- pytest.raises(TypeError, lambda: ['a', 'b'] + idx)
+ msg = "cannot perform {} with this index type: CategoricalIndex"
+ with pytest.raises(TypeError, match=msg.format(op_name)):
+ func(idx)
def test_method_delegation(self):
@@ -231,8 +234,9 @@ def test_method_delegation(self):
list('aabbca'), categories=list('cabdef'), ordered=True))
# invalid
- pytest.raises(ValueError, lambda: ci.set_categories(
- list('cab'), inplace=True))
+ msg = "cannot use inplace with CategoricalIndex"
+ with pytest.raises(ValueError, match=msg):
+ ci.set_categories(list('cab'), inplace=True)
def test_contains(self):
@@ -357,12 +361,11 @@ def test_append(self):
tm.assert_index_equal(result, ci, exact=True)
# appending with different categories or reordered is not ok
- pytest.raises(
- TypeError,
- lambda: ci.append(ci.values.set_categories(list('abcd'))))
- pytest.raises(
- TypeError,
- lambda: ci.append(ci.values.reorder_categories(list('abc'))))
+ msg = "all inputs must be Index"
+ with pytest.raises(TypeError, match=msg):
+ ci.append(ci.values.set_categories(list('abcd')))
+ with pytest.raises(TypeError, match=msg):
+ ci.append(ci.values.reorder_categories(list('abc')))
# with objects
result = ci.append(Index(['c', 'a']))
@@ -370,7 +373,9 @@ def test_append(self):
tm.assert_index_equal(result, expected, exact=True)
# invalid objects
- pytest.raises(TypeError, lambda: ci.append(Index(['a', 'd'])))
+ msg = "cannot append a non-category item to a CategoricalIndex"
+ with pytest.raises(TypeError, match=msg):
+ ci.append(Index(['a', 'd']))
# GH14298 - if base object is not categorical -> coerce to object
result = Index(['c', 'a']).append(ci)
@@ -406,7 +411,10 @@ def test_insert(self):
tm.assert_index_equal(result, expected, exact=True)
# invalid
- pytest.raises(TypeError, lambda: ci.insert(0, 'd'))
+ msg = ("cannot insert an item into a CategoricalIndex that is not"
+ " already an existing category")
+ with pytest.raises(TypeError, match=msg):
+ ci.insert(0, 'd')
# GH 18295 (test missing)
expected = CategoricalIndex(['a', np.nan, 'a', 'b', 'c', 'b'])
@@ -633,12 +641,16 @@ def test_get_indexer(self):
r1 = idx1.get_indexer(idx2)
assert_almost_equal(r1, np.array([0, 1, 2, -1], dtype=np.intp))
- pytest.raises(NotImplementedError,
- lambda: idx2.get_indexer(idx1, method='pad'))
- pytest.raises(NotImplementedError,
- lambda: idx2.get_indexer(idx1, method='backfill'))
- pytest.raises(NotImplementedError,
- lambda: idx2.get_indexer(idx1, method='nearest'))
+ msg = ("method='pad' and method='backfill' not implemented yet for"
+ " CategoricalIndex")
+ with pytest.raises(NotImplementedError, match=msg):
+ idx2.get_indexer(idx1, method='pad')
+ with pytest.raises(NotImplementedError, match=msg):
+ idx2.get_indexer(idx1, method='backfill')
+
+ msg = "method='nearest' not implemented yet for CategoricalIndex"
+ with pytest.raises(NotImplementedError, match=msg):
+ idx2.get_indexer(idx1, method='nearest')
def test_get_loc(self):
# GH 12531
@@ -776,12 +788,15 @@ def test_equals_categorical(self):
# invalid comparisons
with pytest.raises(ValueError, match="Lengths must match"):
ci1 == Index(['a', 'b', 'c'])
- pytest.raises(TypeError, lambda: ci1 == ci2)
- pytest.raises(
- TypeError, lambda: ci1 == Categorical(ci1.values, ordered=False))
- pytest.raises(
- TypeError,
- lambda: ci1 == Categorical(ci1.values, categories=list('abc')))
+
+ msg = ("categorical index comparisons must have the same categories"
+ " and ordered attributes")
+ with pytest.raises(TypeError, match=msg):
+ ci1 == ci2
+ with pytest.raises(TypeError, match=msg):
+ ci1 == Categorical(ci1.values, ordered=False)
+ with pytest.raises(TypeError, match=msg):
+ ci1 == Categorical(ci1.values, categories=list('abc'))
# tests
# make sure that we are testing for category inclusion properly
diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py
index fd356202a8ce5..03448129a48fc 100644
--- a/pandas/tests/indexes/test_common.py
+++ b/pandas/tests/indexes/test_common.py
@@ -3,6 +3,8 @@
any index subclass. Makes use of the `indices` fixture defined
in pandas/tests/indexes/conftest.py.
"""
+import re
+
import numpy as np
import pytest
@@ -189,8 +191,14 @@ def test_unique(self, indices):
result = indices.unique(level=level)
tm.assert_index_equal(result, expected)
- for level in 3, 'wrong':
- pytest.raises((IndexError, KeyError), indices.unique, level=level)
+ msg = "Too many levels: Index has only 1 level, not 4"
+ with pytest.raises(IndexError, match=msg):
+ indices.unique(level=3)
+
+ msg = r"Level wrong must be same as name \({}\)".format(
+ re.escape(indices.name.__repr__()))
+ with pytest.raises(KeyError, match=msg):
+ indices.unique(level='wrong')
def test_get_unique_index(self, indices):
# MultiIndex tested separately
@@ -239,12 +247,16 @@ def test_get_unique_index(self, indices):
tm.assert_index_equal(result, expected)
def test_sort(self, indices):
- pytest.raises(TypeError, indices.sort)
+ msg = "cannot sort an Index object in-place, use sort_values instead"
+ with pytest.raises(TypeError, match=msg):
+ indices.sort()
def test_mutability(self, indices):
if not len(indices):
pytest.skip('Skip check for empty Index')
- pytest.raises(TypeError, indices.__setitem__, 0, indices[0])
+ msg = "Index does not support mutable operations"
+ with pytest.raises(TypeError, match=msg):
+ indices[0] = indices[0]
def test_view(self, indices):
assert indices.view().name == indices.name
diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py
index a64340c02cd22..26413f4519eff 100644
--- a/pandas/tests/indexes/test_numeric.py
+++ b/pandas/tests/indexes/test_numeric.py
@@ -1,15 +1,17 @@
# -*- coding: utf-8 -*-
from datetime import datetime
+import re
import numpy as np
import pytest
from pandas._libs.tslibs import Timestamp
-from pandas.compat import range
+from pandas.compat import PY2, range
import pandas as pd
from pandas import Float64Index, Index, Int64Index, Series, UInt64Index
+from pandas.api.types import pandas_dtype
from pandas.tests.indexes.common import Base
import pandas.util.testing as tm
@@ -153,12 +155,22 @@ def test_constructor(self):
result = Index(np.array([np.nan]))
assert pd.isna(result.values).all()
+ @pytest.mark.skipif(PY2, reason="pytest.raises match regex fails")
def test_constructor_invalid(self):
# invalid
- pytest.raises(TypeError, Float64Index, 0.)
- pytest.raises(TypeError, Float64Index, ['a', 'b', 0.])
- pytest.raises(TypeError, Float64Index, [Timestamp('20130101')])
+ msg = (r"Float64Index\(\.\.\.\) must be called with a collection of"
+ r" some kind, 0\.0 was passed")
+ with pytest.raises(TypeError, match=msg):
+ Float64Index(0.)
+ msg = ("String dtype not supported, you may need to explicitly cast to"
+ " a numeric type")
+ with pytest.raises(TypeError, match=msg):
+ Float64Index(['a', 'b', 0.])
+ msg = (r"float\(\) argument must be a string or a number, not"
+ " 'Timestamp'")
+ with pytest.raises(TypeError, match=msg):
+ Float64Index([Timestamp('20130101')])
def test_constructor_coerce(self):
@@ -216,12 +228,17 @@ def test_astype(self):
# invalid
for dtype in ['M8[ns]', 'm8[ns]']:
- pytest.raises(TypeError, lambda: i.astype(dtype))
+ msg = ("Cannot convert Float64Index to dtype {}; integer values"
+ " are required for conversion").format(pandas_dtype(dtype))
+ with pytest.raises(TypeError, match=re.escape(msg)):
+ i.astype(dtype)
# GH 13149
for dtype in ['int16', 'int32', 'int64']:
i = Float64Index([0, 1.1, np.NAN])
- pytest.raises(ValueError, lambda: i.astype(dtype))
+ msg = "Cannot convert NA to integer"
+ with pytest.raises(ValueError, match=msg):
+ i.astype(dtype)
def test_type_coercion_fail(self, any_int_dtype):
# see gh-15832
@@ -275,12 +292,16 @@ def test_get_loc(self):
assert idx.get_loc(1.1, method) == loc
assert idx.get_loc(1.1, method, tolerance=0.9) == loc
- pytest.raises(KeyError, idx.get_loc, 'foo')
- pytest.raises(KeyError, idx.get_loc, 1.5)
- pytest.raises(KeyError, idx.get_loc, 1.5, method='pad',
- tolerance=0.1)
- pytest.raises(KeyError, idx.get_loc, True)
- pytest.raises(KeyError, idx.get_loc, False)
+ with pytest.raises(KeyError, match="^'foo'$"):
+ idx.get_loc('foo')
+ with pytest.raises(KeyError, match=r"^1\.5$"):
+ idx.get_loc(1.5)
+ with pytest.raises(KeyError, match=r"^1\.5$"):
+ idx.get_loc(1.5, method='pad', tolerance=0.1)
+ with pytest.raises(KeyError, match="^True$"):
+ idx.get_loc(True)
+ with pytest.raises(KeyError, match="^False$"):
+ idx.get_loc(False)
with pytest.raises(ValueError, match='must be numeric'):
idx.get_loc(1.4, method='nearest', tolerance='foo')
@@ -310,15 +331,20 @@ def test_get_loc_na(self):
# not representable by slice
idx = Float64Index([np.nan, 1, np.nan, np.nan])
assert idx.get_loc(1) == 1
- pytest.raises(KeyError, idx.slice_locs, np.nan)
+ msg = "'Cannot get left slice bound for non-unique label: nan"
+ with pytest.raises(KeyError, match=msg):
+ idx.slice_locs(np.nan)
def test_get_loc_missing_nan(self):
# GH 8569
idx = Float64Index([1, 2])
assert idx.get_loc(1) == 0
- pytest.raises(KeyError, idx.get_loc, 3)
- pytest.raises(KeyError, idx.get_loc, np.nan)
- pytest.raises(KeyError, idx.get_loc, [np.nan])
+ with pytest.raises(KeyError, match=r"^3\.0$"):
+ idx.get_loc(3)
+ with pytest.raises(KeyError, match="^nan$"):
+ idx.get_loc(np.nan)
+ with pytest.raises(KeyError, match=r"^\[nan\]$"):
+ idx.get_loc([np.nan])
def test_contains_nans(self):
i = Float64Index([1.0, 2.0, np.nan])
@@ -499,13 +525,17 @@ def test_union_noncomparable(self):
tm.assert_index_equal(result, expected)
def test_cant_or_shouldnt_cast(self):
+ msg = ("String dtype not supported, you may need to explicitly cast to"
+ " a numeric type")
# can't
data = ['foo', 'bar', 'baz']
- pytest.raises(TypeError, self._holder, data)
+ with pytest.raises(TypeError, match=msg):
+ self._holder(data)
# shouldn't
data = ['0', '1', '2']
- pytest.raises(TypeError, self._holder, data)
+ with pytest.raises(TypeError, match=msg):
+ self._holder(data)
def test_view_index(self):
self.index.view(Index)
@@ -576,7 +606,10 @@ def test_constructor(self):
tm.assert_index_equal(index, expected)
# scalar raise Exception
- pytest.raises(TypeError, Int64Index, 5)
+ msg = (r"Int64Index\(\.\.\.\) must be called with a collection of some"
+ " kind, 5 was passed")
+ with pytest.raises(TypeError, match=msg):
+ Int64Index(5)
# copy
arr = self.index.values
diff --git a/pandas/tests/indexes/timedeltas/test_arithmetic.py b/pandas/tests/indexes/timedeltas/test_arithmetic.py
index 04977023d7c62..3173252e174ab 100644
--- a/pandas/tests/indexes/timedeltas/test_arithmetic.py
+++ b/pandas/tests/indexes/timedeltas/test_arithmetic.py
@@ -198,20 +198,34 @@ def test_ops_ndarray(self):
expected = pd.to_timedelta(['2 days']).values
tm.assert_numpy_array_equal(td + other, expected)
tm.assert_numpy_array_equal(other + td, expected)
- pytest.raises(TypeError, lambda: td + np.array([1]))
- pytest.raises(TypeError, lambda: np.array([1]) + td)
+ msg = r"unsupported operand type\(s\) for \+: 'Timedelta' and 'int'"
+ with pytest.raises(TypeError, match=msg):
+ td + np.array([1])
+ msg = (r"unsupported operand type\(s\) for \+: 'numpy.ndarray' and"
+ " 'Timedelta'")
+ with pytest.raises(TypeError, match=msg):
+ np.array([1]) + td
expected = pd.to_timedelta(['0 days']).values
tm.assert_numpy_array_equal(td - other, expected)
tm.assert_numpy_array_equal(-other + td, expected)
- pytest.raises(TypeError, lambda: td - np.array([1]))
- pytest.raises(TypeError, lambda: np.array([1]) - td)
+ msg = r"unsupported operand type\(s\) for -: 'Timedelta' and 'int'"
+ with pytest.raises(TypeError, match=msg):
+ td - np.array([1])
+ msg = (r"unsupported operand type\(s\) for -: 'numpy.ndarray' and"
+ " 'Timedelta'")
+ with pytest.raises(TypeError, match=msg):
+ np.array([1]) - td
expected = pd.to_timedelta(['2 days']).values
tm.assert_numpy_array_equal(td * np.array([2]), expected)
tm.assert_numpy_array_equal(np.array([2]) * td, expected)
- pytest.raises(TypeError, lambda: td * other)
- pytest.raises(TypeError, lambda: other * td)
+ msg = ("ufunc multiply cannot use operands with types"
+ r" dtype\('<m8\[ns\]'\) and dtype\('<m8\[ns\]'\)")
+ with pytest.raises(TypeError, match=msg):
+ td * other
+ with pytest.raises(TypeError, match=msg):
+ other * td
tm.assert_numpy_array_equal(td / other,
np.array([1], dtype=np.float64))
diff --git a/pandas/tests/indexes/timedeltas/test_construction.py b/pandas/tests/indexes/timedeltas/test_construction.py
index 3938d6acad2f0..0028f1e2edad5 100644
--- a/pandas/tests/indexes/timedeltas/test_construction.py
+++ b/pandas/tests/indexes/timedeltas/test_construction.py
@@ -168,10 +168,15 @@ def test_constructor_coverage(self):
tm.assert_index_equal(from_ints, expected)
# non-conforming freq
- pytest.raises(ValueError, TimedeltaIndex,
- ['1 days', '2 days', '4 days'], freq='D')
+ msg = ("Inferred frequency None from passed values does not conform to"
+ " passed frequency D")
+ with pytest.raises(ValueError, match=msg):
+ TimedeltaIndex(['1 days', '2 days', '4 days'], freq='D')
- pytest.raises(ValueError, timedelta_range, periods=10, freq='D')
+ msg = ("Of the four parameters: start, end, periods, and freq, exactly"
+ " three must be specified")
+ with pytest.raises(ValueError, match=msg):
+ timedelta_range(periods=10, freq='D')
def test_constructor_name(self):
idx = timedelta_range(start='1 days', periods=1, freq='D', name='TEST')
diff --git a/pandas/tests/indexes/timedeltas/test_ops.py b/pandas/tests/indexes/timedeltas/test_ops.py
index 40377e4362b75..63210f67c2dbd 100644
--- a/pandas/tests/indexes/timedeltas/test_ops.py
+++ b/pandas/tests/indexes/timedeltas/test_ops.py
@@ -71,7 +71,9 @@ def test_unknown_attribute(self):
tdi = pd.timedelta_range(start=0, periods=10, freq='1s')
ts = pd.Series(np.random.normal(size=10), index=tdi)
assert 'foo' not in ts.__dict__.keys()
- pytest.raises(AttributeError, lambda: ts.foo)
+ msg = "'Series' object has no attribute 'foo'"
+ with pytest.raises(AttributeError, match=msg):
+ ts.foo
def test_order(self):
# GH 10295
diff --git a/pandas/tests/indexes/timedeltas/test_partial_slicing.py b/pandas/tests/indexes/timedeltas/test_partial_slicing.py
index 62bf2a0b4a1cf..9fce1c9acd488 100644
--- a/pandas/tests/indexes/timedeltas/test_partial_slicing.py
+++ b/pandas/tests/indexes/timedeltas/test_partial_slicing.py
@@ -31,7 +31,9 @@ def test_partial_slice(self):
result = s['6 days, 23:11:12']
assert result == s.iloc[133]
- pytest.raises(KeyError, s.__getitem__, '50 days')
+ msg = r"^Timedelta\('50 days 00:00:00'\)$"
+ with pytest.raises(KeyError, match=msg):
+ s['50 days']
def test_partial_slice_high_reso(self):
diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py
index 3cbd9942f9d84..062e1c1e9f46d 100644
--- a/pandas/tests/indexes/timedeltas/test_timedelta.py
+++ b/pandas/tests/indexes/timedeltas/test_timedelta.py
@@ -264,9 +264,13 @@ def test_fields(self):
tm.assert_index_equal(rng.nanoseconds,
Index([456, 456], dtype='int64'))
- pytest.raises(AttributeError, lambda: rng.hours)
- pytest.raises(AttributeError, lambda: rng.minutes)
- pytest.raises(AttributeError, lambda: rng.milliseconds)
+ msg = "'TimedeltaIndex' object has no attribute '{}'"
+ with pytest.raises(AttributeError, match=msg.format('hours')):
+ rng.hours
+ with pytest.raises(AttributeError, match=msg.format('minutes')):
+ rng.minutes
+ with pytest.raises(AttributeError, match=msg.format('milliseconds')):
+ rng.milliseconds
# with nat
s = Series(rng)
diff --git a/pandas/tests/indexes/timedeltas/test_tools.py b/pandas/tests/indexes/timedeltas/test_tools.py
index d211219159233..58482a174dfd1 100644
--- a/pandas/tests/indexes/timedeltas/test_tools.py
+++ b/pandas/tests/indexes/timedeltas/test_tools.py
@@ -115,14 +115,22 @@ def test_to_timedelta_invalid(self):
to_timedelta(['foo'], errors='never')
# these will error
- pytest.raises(ValueError, lambda: to_timedelta([1, 2], unit='foo'))
- pytest.raises(ValueError, lambda: to_timedelta(1, unit='foo'))
+ msg = "invalid unit abbreviation: foo"
+ with pytest.raises(ValueError, match=msg):
+ to_timedelta([1, 2], unit='foo')
+ with pytest.raises(ValueError, match=msg):
+ to_timedelta(1, unit='foo')
# time not supported ATM
- pytest.raises(ValueError, lambda: to_timedelta(time(second=1)))
+ msg = ("Value must be Timedelta, string, integer, float, timedelta or"
+ " convertible")
+ with pytest.raises(ValueError, match=msg):
+ to_timedelta(time(second=1))
assert to_timedelta(time(second=1), errors='coerce') is pd.NaT
- pytest.raises(ValueError, lambda: to_timedelta(['foo', 'bar']))
+ msg = "unit abbreviation w/o a number"
+ with pytest.raises(ValueError, match=msg):
+ to_timedelta(['foo', 'bar'])
tm.assert_index_equal(TimedeltaIndex([pd.NaT, pd.NaT]),
to_timedelta(['foo', 'bar'], errors='coerce'))
| xref #24332 | https://api.github.com/repos/pandas-dev/pandas/pulls/25447 | 2019-02-26T12:58:33Z | 2019-02-28T13:33:32Z | 2019-02-28T13:33:32Z | 2019-02-28T14:29:25Z |
BUG: repr of np.datetime64('NaT') in Series/DataFrame with dtype object | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 99b57e2427509..89e14074ae75b 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -395,7 +395,7 @@ Sparse
Other
^^^^^
--
+- Bug in :class:`Series` and :class:`DataFrame` repr where ``np.datetime64('NaT')`` and ``np.timedelta64('NaT')`` with ``dtype=object`` would be represented as ``NaN`` (:issue:`25445`)
-
-
diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py
index dbe6b282ce9c0..1d08d559cb33f 100644
--- a/pandas/io/formats/format.py
+++ b/pandas/io/formats/format.py
@@ -941,10 +941,16 @@ def _format_strings(self):
def _format(x):
if self.na_rep is not None and is_scalar(x) and isna(x):
- if x is None:
- return 'None'
- elif x is NaT:
- return 'NaT'
+ try:
+ # try block for np.isnat specifically
+ # determine na_rep if x is None or NaT-like
+ if x is None:
+ return 'None'
+ elif x is NaT or np.isnat(x):
+ return 'NaT'
+ except (TypeError, ValueError):
+ # np.isnat only handles datetime or timedelta objects
+ pass
return self.na_rep
elif isinstance(x, PandasObject):
return '{x}'.format(x=x)
diff --git a/pandas/tests/frame/test_repr_info.py b/pandas/tests/frame/test_repr_info.py
index c77c9d9143e38..e4f0b4c6459ae 100644
--- a/pandas/tests/frame/test_repr_info.py
+++ b/pandas/tests/frame/test_repr_info.py
@@ -512,3 +512,12 @@ def test_repr_categorical_dates_periods(self):
df = DataFrame({'dt': Categorical(dt), 'p': Categorical(p)})
assert repr(df) == exp
+
+ @pytest.mark.parametrize('arg', [np.datetime64, np.timedelta64])
+ @pytest.mark.parametrize('box, expected', [
+ [Series, '0 NaT\ndtype: object'],
+ [DataFrame, ' 0\n0 NaT']])
+ def test_repr_np_nat_with_object(self, arg, box, expected):
+ # GH 25445
+ result = repr(box([arg('NaT')], dtype=object))
+ assert result == expected
| - [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Discovered while investigating #12499
Before:
```
In [1]: pd.Series([np.datetime64('NaT')], dtype=object)
Out[1]:
0 NaN
dtype: object
```
After:
```
In [1]: pd.Series([np.datetime64('NaT')], dtype=object)
Out[1]:
0 NaT
dtype: object
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/25445 | 2019-02-26T07:17:47Z | 2019-03-30T17:37:25Z | 2019-03-30T17:37:25Z | 2019-03-30T19:35:33Z |
ENH: added optional caption and label arguments to DataFrame.to_latex() | diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index cd0714838a3f1..4090a07fee5a5 100644
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -20,8 +20,7 @@ including other versions of pandas.
Enhancements
~~~~~~~~~~~~
-
--
+- :meth:`DataFrame.to_latex` now accepts ``caption`` and ``label`` arguments (:issue:`25436`)
-
.. _whatsnew_1000.enhancements.other:
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 1a5b36b07e93c..b427b1f0ac858 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2925,15 +2925,21 @@ def to_latex(
multicolumn=None,
multicolumn_format=None,
multirow=None,
+ caption=None,
+ label=None,
):
r"""
- Render an object to a LaTeX tabular environment table.
+ Render object to a LaTeX tabular, longtable, or nested table/tabular.
- Render an object to a tabular environment table. You can splice
- this into a LaTeX document. Requires \usepackage{booktabs}.
+ Requires ``\usepackage{booktabs}``. The output can be copy/pasted
+ into a main LaTeX document or read from an external file
+ with ``\input{table.tex}``.
.. versionchanged:: 0.20.2
- Added to Series
+ Added to Series.
+
+ .. versionchanged:: 1.0.0
+ Added caption and label arguments.
Parameters
----------
@@ -3002,6 +3008,17 @@ def to_latex(
from the pandas config module.
.. versionadded:: 0.20.0
+
+ caption : str, optional
+ The LaTeX caption to be placed inside ``\caption{}`` in the output.
+
+ .. versionadded:: 1.0.0
+
+ label : str, optional
+ The LaTeX label to be placed inside ``\label{}`` in the output.
+ This is used with ``\ref{}`` in the main ``.tex`` file.
+
+ .. versionadded:: 1.0.0
%(returns)s
See Also
--------
@@ -3014,7 +3031,7 @@ def to_latex(
>>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'],
... 'mask': ['red', 'purple'],
... 'weapon': ['sai', 'bo staff']})
- >>> print(df.to_latex(index=False)) # doctest: +NORMALIZE_WHITESPACE
+ >>> print(df.to_latex(index=False)) # doctest: +NORMALIZE_WHITESPACE
\begin{tabular}{lll}
\toprule
name & mask & weapon \\
@@ -3061,6 +3078,8 @@ def to_latex(
multicolumn=multicolumn,
multicolumn_format=multicolumn_format,
multirow=multirow,
+ caption=caption,
+ label=label,
)
def to_csv(
diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py
index 8ff4b9bda0430..f8db1b19dadfa 100644
--- a/pandas/io/formats/format.py
+++ b/pandas/io/formats/format.py
@@ -888,6 +888,8 @@ def to_latex(
multicolumn: bool = False,
multicolumn_format: Optional[str] = None,
multirow: bool = False,
+ caption: Optional[str] = None,
+ label: Optional[str] = None,
) -> Optional[str]:
"""
Render a DataFrame to a LaTeX tabular/longtable environment output.
@@ -902,6 +904,8 @@ def to_latex(
multicolumn=multicolumn,
multicolumn_format=multicolumn_format,
multirow=multirow,
+ caption=caption,
+ label=label,
).get_result(buf=buf, encoding=encoding)
def _format_col(self, i: int) -> List[str]:
diff --git a/pandas/io/formats/latex.py b/pandas/io/formats/latex.py
index 4c4d5ec73269a..ca9db88ae7be4 100644
--- a/pandas/io/formats/latex.py
+++ b/pandas/io/formats/latex.py
@@ -36,6 +36,8 @@ def __init__(
multicolumn: bool = False,
multicolumn_format: Optional[str] = None,
multirow: bool = False,
+ caption: Optional[str] = None,
+ label: Optional[str] = None,
):
self.fmt = formatter
self.frame = self.fmt.frame
@@ -45,11 +47,14 @@ def __init__(
self.multicolumn = multicolumn
self.multicolumn_format = multicolumn_format
self.multirow = multirow
+ self.caption = caption
+ self.label = label
self.escape = self.fmt.escape
def write_result(self, buf: IO[str]) -> None:
"""
- Render a DataFrame to a LaTeX tabular/longtable environment output.
+ Render a DataFrame to a LaTeX tabular, longtable, or table/tabular
+ environment output.
"""
# string representation of the columns
@@ -114,12 +119,12 @@ def pad_empties(x):
"not {typ}".format(typ=type(column_format))
)
- if not self.longtable:
- buf.write("\\begin{{tabular}}{{{fmt}}}\n".format(fmt=column_format))
- buf.write("\\toprule\n")
+ if self.longtable:
+ self._write_longtable_begin(buf, column_format)
else:
- buf.write("\\begin{{longtable}}{{{fmt}}}\n".format(fmt=column_format))
- buf.write("\\toprule\n")
+ self._write_tabular_begin(buf, column_format)
+
+ buf.write("\\toprule\n")
ilevels = self.frame.index.nlevels
clevels = self.frame.columns.nlevels
@@ -183,11 +188,10 @@ def pad_empties(x):
if self.multirow and i < len(strrows) - 1:
self._print_cline(buf, i, len(strcols))
- if not self.longtable:
- buf.write("\\bottomrule\n")
- buf.write("\\end{tabular}\n")
+ if self.longtable:
+ self._write_longtable_end(buf)
else:
- buf.write("\\end{longtable}\n")
+ self._write_tabular_end(buf)
def _format_multicolumn(self, row: List[str], ilevels: int) -> List[str]:
r"""
@@ -268,3 +272,107 @@ def _print_cline(self, buf: IO[str], i: int, icol: int) -> None:
buf.write("\\cline{{{cl:d}-{icol:d}}}\n".format(cl=cl[1], icol=icol))
# remove entries that have been written to buffer
self.clinebuf = [x for x in self.clinebuf if x[0] != i]
+
+ def _write_tabular_begin(self, buf, column_format):
+ """
+ Write the beginning of a tabular environment or
+ nested table/tabular environments including caption and label.
+
+ Parameters
+ ----------
+ buf : string or file handle
+ File path or object. If not specified, the result is returned as
+ a string.
+ column_format : str, default None
+ The columns format as specified in `LaTeX table format
+ <https://en.wikibooks.org/wiki/LaTeX/Tables>`__ e.g 'rcl'
+ for 3 columns
+
+ """
+ if self.caption is not None or self.label is not None:
+ # then write output in a nested table/tabular environment
+ if self.caption is None:
+ caption_ = ""
+ else:
+ caption_ = "\n\\caption{{{}}}".format(self.caption)
+
+ if self.label is None:
+ label_ = ""
+ else:
+ label_ = "\n\\label{{{}}}".format(self.label)
+
+ buf.write("\\begin{{table}}\n\\centering{}{}\n".format(caption_, label_))
+ else:
+ # then write output only in a tabular environment
+ pass
+
+ buf.write("\\begin{{tabular}}{{{fmt}}}\n".format(fmt=column_format))
+
+ def _write_tabular_end(self, buf):
+ """
+ Write the end of a tabular environment or nested table/tabular
+ environment.
+
+ Parameters
+ ----------
+ buf : string or file handle
+ File path or object. If not specified, the result is returned as
+ a string.
+
+ """
+ buf.write("\\bottomrule\n")
+ buf.write("\\end{tabular}\n")
+ if self.caption is not None or self.label is not None:
+ buf.write("\\end{table}\n")
+ else:
+ pass
+
+ def _write_longtable_begin(self, buf, column_format):
+ """
+ Write the beginning of a longtable environment including caption and
+ label if provided by user.
+
+ Parameters
+ ----------
+ buf : string or file handle
+ File path or object. If not specified, the result is returned as
+ a string.
+ column_format : str, default None
+ The columns format as specified in `LaTeX table format
+ <https://en.wikibooks.org/wiki/LaTeX/Tables>`__ e.g 'rcl'
+ for 3 columns
+
+ """
+ buf.write("\\begin{{longtable}}{{{fmt}}}\n".format(fmt=column_format))
+
+ if self.caption is not None or self.label is not None:
+ if self.caption is None:
+ pass
+ else:
+ buf.write("\\caption{{{}}}".format(self.caption))
+
+ if self.label is None:
+ pass
+ else:
+ buf.write("\\label{{{}}}".format(self.label))
+
+ # a double-backslash is required at the end of the line
+ # as discussed here:
+ # https://tex.stackexchange.com/questions/219138
+ buf.write("\\\\\n")
+ else:
+ pass
+
+ @staticmethod
+ def _write_longtable_end(buf):
+ """
+ Write the end of a longtable environment.
+
+ Parameters
+ ----------
+ buf : string or file handle
+ File path or object. If not specified, the result is returned as
+ a string.
+
+ """
+ buf.write("\\end{longtable}\n")
diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py
index 924b2a19e8504..9ffb54d23e37e 100644
--- a/pandas/tests/io/formats/test_to_latex.py
+++ b/pandas/tests/io/formats/test_to_latex.py
@@ -388,8 +388,7 @@ def test_to_latex_special_escape(self):
"""
assert escaped_result == escaped_expected
- def test_to_latex_longtable(self, float_frame):
- float_frame.to_latex(longtable=True)
+ def test_to_latex_longtable(self):
df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})
withindex_result = df.to_latex(longtable=True)
@@ -439,6 +438,141 @@ def test_to_latex_longtable(self, float_frame):
with3columns_result = df.to_latex(index=False, longtable=True)
assert r"\multicolumn{3}" in with3columns_result
+ def test_to_latex_caption_label(self):
+ # GH 25436
+ the_caption = "a table in a \\texttt{table/tabular} environment"
+ the_label = "tab:table_tabular"
+
+ df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})
+
+ # test when only the caption is provided
+ result_c = df.to_latex(caption=the_caption)
+
+ expected_c = r"""\begin{table}
+\centering
+\caption{a table in a \texttt{table/tabular} environment}
+\begin{tabular}{lrl}
+\toprule
+{} & a & b \\
+\midrule
+0 & 1 & b1 \\
+1 & 2 & b2 \\
+\bottomrule
+\end{tabular}
+\end{table}
+"""
+ assert result_c == expected_c
+
+ # test when only the label is provided
+ result_l = df.to_latex(label=the_label)
+
+ expected_l = r"""\begin{table}
+\centering
+\label{tab:table_tabular}
+\begin{tabular}{lrl}
+\toprule
+{} & a & b \\
+\midrule
+0 & 1 & b1 \\
+1 & 2 & b2 \\
+\bottomrule
+\end{tabular}
+\end{table}
+"""
+ assert result_l == expected_l
+
+ # test when the caption and the label are provided
+ result_cl = df.to_latex(caption=the_caption, label=the_label)
+
+ expected_cl = r"""\begin{table}
+\centering
+\caption{a table in a \texttt{table/tabular} environment}
+\label{tab:table_tabular}
+\begin{tabular}{lrl}
+\toprule
+{} & a & b \\
+\midrule
+0 & 1 & b1 \\
+1 & 2 & b2 \\
+\bottomrule
+\end{tabular}
+\end{table}
+"""
+ assert result_cl == expected_cl
+
+ def test_to_latex_longtable_caption_label(self):
+ # GH 25436
+ the_caption = "a table in a \\texttt{longtable} environment"
+ the_label = "tab:longtable"
+
+ df = DataFrame({"a": [1, 2], "b": ["b1", "b2"]})
+
+ # test when only the caption is provided
+ result_c = df.to_latex(longtable=True, caption=the_caption)
+
+ expected_c = r"""\begin{longtable}{lrl}
+\caption{a table in a \texttt{longtable} environment}\\
+\toprule
+{} & a & b \\
+\midrule
+\endhead
+\midrule
+\multicolumn{3}{r}{{Continued on next page}} \\
+\midrule
+\endfoot
+
+\bottomrule
+\endlastfoot
+0 & 1 & b1 \\
+1 & 2 & b2 \\
+\end{longtable}
+"""
+ assert result_c == expected_c
+
+ # test when only the label is provided
+ result_l = df.to_latex(longtable=True, label=the_label)
+
+ expected_l = r"""\begin{longtable}{lrl}
+\label{tab:longtable}\\
+\toprule
+{} & a & b \\
+\midrule
+\endhead
+\midrule
+\multicolumn{3}{r}{{Continued on next page}} \\
+\midrule
+\endfoot
+
+\bottomrule
+\endlastfoot
+0 & 1 & b1 \\
+1 & 2 & b2 \\
+\end{longtable}
+"""
+ assert result_l == expected_l
+
+ # test when the caption and the label are provided
+ result_cl = df.to_latex(longtable=True, caption=the_caption, label=the_label)
+
+ expected_cl = r"""\begin{longtable}{lrl}
+\caption{a table in a \texttt{longtable} environment}\label{tab:longtable}\\
+\toprule
+{} & a & b \\
+\midrule
+\endhead
+\midrule
+\multicolumn{3}{r}{{Continued on next page}} \\
+\midrule
+\endfoot
+
+\bottomrule
+\endlastfoot
+0 & 1 & b1 \\
+1 & 2 & b2 \\
+\end{longtable}
+"""
+ assert result_cl == expected_cl
+
def test_to_latex_escape_special_chars(self):
special_characters = ["&", "%", "$", "#", "_", "{", "}", "~", "^", "\\"]
df = DataFrame(data=special_characters)
| - [x] closes #25436
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25437 | 2019-02-25T06:20:07Z | 2019-09-03T19:26:02Z | 2019-09-03T19:26:02Z | 2019-09-03T19:26:17Z |
BUG: Fix index type casting in read_json with orient='table' and float index (#25433) | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 170e7f14da397..642093db3ded6 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -194,6 +194,8 @@ I/O
- Fixed bug in missing text when using :meth:`to_clipboard` if copying utf-16 characters in Python 3 on Windows (:issue:`25040`)
- Bug in :func:`read_json` for ``orient='table'`` when it tries to infer dtypes by default, which is not applicable as dtypes are already defined in the JSON schema (:issue:`21345`)
+- Bug in :func:`read_json` for ``orient='table'`` and float index, as it infers index dtype by default, which is not applicable because index dtype is already defined in the JSON schema (:issue:`25433`)
+- Bug in :func:`read_json` for ``orient='table'`` and string of float column names, as it makes a column name type conversion to Timestamp, which is not applicable because column names are already defined in the JSON schema (:issue:`25435`)
-
-
-
diff --git a/pandas/io/json/json.py b/pandas/io/json/json.py
index 725e2d28ffd67..4bae067ee5196 100644
--- a/pandas/io/json/json.py
+++ b/pandas/io/json/json.py
@@ -227,7 +227,7 @@ def _write(self, obj, orient, double_precision, ensure_ascii,
def read_json(path_or_buf=None, orient=None, typ='frame', dtype=None,
- convert_axes=True, convert_dates=True, keep_default_dates=True,
+ convert_axes=None, convert_dates=True, keep_default_dates=True,
numpy=False, precise_float=False, date_unit=None, encoding=None,
lines=False, chunksize=None, compression='infer'):
"""
@@ -277,18 +277,25 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=None,
'table' as an allowed value for the ``orient`` argument
typ : type of object to recover (series or frame), default 'frame'
- dtype : boolean or dict, default True
+ dtype : boolean or dict, default None
If True, infer dtypes; if a dict of column to dtype, then use those;
if False, then don't infer dtypes at all, applies only to the data.
- Not applicable with ``orient='table'``.
+ For all ``orient`` values except ``'table'``, default is True.
- .. versionchanged:: 0.25
+ .. versionchanged:: 0.25.0
- Not applicable with ``orient='table'``.
+ Not applicable for ``orient='table'``.
- convert_axes : boolean, default True
+ convert_axes : boolean, default None
Try to convert the axes to the proper dtypes.
+
+ For all ``orient`` values except ``'table'``, default is True.
+
+ .. versionchanged:: 0.25.0
+
+ Not applicable for ``orient='table'``.
+
convert_dates : boolean, default True
List of columns to parse for dates; If True, then try to parse
datelike columns default is True; a column label is datelike if
@@ -417,8 +424,13 @@ def read_json(path_or_buf=None, orient=None, typ='frame', dtype=None,
if orient == 'table' and dtype:
raise ValueError("cannot pass both dtype and orient='table'")
+ if orient == 'table' and convert_axes:
+ raise ValueError("cannot pass both convert_axes and orient='table'")
- dtype = orient != 'table' if dtype is None else dtype
+ if dtype is None and orient != 'table':
+ dtype = True
+ if convert_axes is None and orient != 'table':
+ convert_axes = True
compression = _infer_compression(path_or_buf, compression)
filepath_or_buffer, _, compression, should_close = get_filepath_or_buffer(
@@ -692,7 +704,7 @@ def _try_convert_data(self, name, data, use_dtypes=True,
# don't try to coerce, unless a force conversion
if use_dtypes:
- if self.dtype is False:
+ if not self.dtype:
return data, False
elif self.dtype is True:
pass
diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py
index 3002d1dfb5f8a..351b495e5d8fc 100644
--- a/pandas/tests/io/json/test_json_table_schema.py
+++ b/pandas/tests/io/json/test_json_table_schema.py
@@ -564,17 +564,10 @@ def test_multiindex(self, index_names):
result = pd.read_json(out, orient="table")
tm.assert_frame_equal(df, result)
- @pytest.mark.parametrize("strict_check", [
- pytest.param(True, marks=pytest.mark.xfail),
- False
- ])
- def test_empty_frame_roundtrip(self, strict_check):
+ def test_empty_frame_roundtrip(self):
# GH 21287
df = pd.DataFrame([], columns=['a', 'b', 'c'])
expected = df.copy()
out = df.to_json(orient='table')
result = pd.read_json(out, orient='table')
- # TODO: When DF coercion issue (#21345) is resolved tighten type checks
- tm.assert_frame_equal(expected, result,
- check_dtype=strict_check,
- check_index_type=strict_check)
+ tm.assert_frame_equal(expected, result)
diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py
index fecd0f0572757..ed598b730d960 100644
--- a/pandas/tests/io/json/test_pandas.py
+++ b/pandas/tests/io/json/test_pandas.py
@@ -194,7 +194,7 @@ def _check_orient(df, orient, dtype=None, numpy=False,
else:
unser = unser.sort_index()
- if dtype is False:
+ if not dtype:
check_dtype = False
if not convert_axes and df.index.dtype.type == np.datetime64:
@@ -1202,6 +1202,16 @@ def test_data_frame_size_after_to_json(self):
assert size_before == size_after
+ @pytest.mark.parametrize('index', [None, [1, 2], [1., 2.], ['a', 'b'],
+ ['1', '2'], ['1.', '2.']])
+ @pytest.mark.parametrize('columns', [['a', 'b'], ['1', '2'], ['1.', '2.']])
+ def test_from_json_to_json_table_index_and_columns(self, index, columns):
+ # GH25433 GH25435
+ expected = DataFrame([[1, 2], [3, 4]], index=index, columns=columns)
+ dfjson = expected.to_json(orient='table')
+ result = pd.read_json(dfjson, orient='table')
+ assert_frame_equal(result, expected)
+
def test_from_json_to_json_table_dtypes(self):
# GH21345
expected = pd.DataFrame({'a': [1, 2], 'b': [3., 4.], 'c': ['5', '6']})
@@ -1214,9 +1224,18 @@ def test_read_json_table_dtype_raises(self, dtype):
# GH21345
df = pd.DataFrame({'a': [1, 2], 'b': [3., 4.], 'c': ['5', '6']})
dfjson = df.to_json(orient='table')
- with pytest.raises(ValueError):
+ msg = "cannot pass both dtype and orient='table'"
+ with pytest.raises(ValueError, match=msg):
pd.read_json(dfjson, orient='table', dtype=dtype)
+ def test_read_json_table_convert_axes_raises(self):
+ # GH25433 GH25435
+ df = DataFrame([[1, 2], [3, 4]], index=[1., 2.], columns=['1.', '2.'])
+ dfjson = df.to_json(orient='table')
+ msg = "cannot pass both convert_axes and orient='table'"
+ with pytest.raises(ValueError, match=msg):
+ pd.read_json(dfjson, orient='table', convert_axes=True)
+
@pytest.mark.parametrize('data, expected', [
(DataFrame([[1, 2], [4, 5]], columns=['a', 'b']),
{'columns': ['a', 'b'], 'data': [[1, 2], [4, 5]]}),
| closes #25433
closes #25435
- [X] tests added / passed
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [X] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25434 | 2019-02-24T20:47:52Z | 2019-02-28T15:53:31Z | 2019-02-28T15:53:30Z | 2019-02-28T15:53:36Z |
TST: numpy RuntimeWarning with Series.round() | diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py
index 2e690ebbfa121..43a45bb915819 100644
--- a/pandas/tests/frame/test_analytics.py
+++ b/pandas/tests/frame/test_analytics.py
@@ -8,7 +8,7 @@
import numpy as np
import pytest
-from pandas.compat import PY35, lrange
+from pandas.compat import PY2, PY35, is_platform_windows, lrange
import pandas.util._test_decorators as td
import pandas as pd
@@ -1842,6 +1842,17 @@ def test_numpy_round(self):
with pytest.raises(ValueError, match=msg):
np.round(df, decimals=0, out=df)
+ @pytest.mark.xfail(
+ PY2 and is_platform_windows(), reason="numpy/numpy#7882",
+ raises=AssertionError, strict=True)
+ def test_numpy_round_nan(self):
+ # See gh-14197
+ df = Series([1.53, np.nan, 0.06]).to_frame()
+ with tm.assert_produces_warning(None):
+ result = df.round()
+ expected = Series([2., np.nan, 0.]).to_frame()
+ tm.assert_frame_equal(result, expected)
+
def test_round_mixed_type(self):
# GH 11885
df = DataFrame({'col1': [1.1, 2.2, 3.3, 4.4],
diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py
index 6811e370726b2..1f265d574da15 100644
--- a/pandas/tests/series/test_analytics.py
+++ b/pandas/tests/series/test_analytics.py
@@ -9,7 +9,7 @@
from numpy import nan
import pytest
-from pandas.compat import PY35, lrange, range
+from pandas.compat import PY2, PY35, is_platform_windows, lrange, range
import pandas.util._test_decorators as td
import pandas as pd
@@ -285,6 +285,17 @@ def test_numpy_round(self):
with pytest.raises(ValueError, match=msg):
np.round(s, decimals=0, out=s)
+ @pytest.mark.xfail(
+ PY2 and is_platform_windows(), reason="numpy/numpy#7882",
+ raises=AssertionError, strict=True)
+ def test_numpy_round_nan(self):
+ # See gh-14197
+ s = Series([1.53, np.nan, 0.06])
+ with tm.assert_produces_warning(None):
+ result = s.round()
+ expected = Series([2., np.nan, 0.])
+ assert_series_equal(result, expected)
+
def test_built_in_round(self):
if not compat.PY3:
pytest.skip(
| - [x] closes #14197
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ n/a] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25432 | 2019-02-24T15:57:21Z | 2019-02-27T14:40:33Z | 2019-02-27T14:40:33Z | 2019-02-28T09:19:05Z |
[BUG] maybe_upcast_putmast also handle ndarray | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 1823a8e8654fd..6ac7fdd2434c7 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -169,7 +169,10 @@ def trans(x): # noqa
def maybe_upcast_putmask(result, mask, other):
"""
- A safe version of putmask that potentially upcasts the result
+ A safe version of putmask that potentially upcasts the result.
+ The result is replaced with the first N elements of other,
+ where N is the number of True values in mask.
+ If the length of other is shorter than N, other will be repeated.
Parameters
----------
@@ -185,8 +188,18 @@ def maybe_upcast_putmask(result, mask, other):
result : ndarray
changed : boolean
Set to true if the result array was upcasted
+
+ Examples
+ --------
+ >>> result, _ = maybe_upcast_putmask(np.arange(1,6),
+ np.array([False, True, False, True, True]), np.arange(21,23))
+ >>> result
+ array([1, 21, 3, 22, 21])
"""
+ if not isinstance(result, np.ndarray):
+ raise ValueError("The result input must be a ndarray.")
+
if mask.any():
# Two conversions for date-like dtypes that can't be done automatically
# in np.place:
@@ -241,7 +254,7 @@ def changeit():
# we have an ndarray and the masking has nans in it
else:
- if isna(other[mask]).any():
+ if isna(other).any():
return changeit()
try:
diff --git a/pandas/tests/dtypes/cast/test_upcast.py b/pandas/tests/dtypes/cast/test_upcast.py
new file mode 100644
index 0000000000000..074e89274cc88
--- /dev/null
+++ b/pandas/tests/dtypes/cast/test_upcast.py
@@ -0,0 +1,66 @@
+# -*- coding: utf-8 -*-
+
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.cast import maybe_upcast_putmask
+
+from pandas import Series
+from pandas.util import testing as tm
+
+
+@pytest.mark.parametrize("result", [
+ Series([10, 11, 12]),
+ [10, 11, 12],
+ (10, 11, 12)
+])
+def test_upcast_error(result):
+ # GH23823
+ mask = np.array([False, True, False])
+ other = np.array([61, 62, 63])
+ with pytest.raises(ValueError):
+ result, _ = maybe_upcast_putmask(result, mask, other)
+
+
+@pytest.mark.parametrize("arr, other, exp_changed, expected", [
+ (np.arange(1, 6), np.array([61, 62, 63]),
+ False, np.array([1, 61, 3, 62, 63])),
+ (np.arange(1, 6), np.array([61.1, 62.2, 63.3]),
+ True, np.array([1, 61.1, 3, 62.2, 63.3])),
+ (np.arange(1, 6), np.nan,
+ True, np.array([1, np.nan, 3, np.nan, np.nan])),
+ (np.arange(10, 15), np.array([61, 62]),
+ False, np.array([10, 61, 12, 62, 61])),
+ (np.arange(10, 15), np.array([61, np.nan]),
+ True, np.array([10, 61, 12, np.nan, 61]))
+])
+def test_upcast(arr, other, exp_changed, expected):
+ # GH23823
+ mask = np.array([False, True, False, True, True])
+ result, changed = maybe_upcast_putmask(arr, mask, other)
+
+ assert changed == exp_changed
+ tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize("arr, other, exp_changed, expected", [
+ (np.arange('2019-01-01', '2019-01-06', dtype='datetime64[D]'),
+ np.arange('2018-01-01', '2018-01-04', dtype='datetime64[D]'),
+ False, np.array(['2019-01-01', '2018-01-01', '2019-01-03',
+ '2018-01-02', '2018-01-03'], dtype='datetime64[D]')),
+ (np.arange('2019-01-01', '2019-01-06', dtype='datetime64[D]'), np.nan,
+ False, np.array(['2019-01-01', np.datetime64('NaT'),
+ '2019-01-03', np.datetime64('NaT'),
+ np.datetime64('NaT')], dtype='datetime64[D]')),
+ (np.arange('2019-01-01', '2019-01-06', dtype='datetime64[D]'),
+ np.arange('2018-01-01', '2018-01-03', dtype='datetime64[D]'),
+ False, np.array(['2019-01-01', '2018-01-01', '2019-01-03',
+ '2018-01-02', '2018-01-01'], dtype='datetime64[D]'))
+])
+def test_upcast_datetime(arr, other, exp_changed, expected):
+ # GH23823
+ mask = np.array([False, True, False, True, True])
+ result, changed = maybe_upcast_putmask(arr, mask, other)
+
+ assert changed == exp_changed
+ tm.assert_numpy_array_equal(result, expected)
| - closes #23823
- 2 tests added
- passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- whatsnew entry
Follow h-vetinari's footstep. `maybe_upcast_putmask` was left untouched in #25425. Try to fix the bug so that `maybe_upcast_putmask` can also handle `ndarray` as well as `Series`.
| https://api.github.com/repos/pandas-dev/pandas/pulls/25431 | 2019-02-24T15:04:24Z | 2019-03-22T11:51:09Z | 2019-03-22T11:51:09Z | 2019-03-22T11:51:15Z |
TST/REF: Add pytest idiom to test_frequencies.py | diff --git a/pandas/tests/tseries/frequencies/__init__.py b/pandas/tests/tseries/frequencies/__init__.py
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/pandas/tests/tseries/frequencies/test_freq_code.py b/pandas/tests/tseries/frequencies/test_freq_code.py
new file mode 100644
index 0000000000000..0aa29e451b1ba
--- /dev/null
+++ b/pandas/tests/tseries/frequencies/test_freq_code.py
@@ -0,0 +1,149 @@
+import pytest
+
+from pandas._libs.tslibs import frequencies as libfrequencies, resolution
+from pandas._libs.tslibs.frequencies import (
+ FreqGroup, _period_code_map, get_freq, get_freq_code)
+import pandas.compat as compat
+
+import pandas.tseries.offsets as offsets
+
+
+@pytest.fixture(params=list(compat.iteritems(_period_code_map)))
+def period_code_item(request):
+ return request.param
+
+
+@pytest.mark.parametrize("freqstr,expected", [
+ ("A", 1000), ("3A", 1000), ("-1A", 1000),
+ ("Y", 1000), ("3Y", 1000), ("-1Y", 1000),
+ ("W", 4000), ("W-MON", 4001), ("W-FRI", 4005)
+])
+def test_freq_code(freqstr, expected):
+ assert get_freq(freqstr) == expected
+
+
+def test_freq_code_match(period_code_item):
+ freqstr, code = period_code_item
+ assert get_freq(freqstr) == code
+
+
+@pytest.mark.parametrize("freqstr,expected", [
+ ("A", 1000), ("3A", 1000), ("-1A", 1000), ("A-JAN", 1000),
+ ("A-MAY", 1000), ("Y", 1000), ("3Y", 1000), ("-1Y", 1000),
+ ("Y-JAN", 1000), ("Y-MAY", 1000), (offsets.YearEnd(), 1000),
+ (offsets.YearEnd(month=1), 1000), (offsets.YearEnd(month=5), 1000),
+ ("W", 4000), ("W-MON", 4000), ("W-FRI", 4000), (offsets.Week(), 4000),
+ (offsets.Week(weekday=1), 4000), (offsets.Week(weekday=5), 4000),
+ ("T", FreqGroup.FR_MIN),
+])
+def test_freq_group(freqstr, expected):
+ assert resolution.get_freq_group(freqstr) == expected
+
+
+def test_freq_group_match(period_code_item):
+ freqstr, code = period_code_item
+
+ str_group = resolution.get_freq_group(freqstr)
+ code_group = resolution.get_freq_group(code)
+
+ assert str_group == code_group == code // 1000 * 1000
+
+
+@pytest.mark.parametrize("freqstr,exp_freqstr", [
+ ("D", "D"), ("W", "D"), ("M", "D"),
+ ("S", "S"), ("T", "S"), ("H", "S")
+])
+def test_get_to_timestamp_base(freqstr, exp_freqstr):
+ tsb = libfrequencies.get_to_timestamp_base
+
+ assert tsb(get_freq_code(freqstr)[0]) == get_freq_code(exp_freqstr)[0]
+
+
+_reso = resolution.Resolution
+
+
+@pytest.mark.parametrize("freqstr,expected", [
+ ("A", "year"), ("Q", "quarter"), ("M", "month"),
+ ("D", "day"), ("H", "hour"), ("T", "minute"),
+ ("S", "second"), ("L", "millisecond"),
+ ("U", "microsecond"), ("N", "nanosecond")
+])
+def test_get_str_from_freq(freqstr, expected):
+ assert _reso.get_str_from_freq(freqstr) == expected
+
+
+@pytest.mark.parametrize("freq", ["A", "Q", "M", "D", "H",
+ "T", "S", "L", "U", "N"])
+def test_get_freq_roundtrip(freq):
+ result = _reso.get_freq(_reso.get_str_from_freq(freq))
+ assert freq == result
+
+
+@pytest.mark.parametrize("freq", ["D", "H", "T", "S", "L", "U"])
+def test_get_freq_roundtrip2(freq):
+ result = _reso.get_freq(_reso.get_str(_reso.get_reso_from_freq(freq)))
+ assert freq == result
+
+
+@pytest.mark.parametrize("args,expected", [
+ ((1.5, "T"), (90, "S")), ((62.4, "T"), (3744, "S")),
+ ((1.04, "H"), (3744, "S")), ((1, "D"), (1, "D")),
+ ((0.342931, "H"), (1234551600, "U")), ((1.2345, "D"), (106660800, "L"))
+])
+def test_resolution_bumping(args, expected):
+ # see gh-14378
+ assert _reso.get_stride_from_decimal(*args) == expected
+
+
+@pytest.mark.parametrize("args", [
+ (0.5, "N"),
+
+ # Too much precision in the input can prevent.
+ (0.3429324798798269273987982, "H")
+])
+def test_cat(args):
+ msg = "Could not convert to integer offset at any resolution"
+
+ with pytest.raises(ValueError, match=msg):
+ _reso.get_stride_from_decimal(*args)
+
+
+@pytest.mark.parametrize("freq_input,expected", [
+ # Frequency string.
+ ("A", (get_freq("A"), 1)),
+ ("3D", (get_freq("D"), 3)),
+ ("-2M", (get_freq("M"), -2)),
+
+ # Tuple.
+ (("D", 1), (get_freq("D"), 1)),
+ (("A", 3), (get_freq("A"), 3)),
+ (("M", -2), (get_freq("M"), -2)),
+ ((5, "T"), (FreqGroup.FR_MIN, 5)),
+
+ # Numeric Tuple.
+ ((1000, 1), (1000, 1)),
+
+ # Offsets.
+ (offsets.Day(), (get_freq("D"), 1)),
+ (offsets.Day(3), (get_freq("D"), 3)),
+ (offsets.Day(-2), (get_freq("D"), -2)),
+ (offsets.MonthEnd(), (get_freq("M"), 1)),
+ (offsets.MonthEnd(3), (get_freq("M"), 3)),
+ (offsets.MonthEnd(-2), (get_freq("M"), -2)),
+ (offsets.Week(), (get_freq("W"), 1)),
+ (offsets.Week(3), (get_freq("W"), 3)),
+ (offsets.Week(-2), (get_freq("W"), -2)),
+ (offsets.Hour(), (FreqGroup.FR_HR, 1)),
+
+ # Monday is weekday=0.
+ (offsets.Week(weekday=1), (get_freq("W-TUE"), 1)),
+ (offsets.Week(3, weekday=0), (get_freq("W-MON"), 3)),
+ (offsets.Week(-2, weekday=4), (get_freq("W-FRI"), -2)),
+])
+def test_get_freq_code(freq_input, expected):
+ assert get_freq_code(freq_input) == expected
+
+
+def test_get_code_invalid():
+ with pytest.raises(ValueError, match="Invalid frequency"):
+ get_freq_code((5, "baz"))
diff --git a/pandas/tests/tseries/frequencies/test_inference.py b/pandas/tests/tseries/frequencies/test_inference.py
new file mode 100644
index 0000000000000..9e7ddbc45bba8
--- /dev/null
+++ b/pandas/tests/tseries/frequencies/test_inference.py
@@ -0,0 +1,406 @@
+from datetime import datetime, timedelta
+
+import numpy as np
+import pytest
+
+from pandas._libs.tslibs.ccalendar import DAYS, MONTHS
+from pandas._libs.tslibs.frequencies import INVALID_FREQ_ERR_MSG
+import pandas.compat as compat
+from pandas.compat import is_platform_windows, range
+
+from pandas import (
+ DatetimeIndex, Index, Series, Timestamp, date_range, period_range)
+from pandas.core.tools.datetimes import to_datetime
+import pandas.util.testing as tm
+
+import pandas.tseries.frequencies as frequencies
+import pandas.tseries.offsets as offsets
+
+
+def _check_generated_range(start, periods, freq):
+ """
+ Check the range generated from a given start, frequency, and period count.
+
+ Parameters
+ ----------
+ start : str
+ The start date.
+ periods : int
+ The number of periods.
+ freq : str
+ The frequency of the range.
+ """
+ freq = freq.upper()
+
+ gen = date_range(start, periods=periods, freq=freq)
+ index = DatetimeIndex(gen.values)
+
+ if not freq.startswith("Q-"):
+ assert frequencies.infer_freq(index) == gen.freqstr
+ else:
+ inf_freq = frequencies.infer_freq(index)
+ is_dec_range = inf_freq == "Q-DEC" and gen.freqstr in (
+ "Q", "Q-DEC", "Q-SEP", "Q-JUN", "Q-MAR")
+ is_nov_range = inf_freq == "Q-NOV" and gen.freqstr in (
+ "Q-NOV", "Q-AUG", "Q-MAY", "Q-FEB")
+ is_oct_range = inf_freq == "Q-OCT" and gen.freqstr in (
+ "Q-OCT", "Q-JUL", "Q-APR", "Q-JAN")
+ assert is_dec_range or is_nov_range or is_oct_range
+
+
+@pytest.fixture(params=[(timedelta(1), "D"),
+ (timedelta(hours=1), "H"),
+ (timedelta(minutes=1), "T"),
+ (timedelta(seconds=1), "S"),
+ (np.timedelta64(1, "ns"), "N"),
+ (timedelta(microseconds=1), "U"),
+ (timedelta(microseconds=1000), "L")])
+def base_delta_code_pair(request):
+ return request.param
+
+
+@pytest.fixture(params=[1, 2, 3, 4])
+def count(request):
+ return request.param
+
+
+@pytest.fixture(params=DAYS)
+def day(request):
+ return request.param
+
+
+@pytest.fixture(params=MONTHS)
+def month(request):
+ return request.param
+
+
+@pytest.fixture(params=[5, 7])
+def periods(request):
+ return request.param
+
+
+def test_raise_if_period_index():
+ index = period_range(start="1/1/1990", periods=20, freq="M")
+ msg = "Check the `freq` attribute instead of using infer_freq"
+
+ with pytest.raises(TypeError, match=msg):
+ frequencies.infer_freq(index)
+
+
+def test_raise_if_too_few():
+ index = DatetimeIndex(["12/31/1998", "1/3/1999"])
+ msg = "Need at least 3 dates to infer frequency"
+
+ with pytest.raises(ValueError, match=msg):
+ frequencies.infer_freq(index)
+
+
+def test_business_daily():
+ index = DatetimeIndex(["01/01/1999", "1/4/1999", "1/5/1999"])
+ assert frequencies.infer_freq(index) == "B"
+
+
+def test_business_daily_look_alike():
+ # see gh-16624
+ #
+ # Do not infer "B when "weekend" (2-day gap) in wrong place.
+ index = DatetimeIndex(["12/31/1998", "1/3/1999", "1/4/1999"])
+ assert frequencies.infer_freq(index) is None
+
+
+def test_day_corner():
+ index = DatetimeIndex(["1/1/2000", "1/2/2000", "1/3/2000"])
+ assert frequencies.infer_freq(index) == "D"
+
+
+def test_non_datetime_index():
+ dates = to_datetime(["1/1/2000", "1/2/2000", "1/3/2000"])
+ assert frequencies.infer_freq(dates) == "D"
+
+
+def test_fifth_week_of_month_infer():
+ # see gh-9425
+ #
+ # Only attempt to infer up to WOM-4.
+ index = DatetimeIndex(["2014-03-31", "2014-06-30", "2015-03-30"])
+ assert frequencies.infer_freq(index) is None
+
+
+def test_week_of_month_fake():
+ # All of these dates are on same day
+ # of week and are 4 or 5 weeks apart.
+ index = DatetimeIndex(["2013-08-27", "2013-10-01",
+ "2013-10-29", "2013-11-26"])
+ assert frequencies.infer_freq(index) != "WOM-4TUE"
+
+
+def test_fifth_week_of_month():
+ # see gh-9425
+ #
+ # Only supports freq up to WOM-4.
+ msg = ("Of the four parameters: start, end, periods, "
+ "and freq, exactly three must be specified")
+
+ with pytest.raises(ValueError, match=msg):
+ date_range("2014-01-01", freq="WOM-5MON")
+
+
+def test_monthly_ambiguous():
+ rng = DatetimeIndex(["1/31/2000", "2/29/2000", "3/31/2000"])
+ assert rng.inferred_freq == "M"
+
+
+def test_annual_ambiguous():
+ rng = DatetimeIndex(["1/31/2000", "1/31/2001", "1/31/2002"])
+ assert rng.inferred_freq == "A-JAN"
+
+
+def test_infer_freq_delta(base_delta_code_pair, count):
+ b = Timestamp(datetime.now())
+ base_delta, code = base_delta_code_pair
+
+ inc = base_delta * count
+ index = DatetimeIndex([b + inc * j for j in range(3)])
+
+ exp_freq = "%d%s" % (count, code) if count > 1 else code
+ assert frequencies.infer_freq(index) == exp_freq
+
+
+@pytest.mark.parametrize("constructor", [
+ lambda now, delta: DatetimeIndex([now + delta * 7] +
+ [now + delta * j for j in range(3)]),
+ lambda now, delta: DatetimeIndex([now + delta * j for j in range(3)] +
+ [now + delta * 7])
+])
+def test_infer_freq_custom(base_delta_code_pair, constructor):
+ b = Timestamp(datetime.now())
+ base_delta, _ = base_delta_code_pair
+
+ index = constructor(b, base_delta)
+ assert frequencies.infer_freq(index) is None
+
+
+def test_weekly_infer(periods, day):
+ _check_generated_range("1/1/2000", periods, "W-{day}".format(day=day))
+
+
+def test_week_of_month_infer(periods, day, count):
+ _check_generated_range("1/1/2000", periods,
+ "WOM-{count}{day}".format(count=count, day=day))
+
+
+@pytest.mark.parametrize("freq", ["M", "BM", "BMS"])
+def test_monthly_infer(periods, freq):
+ _check_generated_range("1/1/2000", periods, "M")
+
+
+def test_quarterly_infer(month, periods):
+ _check_generated_range("1/1/2000", periods,
+ "Q-{month}".format(month=month))
+
+
+@pytest.mark.parametrize("annual", ["A", "BA"])
+def test_annually_infer(month, periods, annual):
+ _check_generated_range("1/1/2000", periods,
+ "{annual}-{month}".format(annual=annual,
+ month=month))
+
+
+@pytest.mark.parametrize("freq,expected", [
+ ("Q", "Q-DEC"), ("Q-NOV", "Q-NOV"), ("Q-OCT", "Q-OCT")
+])
+def test_infer_freq_index(freq, expected):
+ rng = period_range("1959Q2", "2009Q3", freq=freq)
+ rng = Index(rng.to_timestamp("D", how="e").astype(object))
+
+ assert rng.inferred_freq == expected
+
+
+@pytest.mark.parametrize(
+ "expected,dates",
+ list(compat.iteritems(
+ {"AS-JAN": ["2009-01-01", "2010-01-01", "2011-01-01", "2012-01-01"],
+ "Q-OCT": ["2009-01-31", "2009-04-30", "2009-07-31", "2009-10-31"],
+ "M": ["2010-11-30", "2010-12-31", "2011-01-31", "2011-02-28"],
+ "W-SAT": ["2010-12-25", "2011-01-01", "2011-01-08", "2011-01-15"],
+ "D": ["2011-01-01", "2011-01-02", "2011-01-03", "2011-01-04"],
+ "H": ["2011-12-31 22:00", "2011-12-31 23:00",
+ "2012-01-01 00:00", "2012-01-01 01:00"]}))
+)
+def test_infer_freq_tz(tz_naive_fixture, expected, dates):
+ # see gh-7310
+ tz = tz_naive_fixture
+ idx = DatetimeIndex(dates, tz=tz)
+ assert idx.inferred_freq == expected
+
+
+@pytest.mark.parametrize("date_pair", [
+ ["2013-11-02", "2013-11-5"], # Fall DST
+ ["2014-03-08", "2014-03-11"], # Spring DST
+ ["2014-01-01", "2014-01-03"] # Regular Time
+])
+@pytest.mark.parametrize("freq", [
+ "3H", "10T", "3601S", "3600001L", "3600000001U", "3600000000001N"
+])
+def test_infer_freq_tz_transition(tz_naive_fixture, date_pair, freq):
+ # see gh-8772
+ tz = tz_naive_fixture
+ idx = date_range(date_pair[0], date_pair[1], freq=freq, tz=tz)
+ assert idx.inferred_freq == freq
+
+
+def test_infer_freq_tz_transition_custom():
+ index = date_range("2013-11-03", periods=5,
+ freq="3H").tz_localize("America/Chicago")
+ assert index.inferred_freq is None
+
+
+@pytest.mark.parametrize("data,expected", [
+ # Hourly freq in a day must result in "H"
+ (["2014-07-01 09:00", "2014-07-01 10:00", "2014-07-01 11:00",
+ "2014-07-01 12:00", "2014-07-01 13:00", "2014-07-01 14:00"], "H"),
+
+ (["2014-07-01 09:00", "2014-07-01 10:00", "2014-07-01 11:00",
+ "2014-07-01 12:00", "2014-07-01 13:00", "2014-07-01 14:00",
+ "2014-07-01 15:00", "2014-07-01 16:00", "2014-07-02 09:00",
+ "2014-07-02 10:00", "2014-07-02 11:00"], "BH"),
+ (["2014-07-04 09:00", "2014-07-04 10:00", "2014-07-04 11:00",
+ "2014-07-04 12:00", "2014-07-04 13:00", "2014-07-04 14:00",
+ "2014-07-04 15:00", "2014-07-04 16:00", "2014-07-07 09:00",
+ "2014-07-07 10:00", "2014-07-07 11:00"], "BH"),
+ (["2014-07-04 09:00", "2014-07-04 10:00", "2014-07-04 11:00",
+ "2014-07-04 12:00", "2014-07-04 13:00", "2014-07-04 14:00",
+ "2014-07-04 15:00", "2014-07-04 16:00", "2014-07-07 09:00",
+ "2014-07-07 10:00", "2014-07-07 11:00", "2014-07-07 12:00",
+ "2014-07-07 13:00", "2014-07-07 14:00", "2014-07-07 15:00",
+ "2014-07-07 16:00", "2014-07-08 09:00", "2014-07-08 10:00",
+ "2014-07-08 11:00", "2014-07-08 12:00", "2014-07-08 13:00",
+ "2014-07-08 14:00", "2014-07-08 15:00", "2014-07-08 16:00"], "BH"),
+])
+def test_infer_freq_business_hour(data, expected):
+ # see gh-7905
+ idx = DatetimeIndex(data)
+ assert idx.inferred_freq == expected
+
+
+def test_not_monotonic():
+ rng = DatetimeIndex(["1/31/2000", "1/31/2001", "1/31/2002"])
+ rng = rng[::-1]
+
+ assert rng.inferred_freq == "-1A-JAN"
+
+
+def test_non_datetime_index2():
+ rng = DatetimeIndex(["1/31/2000", "1/31/2001", "1/31/2002"])
+ vals = rng.to_pydatetime()
+
+ result = frequencies.infer_freq(vals)
+ assert result == rng.inferred_freq
+
+
+@pytest.mark.parametrize("idx", [
+ tm.makeIntIndex(10), tm.makeFloatIndex(10), tm.makePeriodIndex(10)
+])
+def test_invalid_index_types(idx):
+ msg = ("(cannot infer freq from a non-convertible)|"
+ "(Check the `freq` attribute instead of using infer_freq)")
+
+ with pytest.raises(TypeError, match=msg):
+ frequencies.infer_freq(idx)
+
+
+@pytest.mark.skipif(is_platform_windows(),
+ reason="see gh-10822: Windows issue")
+@pytest.mark.parametrize("idx", [tm.makeStringIndex(10),
+ tm.makeUnicodeIndex(10)])
+def test_invalid_index_types_unicode(idx):
+ # see gh-10822
+ #
+ # Odd error message on conversions to datetime for unicode.
+ msg = "Unknown string format"
+
+ with pytest.raises(ValueError, match=msg):
+ frequencies.infer_freq(idx)
+
+
+def test_string_datetime_like_compat():
+ # see gh-6463
+ data = ["2004-01", "2004-02", "2004-03", "2004-04"]
+
+ expected = frequencies.infer_freq(data)
+ result = frequencies.infer_freq(Index(data))
+
+ assert result == expected
+
+
+def test_series():
+ # see gh-6407
+ s = Series(date_range("20130101", "20130110"))
+ inferred = frequencies.infer_freq(s)
+ assert inferred == "D"
+
+
+@pytest.mark.parametrize("end", [10, 10.])
+def test_series_invalid_type(end):
+ # see gh-6407
+ msg = "cannot infer freq from a non-convertible dtype on a Series"
+ s = Series(np.arange(end))
+
+ with pytest.raises(TypeError, match=msg):
+ frequencies.infer_freq(s)
+
+
+def test_series_inconvertible_string():
+ # see gh-6407
+ msg = "Unknown string format"
+
+ with pytest.raises(ValueError, match=msg):
+ frequencies.infer_freq(Series(["foo", "bar"]))
+
+
+@pytest.mark.parametrize("freq", [None, "L"])
+def test_series_period_index(freq):
+ # see gh-6407
+ #
+ # Cannot infer on PeriodIndex
+ msg = "cannot infer freq from a non-convertible dtype on a Series"
+ s = Series(period_range("2013", periods=10, freq=freq))
+
+ with pytest.raises(TypeError, match=msg):
+ frequencies.infer_freq(s)
+
+
+@pytest.mark.parametrize("freq", ["M", "L", "S"])
+def test_series_datetime_index(freq):
+ s = Series(date_range("20130101", periods=10, freq=freq))
+ inferred = frequencies.infer_freq(s)
+ assert inferred == freq
+
+
+@pytest.mark.parametrize("offset_func", [
+ frequencies.get_offset,
+ lambda freq: date_range("2011-01-01", periods=5, freq=freq)
+])
+@pytest.mark.parametrize("freq", [
+ "WEEKDAY", "EOM", "W@MON", "W@TUE", "W@WED", "W@THU",
+ "W@FRI", "W@SAT", "W@SUN", "Q@JAN", "Q@FEB", "Q@MAR",
+ "A@JAN", "A@FEB", "A@MAR", "A@APR", "A@MAY", "A@JUN",
+ "A@JUL", "A@AUG", "A@SEP", "A@OCT", "A@NOV", "A@DEC",
+ "Y@JAN", "WOM@1MON", "WOM@2MON", "WOM@3MON",
+ "WOM@4MON", "WOM@1TUE", "WOM@2TUE", "WOM@3TUE",
+ "WOM@4TUE", "WOM@1WED", "WOM@2WED", "WOM@3WED",
+ "WOM@4WED", "WOM@1THU", "WOM@2THU", "WOM@3THU",
+ "WOM@4THU", "WOM@1FRI", "WOM@2FRI", "WOM@3FRI",
+ "WOM@4FRI"
+])
+def test_legacy_offset_warnings(offset_func, freq):
+ with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG):
+ offset_func(freq)
+
+
+def test_ms_vs_capital_ms():
+ left = frequencies.get_offset("ms")
+ right = frequencies.get_offset("MS")
+
+ assert left == offsets.Milli()
+ assert right == offsets.MonthBegin()
diff --git a/pandas/tests/tseries/frequencies/test_to_offset.py b/pandas/tests/tseries/frequencies/test_to_offset.py
new file mode 100644
index 0000000000000..c9c35b47f3475
--- /dev/null
+++ b/pandas/tests/tseries/frequencies/test_to_offset.py
@@ -0,0 +1,146 @@
+import re
+
+import pytest
+
+from pandas import Timedelta
+
+import pandas.tseries.frequencies as frequencies
+import pandas.tseries.offsets as offsets
+
+
+@pytest.mark.parametrize("freq_input,expected", [
+ (frequencies.to_offset("10us"), offsets.Micro(10)),
+ (offsets.Hour(), offsets.Hour()),
+ ((5, "T"), offsets.Minute(5)),
+ ("2h30min", offsets.Minute(150)),
+ ("2h 30min", offsets.Minute(150)),
+ ("2h30min15s", offsets.Second(150 * 60 + 15)),
+ ("2h 60min", offsets.Hour(3)),
+ ("2h 20.5min", offsets.Second(8430)),
+ ("1.5min", offsets.Second(90)),
+ ("0.5S", offsets.Milli(500)),
+ ("15l500u", offsets.Micro(15500)),
+ ("10s75L", offsets.Milli(10075)),
+ ("1s0.25ms", offsets.Micro(1000250)),
+ ("1s0.25L", offsets.Micro(1000250)),
+ ("2800N", offsets.Nano(2800)),
+ ("2SM", offsets.SemiMonthEnd(2)),
+ ("2SM-16", offsets.SemiMonthEnd(2, day_of_month=16)),
+ ("2SMS-14", offsets.SemiMonthBegin(2, day_of_month=14)),
+ ("2SMS-15", offsets.SemiMonthBegin(2)),
+])
+def test_to_offset(freq_input, expected):
+ result = frequencies.to_offset(freq_input)
+ assert result == expected
+
+
+@pytest.mark.parametrize("freqstr,expected", [
+ ("-1S", -1),
+ ("-2SM", -2),
+ ("-1SMS", -1),
+ ("-5min10s", -310),
+])
+def test_to_offset_negative(freqstr, expected):
+ result = frequencies.to_offset(freqstr)
+ assert result.n == expected
+
+
+@pytest.mark.parametrize("freqstr", [
+ "2h20m", "U1", "-U", "3U1", "-2-3U", "-2D:3H",
+ "1.5.0S", "2SMS-15-15", "2SMS-15D", "100foo",
+
+ # Invalid leading +/- signs.
+ "+-1d", "-+1h", "+1", "-7", "+d", "-m",
+
+ # Invalid shortcut anchors.
+ "SM-0", "SM-28", "SM-29", "SM-FOO", "BSM", "SM--1", "SMS-1",
+ "SMS-28", "SMS-30", "SMS-BAR", "SMS-BYR", "BSMS", "SMS--2"
+])
+def test_to_offset_invalid(freqstr):
+ # see gh-13930
+
+ # We escape string because some of our
+ # inputs contain regex special characters.
+ msg = re.escape("Invalid frequency: {freqstr}".format(freqstr=freqstr))
+ with pytest.raises(ValueError, match=msg):
+ frequencies.to_offset(freqstr)
+
+
+def test_to_offset_no_evaluate():
+ with pytest.raises(ValueError, match="Could not evaluate"):
+ frequencies.to_offset(("", ""))
+
+
+@pytest.mark.parametrize("freqstr,expected", [
+ ("2D 3H", offsets.Hour(51)),
+ ("2 D3 H", offsets.Hour(51)),
+ ("2 D 3 H", offsets.Hour(51)),
+ (" 2 D 3 H ", offsets.Hour(51)),
+ (" H ", offsets.Hour()),
+ (" 3 H ", offsets.Hour(3)),
+])
+def test_to_offset_whitespace(freqstr, expected):
+ result = frequencies.to_offset(freqstr)
+ assert result == expected
+
+
+@pytest.mark.parametrize("freqstr,expected", [
+ ("00H 00T 01S", 1),
+ ("-00H 03T 14S", -194),
+])
+def test_to_offset_leading_zero(freqstr, expected):
+ result = frequencies.to_offset(freqstr)
+ assert result.n == expected
+
+
+@pytest.mark.parametrize("freqstr,expected", [
+ ("+1d", 1),
+ ("+2h30min", 150),
+])
+def test_to_offset_leading_plus(freqstr, expected):
+ result = frequencies.to_offset(freqstr)
+ assert result.n == expected
+
+
+@pytest.mark.parametrize("kwargs,expected", [
+ (dict(days=1, seconds=1), offsets.Second(86401)),
+ (dict(days=-1, seconds=1), offsets.Second(-86399)),
+ (dict(hours=1, minutes=10), offsets.Minute(70)),
+ (dict(hours=1, minutes=-10), offsets.Minute(50)),
+ (dict(weeks=1), offsets.Day(7)),
+ (dict(hours=1), offsets.Hour(1)),
+ (dict(hours=1), frequencies.to_offset("60min")),
+ (dict(microseconds=1), offsets.Micro(1))
+])
+def test_to_offset_pd_timedelta(kwargs, expected):
+ # see gh-9064
+ td = Timedelta(**kwargs)
+ result = frequencies.to_offset(td)
+ assert result == expected
+
+
+def test_to_offset_pd_timedelta_invalid():
+ # see gh-9064
+ msg = "Invalid frequency: 0 days 00:00:00"
+ td = Timedelta(microseconds=0)
+
+ with pytest.raises(ValueError, match=msg):
+ frequencies.to_offset(td)
+
+
+@pytest.mark.parametrize("shortcut,expected", [
+ ("W", offsets.Week(weekday=6)),
+ ("W-SUN", offsets.Week(weekday=6)),
+ ("Q", offsets.QuarterEnd(startingMonth=12)),
+ ("Q-DEC", offsets.QuarterEnd(startingMonth=12)),
+ ("Q-MAY", offsets.QuarterEnd(startingMonth=5)),
+ ("SM", offsets.SemiMonthEnd(day_of_month=15)),
+ ("SM-15", offsets.SemiMonthEnd(day_of_month=15)),
+ ("SM-1", offsets.SemiMonthEnd(day_of_month=1)),
+ ("SM-27", offsets.SemiMonthEnd(day_of_month=27)),
+ ("SMS-2", offsets.SemiMonthBegin(day_of_month=2)),
+ ("SMS-27", offsets.SemiMonthBegin(day_of_month=27)),
+])
+def test_anchored_shortcuts(shortcut, expected):
+ result = frequencies.to_offset(shortcut)
+ assert result == expected
diff --git a/pandas/tests/tseries/test_frequencies.py b/pandas/tests/tseries/test_frequencies.py
deleted file mode 100644
index eb4e63654b47b..0000000000000
--- a/pandas/tests/tseries/test_frequencies.py
+++ /dev/null
@@ -1,793 +0,0 @@
-from datetime import datetime, timedelta
-
-import numpy as np
-import pytest
-
-from pandas._libs.tslibs import frequencies as libfrequencies, resolution
-from pandas._libs.tslibs.ccalendar import MONTHS
-from pandas._libs.tslibs.frequencies import (
- INVALID_FREQ_ERR_MSG, FreqGroup, _period_code_map, get_freq, get_freq_code)
-import pandas.compat as compat
-from pandas.compat import is_platform_windows, range
-
-from pandas import (
- DatetimeIndex, Index, Series, Timedelta, Timestamp, date_range,
- period_range)
-from pandas.core.tools.datetimes import to_datetime
-import pandas.util.testing as tm
-
-import pandas.tseries.frequencies as frequencies
-import pandas.tseries.offsets as offsets
-
-
-class TestToOffset(object):
-
- def test_to_offset_multiple(self):
- freqstr = '2h30min'
- freqstr2 = '2h 30min'
-
- result = frequencies.to_offset(freqstr)
- assert (result == frequencies.to_offset(freqstr2))
- expected = offsets.Minute(150)
- assert (result == expected)
-
- freqstr = '2h30min15s'
- result = frequencies.to_offset(freqstr)
- expected = offsets.Second(150 * 60 + 15)
- assert (result == expected)
-
- freqstr = '2h 60min'
- result = frequencies.to_offset(freqstr)
- expected = offsets.Hour(3)
- assert (result == expected)
-
- freqstr = '2h 20.5min'
- result = frequencies.to_offset(freqstr)
- expected = offsets.Second(8430)
- assert (result == expected)
-
- freqstr = '1.5min'
- result = frequencies.to_offset(freqstr)
- expected = offsets.Second(90)
- assert (result == expected)
-
- freqstr = '0.5S'
- result = frequencies.to_offset(freqstr)
- expected = offsets.Milli(500)
- assert (result == expected)
-
- freqstr = '15l500u'
- result = frequencies.to_offset(freqstr)
- expected = offsets.Micro(15500)
- assert (result == expected)
-
- freqstr = '10s75L'
- result = frequencies.to_offset(freqstr)
- expected = offsets.Milli(10075)
- assert (result == expected)
-
- freqstr = '1s0.25ms'
- result = frequencies.to_offset(freqstr)
- expected = offsets.Micro(1000250)
- assert (result == expected)
-
- freqstr = '1s0.25L'
- result = frequencies.to_offset(freqstr)
- expected = offsets.Micro(1000250)
- assert (result == expected)
-
- freqstr = '2800N'
- result = frequencies.to_offset(freqstr)
- expected = offsets.Nano(2800)
- assert (result == expected)
-
- freqstr = '2SM'
- result = frequencies.to_offset(freqstr)
- expected = offsets.SemiMonthEnd(2)
- assert (result == expected)
-
- freqstr = '2SM-16'
- result = frequencies.to_offset(freqstr)
- expected = offsets.SemiMonthEnd(2, day_of_month=16)
- assert (result == expected)
-
- freqstr = '2SMS-14'
- result = frequencies.to_offset(freqstr)
- expected = offsets.SemiMonthBegin(2, day_of_month=14)
- assert (result == expected)
-
- freqstr = '2SMS-15'
- result = frequencies.to_offset(freqstr)
- expected = offsets.SemiMonthBegin(2)
- assert (result == expected)
-
- # malformed
- with pytest.raises(ValueError, match='Invalid frequency: 2h20m'):
- frequencies.to_offset('2h20m')
-
- def test_to_offset_negative(self):
- freqstr = '-1S'
- result = frequencies.to_offset(freqstr)
- assert (result.n == -1)
-
- freqstr = '-5min10s'
- result = frequencies.to_offset(freqstr)
- assert (result.n == -310)
-
- freqstr = '-2SM'
- result = frequencies.to_offset(freqstr)
- assert (result.n == -2)
-
- freqstr = '-1SMS'
- result = frequencies.to_offset(freqstr)
- assert (result.n == -1)
-
- def test_to_offset_invalid(self):
- # GH 13930
- with pytest.raises(ValueError, match='Invalid frequency: U1'):
- frequencies.to_offset('U1')
- with pytest.raises(ValueError, match='Invalid frequency: -U'):
- frequencies.to_offset('-U')
- with pytest.raises(ValueError, match='Invalid frequency: 3U1'):
- frequencies.to_offset('3U1')
- with pytest.raises(ValueError, match='Invalid frequency: -2-3U'):
- frequencies.to_offset('-2-3U')
- with pytest.raises(ValueError, match='Invalid frequency: -2D:3H'):
- frequencies.to_offset('-2D:3H')
- with pytest.raises(ValueError, match='Invalid frequency: 1.5.0S'):
- frequencies.to_offset('1.5.0S')
-
- # split offsets with spaces are valid
- assert frequencies.to_offset('2D 3H') == offsets.Hour(51)
- assert frequencies.to_offset('2 D3 H') == offsets.Hour(51)
- assert frequencies.to_offset('2 D 3 H') == offsets.Hour(51)
- assert frequencies.to_offset(' 2 D 3 H ') == offsets.Hour(51)
- assert frequencies.to_offset(' H ') == offsets.Hour()
- assert frequencies.to_offset(' 3 H ') == offsets.Hour(3)
-
- # special cases
- assert frequencies.to_offset('2SMS-15') == offsets.SemiMonthBegin(2)
- with pytest.raises(ValueError, match='Invalid frequency: 2SMS-15-15'):
- frequencies.to_offset('2SMS-15-15')
- with pytest.raises(ValueError, match='Invalid frequency: 2SMS-15D'):
- frequencies.to_offset('2SMS-15D')
-
- def test_to_offset_leading_zero(self):
- freqstr = '00H 00T 01S'
- result = frequencies.to_offset(freqstr)
- assert (result.n == 1)
-
- freqstr = '-00H 03T 14S'
- result = frequencies.to_offset(freqstr)
- assert (result.n == -194)
-
- def test_to_offset_leading_plus(self):
- freqstr = '+1d'
- result = frequencies.to_offset(freqstr)
- assert (result.n == 1)
-
- freqstr = '+2h30min'
- result = frequencies.to_offset(freqstr)
- assert (result.n == 150)
-
- for bad_freq in ['+-1d', '-+1h', '+1', '-7', '+d', '-m']:
- with pytest.raises(ValueError, match='Invalid frequency:'):
- frequencies.to_offset(bad_freq)
-
- def test_to_offset_pd_timedelta(self):
- # Tests for #9064
- td = Timedelta(days=1, seconds=1)
- result = frequencies.to_offset(td)
- expected = offsets.Second(86401)
- assert (expected == result)
-
- td = Timedelta(days=-1, seconds=1)
- result = frequencies.to_offset(td)
- expected = offsets.Second(-86399)
- assert (expected == result)
-
- td = Timedelta(hours=1, minutes=10)
- result = frequencies.to_offset(td)
- expected = offsets.Minute(70)
- assert (expected == result)
-
- td = Timedelta(hours=1, minutes=-10)
- result = frequencies.to_offset(td)
- expected = offsets.Minute(50)
- assert (expected == result)
-
- td = Timedelta(weeks=1)
- result = frequencies.to_offset(td)
- expected = offsets.Day(7)
- assert (expected == result)
-
- td1 = Timedelta(hours=1)
- result1 = frequencies.to_offset(td1)
- result2 = frequencies.to_offset('60min')
- assert (result1 == result2)
-
- td = Timedelta(microseconds=1)
- result = frequencies.to_offset(td)
- expected = offsets.Micro(1)
- assert (expected == result)
-
- td = Timedelta(microseconds=0)
- pytest.raises(ValueError, lambda: frequencies.to_offset(td))
-
- def test_anchored_shortcuts(self):
- result = frequencies.to_offset('W')
- expected = frequencies.to_offset('W-SUN')
- assert (result == expected)
-
- result1 = frequencies.to_offset('Q')
- result2 = frequencies.to_offset('Q-DEC')
- expected = offsets.QuarterEnd(startingMonth=12)
- assert (result1 == expected)
- assert (result2 == expected)
-
- result1 = frequencies.to_offset('Q-MAY')
- expected = offsets.QuarterEnd(startingMonth=5)
- assert (result1 == expected)
-
- result1 = frequencies.to_offset('SM')
- result2 = frequencies.to_offset('SM-15')
- expected = offsets.SemiMonthEnd(day_of_month=15)
- assert (result1 == expected)
- assert (result2 == expected)
-
- result = frequencies.to_offset('SM-1')
- expected = offsets.SemiMonthEnd(day_of_month=1)
- assert (result == expected)
-
- result = frequencies.to_offset('SM-27')
- expected = offsets.SemiMonthEnd(day_of_month=27)
- assert (result == expected)
-
- result = frequencies.to_offset('SMS-2')
- expected = offsets.SemiMonthBegin(day_of_month=2)
- assert (result == expected)
-
- result = frequencies.to_offset('SMS-27')
- expected = offsets.SemiMonthBegin(day_of_month=27)
- assert (result == expected)
-
- # ensure invalid cases fail as expected
- invalid_anchors = ['SM-0', 'SM-28', 'SM-29',
- 'SM-FOO', 'BSM', 'SM--1',
- 'SMS-1', 'SMS-28', 'SMS-30',
- 'SMS-BAR', 'SMS-BYR' 'BSMS',
- 'SMS--2']
- for invalid_anchor in invalid_anchors:
- with pytest.raises(ValueError, match='Invalid frequency: '):
- frequencies.to_offset(invalid_anchor)
-
-
-def test_ms_vs_MS():
- left = frequencies.get_offset('ms')
- right = frequencies.get_offset('MS')
- assert left == offsets.Milli()
- assert right == offsets.MonthBegin()
-
-
-def test_rule_aliases():
- rule = frequencies.to_offset('10us')
- assert rule == offsets.Micro(10)
-
-
-class TestFrequencyCode(object):
-
- def test_freq_code(self):
- assert get_freq('A') == 1000
- assert get_freq('3A') == 1000
- assert get_freq('-1A') == 1000
-
- assert get_freq('Y') == 1000
- assert get_freq('3Y') == 1000
- assert get_freq('-1Y') == 1000
-
- assert get_freq('W') == 4000
- assert get_freq('W-MON') == 4001
- assert get_freq('W-FRI') == 4005
-
- for freqstr, code in compat.iteritems(_period_code_map):
- result = get_freq(freqstr)
- assert result == code
-
- result = resolution.get_freq_group(freqstr)
- assert result == code // 1000 * 1000
-
- result = resolution.get_freq_group(code)
- assert result == code // 1000 * 1000
-
- def test_freq_group(self):
- assert resolution.get_freq_group('A') == 1000
- assert resolution.get_freq_group('3A') == 1000
- assert resolution.get_freq_group('-1A') == 1000
- assert resolution.get_freq_group('A-JAN') == 1000
- assert resolution.get_freq_group('A-MAY') == 1000
-
- assert resolution.get_freq_group('Y') == 1000
- assert resolution.get_freq_group('3Y') == 1000
- assert resolution.get_freq_group('-1Y') == 1000
- assert resolution.get_freq_group('Y-JAN') == 1000
- assert resolution.get_freq_group('Y-MAY') == 1000
-
- assert resolution.get_freq_group(offsets.YearEnd()) == 1000
- assert resolution.get_freq_group(offsets.YearEnd(month=1)) == 1000
- assert resolution.get_freq_group(offsets.YearEnd(month=5)) == 1000
-
- assert resolution.get_freq_group('W') == 4000
- assert resolution.get_freq_group('W-MON') == 4000
- assert resolution.get_freq_group('W-FRI') == 4000
- assert resolution.get_freq_group(offsets.Week()) == 4000
- assert resolution.get_freq_group(offsets.Week(weekday=1)) == 4000
- assert resolution.get_freq_group(offsets.Week(weekday=5)) == 4000
-
- def test_get_to_timestamp_base(self):
- tsb = libfrequencies.get_to_timestamp_base
-
- assert (tsb(get_freq_code('D')[0]) ==
- get_freq_code('D')[0])
- assert (tsb(get_freq_code('W')[0]) ==
- get_freq_code('D')[0])
- assert (tsb(get_freq_code('M')[0]) ==
- get_freq_code('D')[0])
-
- assert (tsb(get_freq_code('S')[0]) ==
- get_freq_code('S')[0])
- assert (tsb(get_freq_code('T')[0]) ==
- get_freq_code('S')[0])
- assert (tsb(get_freq_code('H')[0]) ==
- get_freq_code('S')[0])
-
- def test_freq_to_reso(self):
- Reso = resolution.Resolution
-
- assert Reso.get_str_from_freq('A') == 'year'
- assert Reso.get_str_from_freq('Q') == 'quarter'
- assert Reso.get_str_from_freq('M') == 'month'
- assert Reso.get_str_from_freq('D') == 'day'
- assert Reso.get_str_from_freq('H') == 'hour'
- assert Reso.get_str_from_freq('T') == 'minute'
- assert Reso.get_str_from_freq('S') == 'second'
- assert Reso.get_str_from_freq('L') == 'millisecond'
- assert Reso.get_str_from_freq('U') == 'microsecond'
- assert Reso.get_str_from_freq('N') == 'nanosecond'
-
- for freq in ['A', 'Q', 'M', 'D', 'H', 'T', 'S', 'L', 'U', 'N']:
- # check roundtrip
- result = Reso.get_freq(Reso.get_str_from_freq(freq))
- assert freq == result
-
- for freq in ['D', 'H', 'T', 'S', 'L', 'U']:
- result = Reso.get_freq(Reso.get_str(Reso.get_reso_from_freq(freq)))
- assert freq == result
-
- def test_resolution_bumping(self):
- # see gh-14378
- Reso = resolution.Resolution
-
- assert Reso.get_stride_from_decimal(1.5, 'T') == (90, 'S')
- assert Reso.get_stride_from_decimal(62.4, 'T') == (3744, 'S')
- assert Reso.get_stride_from_decimal(1.04, 'H') == (3744, 'S')
- assert Reso.get_stride_from_decimal(1, 'D') == (1, 'D')
- assert (Reso.get_stride_from_decimal(0.342931, 'H') ==
- (1234551600, 'U'))
- assert Reso.get_stride_from_decimal(1.2345, 'D') == (106660800, 'L')
-
- with pytest.raises(ValueError):
- Reso.get_stride_from_decimal(0.5, 'N')
-
- # too much precision in the input can prevent
- with pytest.raises(ValueError):
- Reso.get_stride_from_decimal(0.3429324798798269273987982, 'H')
-
- def test_get_freq_code(self):
- # frequency str
- assert (get_freq_code('A') ==
- (get_freq('A'), 1))
- assert (get_freq_code('3D') ==
- (get_freq('D'), 3))
- assert (get_freq_code('-2M') ==
- (get_freq('M'), -2))
-
- # tuple
- assert (get_freq_code(('D', 1)) ==
- (get_freq('D'), 1))
- assert (get_freq_code(('A', 3)) ==
- (get_freq('A'), 3))
- assert (get_freq_code(('M', -2)) ==
- (get_freq('M'), -2))
-
- # numeric tuple
- assert get_freq_code((1000, 1)) == (1000, 1)
-
- # offsets
- assert (get_freq_code(offsets.Day()) ==
- (get_freq('D'), 1))
- assert (get_freq_code(offsets.Day(3)) ==
- (get_freq('D'), 3))
- assert (get_freq_code(offsets.Day(-2)) ==
- (get_freq('D'), -2))
-
- assert (get_freq_code(offsets.MonthEnd()) ==
- (get_freq('M'), 1))
- assert (get_freq_code(offsets.MonthEnd(3)) ==
- (get_freq('M'), 3))
- assert (get_freq_code(offsets.MonthEnd(-2)) ==
- (get_freq('M'), -2))
-
- assert (get_freq_code(offsets.Week()) ==
- (get_freq('W'), 1))
- assert (get_freq_code(offsets.Week(3)) ==
- (get_freq('W'), 3))
- assert (get_freq_code(offsets.Week(-2)) ==
- (get_freq('W'), -2))
-
- # Monday is weekday=0
- assert (get_freq_code(offsets.Week(weekday=1)) ==
- (get_freq('W-TUE'), 1))
- assert (get_freq_code(offsets.Week(3, weekday=0)) ==
- (get_freq('W-MON'), 3))
- assert (get_freq_code(offsets.Week(-2, weekday=4)) ==
- (get_freq('W-FRI'), -2))
-
- def test_frequency_misc(self):
- assert (resolution.get_freq_group('T') ==
- FreqGroup.FR_MIN)
-
- code, stride = get_freq_code(offsets.Hour())
- assert code == FreqGroup.FR_HR
-
- code, stride = get_freq_code((5, 'T'))
- assert code == FreqGroup.FR_MIN
- assert stride == 5
-
- offset = offsets.Hour()
- result = frequencies.to_offset(offset)
- assert result == offset
-
- result = frequencies.to_offset((5, 'T'))
- expected = offsets.Minute(5)
- assert result == expected
-
- with pytest.raises(ValueError, match='Invalid frequency'):
- get_freq_code((5, 'baz'))
-
- with pytest.raises(ValueError, match='Invalid frequency'):
- frequencies.to_offset('100foo')
-
- with pytest.raises(ValueError, match='Could not evaluate'):
- frequencies.to_offset(('', ''))
-
-
-_dti = DatetimeIndex
-
-
-class TestFrequencyInference(object):
-
- def test_raise_if_period_index(self):
- index = period_range(start="1/1/1990", periods=20, freq="M")
- pytest.raises(TypeError, frequencies.infer_freq, index)
-
- def test_raise_if_too_few(self):
- index = _dti(['12/31/1998', '1/3/1999'])
- pytest.raises(ValueError, frequencies.infer_freq, index)
-
- def test_business_daily(self):
- index = _dti(['01/01/1999', '1/4/1999', '1/5/1999'])
- assert frequencies.infer_freq(index) == 'B'
-
- def test_business_daily_look_alike(self):
- # GH 16624, do not infer 'B' when 'weekend' (2-day gap) in wrong place
- index = _dti(['12/31/1998', '1/3/1999', '1/4/1999'])
- assert frequencies.infer_freq(index) is None
-
- def test_day(self):
- self._check_tick(timedelta(1), 'D')
-
- def test_day_corner(self):
- index = _dti(['1/1/2000', '1/2/2000', '1/3/2000'])
- assert frequencies.infer_freq(index) == 'D'
-
- def test_non_datetimeindex(self):
- dates = to_datetime(['1/1/2000', '1/2/2000', '1/3/2000'])
- assert frequencies.infer_freq(dates) == 'D'
-
- def test_hour(self):
- self._check_tick(timedelta(hours=1), 'H')
-
- def test_minute(self):
- self._check_tick(timedelta(minutes=1), 'T')
-
- def test_second(self):
- self._check_tick(timedelta(seconds=1), 'S')
-
- def test_millisecond(self):
- self._check_tick(timedelta(microseconds=1000), 'L')
-
- def test_microsecond(self):
- self._check_tick(timedelta(microseconds=1), 'U')
-
- def test_nanosecond(self):
- self._check_tick(np.timedelta64(1, 'ns'), 'N')
-
- def _check_tick(self, base_delta, code):
- b = Timestamp(datetime.now())
- for i in range(1, 5):
- inc = base_delta * i
- index = _dti([b + inc * j for j in range(3)])
- if i > 1:
- exp_freq = '%d%s' % (i, code)
- else:
- exp_freq = code
- assert frequencies.infer_freq(index) == exp_freq
-
- index = _dti([b + base_delta * 7] + [b + base_delta * j for j in range(
- 3)])
- assert frequencies.infer_freq(index) is None
-
- index = _dti([b + base_delta * j for j in range(3)] + [b + base_delta *
- 7])
-
- assert frequencies.infer_freq(index) is None
-
- def test_weekly(self):
- days = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']
-
- for day in days:
- self._check_generated_range('1/1/2000', 'W-%s' % day)
-
- def test_week_of_month(self):
- days = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']
-
- for day in days:
- for i in range(1, 5):
- self._check_generated_range('1/1/2000', 'WOM-%d%s' % (i, day))
-
- def test_fifth_week_of_month(self):
- # Only supports freq up to WOM-4. See #9425
- func = lambda: date_range('2014-01-01', freq='WOM-5MON')
- pytest.raises(ValueError, func)
-
- def test_fifth_week_of_month_infer(self):
- # Only attempts to infer up to WOM-4. See #9425
- index = DatetimeIndex(["2014-03-31", "2014-06-30", "2015-03-30"])
- assert frequencies.infer_freq(index) is None
-
- def test_week_of_month_fake(self):
- # All of these dates are on same day of week and are 4 or 5 weeks apart
- index = DatetimeIndex(["2013-08-27", "2013-10-01", "2013-10-29",
- "2013-11-26"])
- assert frequencies.infer_freq(index) != 'WOM-4TUE'
-
- def test_monthly(self):
- self._check_generated_range('1/1/2000', 'M')
-
- def test_monthly_ambiguous(self):
- rng = _dti(['1/31/2000', '2/29/2000', '3/31/2000'])
- assert rng.inferred_freq == 'M'
-
- def test_business_monthly(self):
- self._check_generated_range('1/1/2000', 'BM')
-
- def test_business_start_monthly(self):
- self._check_generated_range('1/1/2000', 'BMS')
-
- def test_quarterly(self):
- for month in ['JAN', 'FEB', 'MAR']:
- self._check_generated_range('1/1/2000', 'Q-%s' % month)
-
- def test_annual(self):
- for month in MONTHS:
- self._check_generated_range('1/1/2000', 'A-%s' % month)
-
- def test_business_annual(self):
- for month in MONTHS:
- self._check_generated_range('1/1/2000', 'BA-%s' % month)
-
- def test_annual_ambiguous(self):
- rng = _dti(['1/31/2000', '1/31/2001', '1/31/2002'])
- assert rng.inferred_freq == 'A-JAN'
-
- def _check_generated_range(self, start, freq):
- freq = freq.upper()
-
- gen = date_range(start, periods=7, freq=freq)
- index = _dti(gen.values)
- if not freq.startswith('Q-'):
- assert frequencies.infer_freq(index) == gen.freqstr
- else:
- inf_freq = frequencies.infer_freq(index)
- is_dec_range = inf_freq == 'Q-DEC' and gen.freqstr in (
- 'Q', 'Q-DEC', 'Q-SEP', 'Q-JUN', 'Q-MAR')
- is_nov_range = inf_freq == 'Q-NOV' and gen.freqstr in (
- 'Q-NOV', 'Q-AUG', 'Q-MAY', 'Q-FEB')
- is_oct_range = inf_freq == 'Q-OCT' and gen.freqstr in (
- 'Q-OCT', 'Q-JUL', 'Q-APR', 'Q-JAN')
- assert is_dec_range or is_nov_range or is_oct_range
-
- gen = date_range(start, periods=5, freq=freq)
- index = _dti(gen.values)
-
- if not freq.startswith('Q-'):
- assert frequencies.infer_freq(index) == gen.freqstr
- else:
- inf_freq = frequencies.infer_freq(index)
- is_dec_range = inf_freq == 'Q-DEC' and gen.freqstr in (
- 'Q', 'Q-DEC', 'Q-SEP', 'Q-JUN', 'Q-MAR')
- is_nov_range = inf_freq == 'Q-NOV' and gen.freqstr in (
- 'Q-NOV', 'Q-AUG', 'Q-MAY', 'Q-FEB')
- is_oct_range = inf_freq == 'Q-OCT' and gen.freqstr in (
- 'Q-OCT', 'Q-JUL', 'Q-APR', 'Q-JAN')
-
- assert is_dec_range or is_nov_range or is_oct_range
-
- def test_infer_freq(self):
- rng = period_range('1959Q2', '2009Q3', freq='Q')
- rng = Index(rng.to_timestamp('D', how='e').astype(object))
- assert rng.inferred_freq == 'Q-DEC'
-
- rng = period_range('1959Q2', '2009Q3', freq='Q-NOV')
- rng = Index(rng.to_timestamp('D', how='e').astype(object))
- assert rng.inferred_freq == 'Q-NOV'
-
- rng = period_range('1959Q2', '2009Q3', freq='Q-OCT')
- rng = Index(rng.to_timestamp('D', how='e').astype(object))
- assert rng.inferred_freq == 'Q-OCT'
-
- def test_infer_freq_tz(self):
-
- freqs = {'AS-JAN':
- ['2009-01-01', '2010-01-01', '2011-01-01', '2012-01-01'],
- 'Q-OCT':
- ['2009-01-31', '2009-04-30', '2009-07-31', '2009-10-31'],
- 'M': ['2010-11-30', '2010-12-31', '2011-01-31', '2011-02-28'],
- 'W-SAT':
- ['2010-12-25', '2011-01-01', '2011-01-08', '2011-01-15'],
- 'D': ['2011-01-01', '2011-01-02', '2011-01-03', '2011-01-04'],
- 'H': ['2011-12-31 22:00', '2011-12-31 23:00',
- '2012-01-01 00:00', '2012-01-01 01:00']}
-
- # GH 7310
- for tz in [None, 'Australia/Sydney', 'Asia/Tokyo', 'Europe/Paris',
- 'US/Pacific', 'US/Eastern']:
- for expected, dates in compat.iteritems(freqs):
- idx = DatetimeIndex(dates, tz=tz)
- assert idx.inferred_freq == expected
-
- def test_infer_freq_tz_transition(self):
- # Tests for #8772
- date_pairs = [['2013-11-02', '2013-11-5'], # Fall DST
- ['2014-03-08', '2014-03-11'], # Spring DST
- ['2014-01-01', '2014-01-03']] # Regular Time
- freqs = ['3H', '10T', '3601S', '3600001L', '3600000001U',
- '3600000000001N']
-
- for tz in [None, 'Australia/Sydney', 'Asia/Tokyo', 'Europe/Paris',
- 'US/Pacific', 'US/Eastern']:
- for date_pair in date_pairs:
- for freq in freqs:
- idx = date_range(date_pair[0], date_pair[
- 1], freq=freq, tz=tz)
- assert idx.inferred_freq == freq
-
- index = date_range("2013-11-03", periods=5,
- freq="3H").tz_localize("America/Chicago")
- assert index.inferred_freq is None
-
- def test_infer_freq_businesshour(self):
- # GH 7905
- idx = DatetimeIndex(
- ['2014-07-01 09:00', '2014-07-01 10:00', '2014-07-01 11:00',
- '2014-07-01 12:00', '2014-07-01 13:00', '2014-07-01 14:00'])
- # hourly freq in a day must result in 'H'
- assert idx.inferred_freq == 'H'
-
- idx = DatetimeIndex(
- ['2014-07-01 09:00', '2014-07-01 10:00', '2014-07-01 11:00',
- '2014-07-01 12:00', '2014-07-01 13:00', '2014-07-01 14:00',
- '2014-07-01 15:00', '2014-07-01 16:00', '2014-07-02 09:00',
- '2014-07-02 10:00', '2014-07-02 11:00'])
- assert idx.inferred_freq == 'BH'
-
- idx = DatetimeIndex(
- ['2014-07-04 09:00', '2014-07-04 10:00', '2014-07-04 11:00',
- '2014-07-04 12:00', '2014-07-04 13:00', '2014-07-04 14:00',
- '2014-07-04 15:00', '2014-07-04 16:00', '2014-07-07 09:00',
- '2014-07-07 10:00', '2014-07-07 11:00'])
- assert idx.inferred_freq == 'BH'
-
- idx = DatetimeIndex(
- ['2014-07-04 09:00', '2014-07-04 10:00', '2014-07-04 11:00',
- '2014-07-04 12:00', '2014-07-04 13:00', '2014-07-04 14:00',
- '2014-07-04 15:00', '2014-07-04 16:00', '2014-07-07 09:00',
- '2014-07-07 10:00', '2014-07-07 11:00', '2014-07-07 12:00',
- '2014-07-07 13:00', '2014-07-07 14:00', '2014-07-07 15:00',
- '2014-07-07 16:00', '2014-07-08 09:00', '2014-07-08 10:00',
- '2014-07-08 11:00', '2014-07-08 12:00', '2014-07-08 13:00',
- '2014-07-08 14:00', '2014-07-08 15:00', '2014-07-08 16:00'])
- assert idx.inferred_freq == 'BH'
-
- def test_not_monotonic(self):
- rng = _dti(['1/31/2000', '1/31/2001', '1/31/2002'])
- rng = rng[::-1]
- assert rng.inferred_freq == '-1A-JAN'
-
- def test_non_datetimeindex2(self):
- rng = _dti(['1/31/2000', '1/31/2001', '1/31/2002'])
-
- vals = rng.to_pydatetime()
-
- result = frequencies.infer_freq(vals)
- assert result == rng.inferred_freq
-
- def test_invalid_index_types(self):
-
- # test all index types
- for i in [tm.makeIntIndex(10), tm.makeFloatIndex(10),
- tm.makePeriodIndex(10)]:
- pytest.raises(TypeError, lambda: frequencies.infer_freq(i))
-
- # GH 10822
- # odd error message on conversions to datetime for unicode
- if not is_platform_windows():
- for i in [tm.makeStringIndex(10), tm.makeUnicodeIndex(10)]:
- pytest.raises(ValueError, lambda: frequencies.infer_freq(i))
-
- def test_string_datetimelike_compat(self):
-
- # GH 6463
- expected = frequencies.infer_freq(['2004-01', '2004-02', '2004-03',
- '2004-04'])
- result = frequencies.infer_freq(Index(['2004-01', '2004-02', '2004-03',
- '2004-04']))
- assert result == expected
-
- def test_series(self):
-
- # GH6407
- # inferring series
-
- # invalid type of Series
- for s in [Series(np.arange(10)), Series(np.arange(10.))]:
- pytest.raises(TypeError, lambda: frequencies.infer_freq(s))
-
- # a non-convertible string
- pytest.raises(ValueError, lambda: frequencies.infer_freq(
- Series(['foo', 'bar'])))
-
- # cannot infer on PeriodIndex
- for freq in [None, 'L']:
- s = Series(period_range('2013', periods=10, freq=freq))
- pytest.raises(TypeError, lambda: frequencies.infer_freq(s))
-
- # DateTimeIndex
- for freq in ['M', 'L', 'S']:
- s = Series(date_range('20130101', periods=10, freq=freq))
- inferred = frequencies.infer_freq(s)
- assert inferred == freq
-
- s = Series(date_range('20130101', '20130110'))
- inferred = frequencies.infer_freq(s)
- assert inferred == 'D'
-
- def test_legacy_offset_warnings(self):
- freqs = ['WEEKDAY', 'EOM', 'W@MON', 'W@TUE', 'W@WED', 'W@THU',
- 'W@FRI', 'W@SAT', 'W@SUN', 'Q@JAN', 'Q@FEB', 'Q@MAR',
- 'A@JAN', 'A@FEB', 'A@MAR', 'A@APR', 'A@MAY', 'A@JUN',
- 'A@JUL', 'A@AUG', 'A@SEP', 'A@OCT', 'A@NOV', 'A@DEC',
- 'Y@JAN', 'WOM@1MON', 'WOM@2MON', 'WOM@3MON',
- 'WOM@4MON', 'WOM@1TUE', 'WOM@2TUE', 'WOM@3TUE',
- 'WOM@4TUE', 'WOM@1WED', 'WOM@2WED', 'WOM@3WED',
- 'WOM@4WED', 'WOM@1THU', 'WOM@2THU', 'WOM@3THU',
- 'WOM@4THU', 'WOM@1FRI', 'WOM@2FRI', 'WOM@3FRI',
- 'WOM@4FRI']
-
- msg = INVALID_FREQ_ERR_MSG
- for freq in freqs:
- with pytest.raises(ValueError, match=msg):
- frequencies.get_offset(freq)
-
- with pytest.raises(ValueError, match=msg):
- date_range('2011-01-01', periods=5, freq=freq)
| https://api.github.com/repos/pandas-dev/pandas/pulls/25430 | 2019-02-24T11:01:00Z | 2019-02-28T15:20:12Z | 2019-02-28T15:20:12Z | 2019-02-28T18:17:19Z | |
Class to read OpenDocument Tables | diff --git a/ci/deps/travis-36-cov.yaml b/ci/deps/travis-36-cov.yaml
index fead806fc8e1c..6f85c32b9a915 100644
--- a/ci/deps/travis-36-cov.yaml
+++ b/ci/deps/travis-36-cov.yaml
@@ -16,6 +16,7 @@ dependencies:
- nomkl
- numexpr
- numpy=1.15.*
+ - odfpy
- openpyxl
- pandas-gbq
# https://github.com/pydata/pandas-gbq/issues/271
diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst
index 9af6c36cc4e4d..bf7ec561b4a7e 100644
--- a/doc/source/user_guide/io.rst
+++ b/doc/source/user_guide/io.rst
@@ -32,6 +32,7 @@ The pandas I/O API is a set of top level ``reader`` functions accessed like
text;`HTML <https://en.wikipedia.org/wiki/HTML>`__;:ref:`read_html<io.read_html>`;:ref:`to_html<io.html>`
text; Local clipboard;:ref:`read_clipboard<io.clipboard>`;:ref:`to_clipboard<io.clipboard>`
binary;`MS Excel <https://en.wikipedia.org/wiki/Microsoft_Excel>`__;:ref:`read_excel<io.excel_reader>`;:ref:`to_excel<io.excel_writer>`
+ binary;`OpenDocument <http://www.opendocumentformat.org>`__;:ref:`read_excel<io.ods>`;
binary;`HDF5 Format <https://support.hdfgroup.org/HDF5/whatishdf5.html>`__;:ref:`read_hdf<io.hdf5>`;:ref:`to_hdf<io.hdf5>`
binary;`Feather Format <https://github.com/wesm/feather>`__;:ref:`read_feather<io.feather>`;:ref:`to_feather<io.feather>`
binary;`Parquet Format <https://parquet.apache.org/>`__;:ref:`read_parquet<io.parquet>`;:ref:`to_parquet<io.parquet>`
@@ -2779,9 +2780,10 @@ parse HTML tables in the top-level pandas io function ``read_html``.
Excel files
-----------
-The :func:`~pandas.read_excel` method can read Excel 2003 (``.xls``) and
-Excel 2007+ (``.xlsx``) files using the ``xlrd`` Python
-module. The :meth:`~DataFrame.to_excel` instance method is used for
+The :func:`~pandas.read_excel` method can read Excel 2003 (``.xls``)
+files using the ``xlrd`` Python module. Excel 2007+ (``.xlsx``) files
+can be read using either ``xlrd`` or ``openpyxl``.
+The :meth:`~DataFrame.to_excel` instance method is used for
saving a ``DataFrame`` to Excel. Generally the semantics are
similar to working with :ref:`csv<io.read_csv_table>` data.
See the :ref:`cookbook<cookbook.excel>` for some advanced strategies.
@@ -3217,7 +3219,27 @@ The look and feel of Excel worksheets created from pandas can be modified using
* ``float_format`` : Format string for floating point numbers (default ``None``).
* ``freeze_panes`` : A tuple of two integers representing the bottommost row and rightmost column to freeze. Each of these parameters is one-based, so (1, 1) will freeze the first row and first column (default ``None``).
+.. _io.ods:
+OpenDocument Spreadsheets
+-------------------------
+
+.. versionadded:: 0.25
+
+The :func:`~pandas.read_excel` method can also read OpenDocument spreadsheets
+using the ``odfpy`` module. The semantics and features for reading
+OpenDocument spreadsheets match what can be done for `Excel files`_ using
+``engine='odf'``.
+
+.. code-block:: python
+
+ # Returns a DataFrame
+ pd.read_excel('path_to_file.ods', engine='odf')
+
+.. note::
+
+ Currently pandas only supports *reading* OpenDocument spreadsheets. Writing
+ is not implemented.
.. _io.clipboard:
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 2030bb4d974c3..35e9fe5706b31 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -164,6 +164,7 @@ Other enhancements
- Added new option ``plotting.backend`` to be able to select a plotting backend different than the existing ``matplotlib`` one. Use ``pandas.set_option('plotting.backend', '<backend-module>')`` where ``<backend-module`` is a library implementing the pandas plotting API (:issue:`14130`)
- :class:`pandas.offsets.BusinessHour` supports multiple opening hours intervals (:issue:`15481`)
- :func:`read_excel` can now use ``openpyxl`` to read Excel files via the ``engine='openpyxl'`` argument. This will become the default in a future release (:issue:`11499`)
+- :func:`pandas.io.excel.read_excel` supports reading OpenDocument tables. Specify ``engine='odf'`` to enable. Consult the :ref:`IO User Guide <io.ods>` for more details (:issue:`9070`)
.. _whatsnew_0250.api_breaking:
diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py
index 31746dc3d6c16..620884d66821c 100644
--- a/pandas/compat/_optional.py
+++ b/pandas/compat/_optional.py
@@ -13,6 +13,7 @@
"lxml.etree": "3.8.0",
"matplotlib": "2.2.2",
"numexpr": "2.6.2",
+ "odfpy": "1.3.0",
"openpyxl": "2.4.8",
"pandas_gbq": "0.8.0",
"pyarrow": "0.9.0",
diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py
index 84ca154d045fe..7fe9f8438ac74 100644
--- a/pandas/core/config_init.py
+++ b/pandas/core/config_init.py
@@ -422,6 +422,7 @@ def use_inf_as_na_cb(key):
_xls_options = ['xlrd']
_xlsm_options = ['xlrd', 'openpyxl']
_xlsx_options = ['xlrd', 'openpyxl']
+_ods_options = ['odf']
with cf.config_prefix("io.excel.xls"):
@@ -447,6 +448,14 @@ def use_inf_as_na_cb(key):
validator=str)
+with cf.config_prefix("io.excel.ods"):
+ cf.register_option("reader", "auto",
+ reader_engine_doc.format(
+ ext='ods',
+ others=', '.join(_ods_options)),
+ validator=str)
+
+
# Set up the io.excel specific writer configuration.
writer_engine_doc = """
: string
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index 8055b6609b1c4..d10a40541bb6c 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -768,12 +768,14 @@ class ExcelFile:
Acceptable values are None or ``xlrd``.
"""
- from pandas.io.excel._xlrd import _XlrdReader
+ from pandas.io.excel._odfreader import _ODFReader
from pandas.io.excel._openpyxl import _OpenpyxlReader
+ from pandas.io.excel._xlrd import _XlrdReader
_engines = {
'xlrd': _XlrdReader,
'openpyxl': _OpenpyxlReader,
+ 'odf': _ODFReader,
}
def __init__(self, io, engine=None):
diff --git a/pandas/io/excel/_odfreader.py b/pandas/io/excel/_odfreader.py
new file mode 100644
index 0000000000000..c820c1497c3c9
--- /dev/null
+++ b/pandas/io/excel/_odfreader.py
@@ -0,0 +1,176 @@
+from typing import List
+
+from pandas.compat._optional import import_optional_dependency
+
+import pandas as pd
+from pandas._typing import FilePathOrBuffer, Scalar
+
+from pandas.io.excel._base import _BaseExcelReader
+
+
+class _ODFReader(_BaseExcelReader):
+ """Read tables out of OpenDocument formatted files
+
+ Parameters
+ ----------
+ filepath_or_buffer: string, path to be parsed or
+ an open readable stream.
+ """
+ def __init__(self, filepath_or_buffer: FilePathOrBuffer):
+ import_optional_dependency("odf")
+ super().__init__(filepath_or_buffer)
+
+ @property
+ def _workbook_class(self):
+ from odf.opendocument import OpenDocument
+ return OpenDocument
+
+ def load_workbook(self, filepath_or_buffer: FilePathOrBuffer):
+ from odf.opendocument import load
+ return load(filepath_or_buffer)
+
+ @property
+ def empty_value(self) -> str:
+ """Property for compat with other readers."""
+ return ''
+
+ @property
+ def sheet_names(self) -> List[str]:
+ """Return a list of sheet names present in the document"""
+ from odf.table import Table
+
+ tables = self.book.getElementsByType(Table)
+ return [t.getAttribute("name") for t in tables]
+
+ def get_sheet_by_index(self, index: int):
+ from odf.table import Table
+ tables = self.book.getElementsByType(Table)
+ return tables[index]
+
+ def get_sheet_by_name(self, name: str):
+ from odf.table import Table
+
+ tables = self.book.getElementsByType(Table)
+
+ for table in tables:
+ if table.getAttribute("name") == name:
+ return table
+
+ raise ValueError("sheet {name} not found".format(name))
+
+ 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
+
+ covered_cell_name = CoveredTableCell().qname
+ table_cell_name = TableCell().qname
+ cell_names = {covered_cell_name, table_cell_name}
+
+ sheet_rows = sheet.getElementsByType(TableRow)
+ empty_rows = 0
+ max_row_len = 0
+
+ table = [] # type: List[List[Scalar]]
+
+ for i, sheet_row in enumerate(sheet_rows):
+ sheet_cells = [x for x in sheet_row.childNodes
+ if x.qname in cell_names]
+ empty_cells = 0
+ table_row = [] # type: List[Scalar]
+
+ for j, sheet_cell in enumerate(sheet_cells):
+ if sheet_cell.qname == table_cell_name:
+ value = self._get_cell_value(sheet_cell, convert_float)
+ else:
+ value = self.empty_value
+
+ column_repeat = self._get_column_repeat(sheet_cell)
+
+ # Queue up empty values, writing only if content succeeds them
+ if value == self.empty_value:
+ empty_cells += column_repeat
+ else:
+ table_row.extend([self.empty_value] * empty_cells)
+ empty_cells = 0
+ table_row.extend([value] * column_repeat)
+
+ if max_row_len < len(table_row):
+ max_row_len = len(table_row)
+
+ row_repeat = self._get_row_repeat(sheet_row)
+ if self._is_empty_row(sheet_row):
+ empty_rows += row_repeat
+ else:
+ # add blank rows to our table
+ table.extend([[self.empty_value]] * empty_rows)
+ empty_rows = 0
+ for _ in range(row_repeat):
+ table.append(table_row)
+
+ # Make our table square
+ for row in table:
+ if len(row) < max_row_len:
+ row.extend([self.empty_value] * (max_row_len - len(row)))
+
+ return table
+
+ def _get_row_repeat(self, row) -> int:
+ """Return number of times this row was repeated
+ Repeating an empty row appeared to be a common way
+ of representing sparse rows in the table.
+ """
+ from odf.namespaces import TABLENS
+
+ return int(row.attributes.get((TABLENS, 'number-rows-repeated'), 1))
+
+ def _get_column_repeat(self, cell) -> int:
+ from odf.namespaces import TABLENS
+ return int(cell.attributes.get(
+ (TABLENS, 'number-columns-repeated'), 1))
+
+ def _is_empty_row(self, row) -> bool:
+ """Helper function to find empty rows
+ """
+ for column in row.childNodes:
+ if len(column.childNodes) > 0:
+ return False
+
+ return True
+
+ def _get_cell_value(self, cell, convert_float: bool) -> Scalar:
+ from odf.namespaces import OFFICENS
+ cell_type = cell.attributes.get((OFFICENS, 'value-type'))
+ if cell_type == 'boolean':
+ if str(cell) == "TRUE":
+ return True
+ return False
+ if cell_type is None:
+ return self.empty_value
+ elif cell_type == 'float':
+ # GH5394
+ cell_value = float(cell.attributes.get((OFFICENS, 'value')))
+
+ if cell_value == 0. and str(cell) != cell_value: # NA handling
+ return str(cell)
+
+ if convert_float:
+ val = int(cell_value)
+ if val == cell_value:
+ return val
+ return cell_value
+ elif cell_type == 'percentage':
+ cell_value = cell.attributes.get((OFFICENS, 'value'))
+ return float(cell_value)
+ elif cell_type == 'string':
+ return str(cell)
+ elif cell_type == 'currency':
+ cell_value = cell.attributes.get((OFFICENS, 'value'))
+ return float(cell_value)
+ elif cell_type == 'date':
+ cell_value = cell.attributes.get((OFFICENS, 'date-value'))
+ return pd.to_datetime(cell_value)
+ elif cell_type == 'time':
+ return pd.to_datetime(str(cell)).time()
+ else:
+ raise ValueError('Unrecognized type {}'.format(cell_type))
diff --git a/pandas/tests/io/data/blank.ods b/pandas/tests/io/data/blank.ods
new file mode 100644
index 0000000000000..7ded3c3c1d688
Binary files /dev/null and b/pandas/tests/io/data/blank.ods differ
diff --git a/pandas/tests/io/data/blank_with_header.ods b/pandas/tests/io/data/blank_with_header.ods
new file mode 100644
index 0000000000000..0a2e696267fda
Binary files /dev/null and b/pandas/tests/io/data/blank_with_header.ods differ
diff --git a/pandas/tests/io/data/invalid_value_type.ods b/pandas/tests/io/data/invalid_value_type.ods
new file mode 100644
index 0000000000000..75a7a40b25d79
Binary files /dev/null and b/pandas/tests/io/data/invalid_value_type.ods differ
diff --git a/pandas/tests/io/data/test1.ods b/pandas/tests/io/data/test1.ods
new file mode 100644
index 0000000000000..5dc0e83456264
Binary files /dev/null and b/pandas/tests/io/data/test1.ods differ
diff --git a/pandas/tests/io/data/test2.ods b/pandas/tests/io/data/test2.ods
new file mode 100644
index 0000000000000..2a90db839026b
Binary files /dev/null and b/pandas/tests/io/data/test2.ods differ
diff --git a/pandas/tests/io/data/test3.ods b/pandas/tests/io/data/test3.ods
new file mode 100644
index 0000000000000..dc78781caa6e9
Binary files /dev/null and b/pandas/tests/io/data/test3.ods differ
diff --git a/pandas/tests/io/data/test4.ods b/pandas/tests/io/data/test4.ods
new file mode 100644
index 0000000000000..c73a20d8b0562
Binary files /dev/null and b/pandas/tests/io/data/test4.ods differ
diff --git a/pandas/tests/io/data/test5.ods b/pandas/tests/io/data/test5.ods
new file mode 100644
index 0000000000000..5872e2624d033
Binary files /dev/null and b/pandas/tests/io/data/test5.ods differ
diff --git a/pandas/tests/io/data/test_converters.ods b/pandas/tests/io/data/test_converters.ods
new file mode 100644
index 0000000000000..0216fb16311d8
Binary files /dev/null and b/pandas/tests/io/data/test_converters.ods differ
diff --git a/pandas/tests/io/data/test_index_name_pre17.ods b/pandas/tests/io/data/test_index_name_pre17.ods
new file mode 100644
index 0000000000000..56638c983d944
Binary files /dev/null and b/pandas/tests/io/data/test_index_name_pre17.ods differ
diff --git a/pandas/tests/io/data/test_multisheet.ods b/pandas/tests/io/data/test_multisheet.ods
new file mode 100644
index 0000000000000..39058e67b4d5b
Binary files /dev/null and b/pandas/tests/io/data/test_multisheet.ods differ
diff --git a/pandas/tests/io/data/test_squeeze.ods b/pandas/tests/io/data/test_squeeze.ods
new file mode 100644
index 0000000000000..10ccf0da2693e
Binary files /dev/null and b/pandas/tests/io/data/test_squeeze.ods differ
diff --git a/pandas/tests/io/data/test_types.ods b/pandas/tests/io/data/test_types.ods
new file mode 100644
index 0000000000000..c9a82bfff810b
Binary files /dev/null and b/pandas/tests/io/data/test_types.ods differ
diff --git a/pandas/tests/io/data/testdateoverflow.ods b/pandas/tests/io/data/testdateoverflow.ods
new file mode 100644
index 0000000000000..bb05267865303
Binary files /dev/null and b/pandas/tests/io/data/testdateoverflow.ods differ
diff --git a/pandas/tests/io/data/testdtype.ods b/pandas/tests/io/data/testdtype.ods
new file mode 100644
index 0000000000000..91145f807c9d9
Binary files /dev/null and b/pandas/tests/io/data/testdtype.ods differ
diff --git a/pandas/tests/io/data/testmultiindex.ods b/pandas/tests/io/data/testmultiindex.ods
new file mode 100644
index 0000000000000..b7f03900e6617
Binary files /dev/null and b/pandas/tests/io/data/testmultiindex.ods differ
diff --git a/pandas/tests/io/data/testskiprows.ods b/pandas/tests/io/data/testskiprows.ods
new file mode 100644
index 0000000000000..443602a2c3f98
Binary files /dev/null and b/pandas/tests/io/data/testskiprows.ods differ
diff --git a/pandas/tests/io/data/times_1900.ods b/pandas/tests/io/data/times_1900.ods
new file mode 100644
index 0000000000000..79e031c721ea3
Binary files /dev/null and b/pandas/tests/io/data/times_1900.ods differ
diff --git a/pandas/tests/io/data/times_1904.ods b/pandas/tests/io/data/times_1904.ods
new file mode 100644
index 0000000000000..b47a949d3b715
Binary files /dev/null and b/pandas/tests/io/data/times_1904.ods differ
diff --git a/pandas/tests/io/data/writertable.odt b/pandas/tests/io/data/writertable.odt
new file mode 100644
index 0000000000000..113bd651e8cd0
Binary files /dev/null and b/pandas/tests/io/data/writertable.odt differ
diff --git a/pandas/tests/io/excel/conftest.py b/pandas/tests/io/excel/conftest.py
index 935db254bd2e5..dd96fb2366152 100644
--- a/pandas/tests/io/excel/conftest.py
+++ b/pandas/tests/io/excel/conftest.py
@@ -30,7 +30,7 @@ def df_ref():
return df_ref
-@pytest.fixture(params=['.xls', '.xlsx', '.xlsm'])
+@pytest.fixture(params=['.xls', '.xlsx', '.xlsm', '.ods'])
def read_ext(request):
"""
Valid extensions for reading Excel files.
diff --git a/pandas/tests/io/excel/test_odf.py b/pandas/tests/io/excel/test_odf.py
new file mode 100644
index 0000000000000..76b3fe19a0771
--- /dev/null
+++ b/pandas/tests/io/excel/test_odf.py
@@ -0,0 +1,39 @@
+import functools
+
+import numpy as np
+import pytest
+
+import pandas as pd
+import pandas.util.testing as tm
+
+pytest.importorskip("odf")
+
+
+@pytest.fixture(autouse=True)
+def cd_and_set_engine(monkeypatch, datapath):
+ func = functools.partial(pd.read_excel, engine="odf")
+ monkeypatch.setattr(pd, 'read_excel', func)
+ monkeypatch.chdir(datapath("io", "data"))
+
+
+def test_read_invalid_types_raises():
+ # the invalid_value_type.ods required manually editing
+ # of the included content.xml file
+ with pytest.raises(ValueError,
+ match="Unrecognized type awesome_new_type"):
+ pd.read_excel("invalid_value_type.ods")
+
+
+def test_read_writer_table():
+ # Also test reading tables from an text OpenDocument file
+ # (.odt)
+ index = pd.Index(["Row 1", "Row 2", "Row 3"], name="Header")
+ expected = pd.DataFrame([
+ [1, np.nan, 7],
+ [2, np.nan, 8],
+ [3, np.nan, 9],
+ ], index=index, columns=["Column 1", "Unnamed: 2", "Column 3"])
+
+ result = pd.read_excel("writertable.odt", 'Table1', index_col=0)
+
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py
index be5951fe12b46..ae69c2302e60a 100644
--- a/pandas/tests/io/excel/test_readers.py
+++ b/pandas/tests/io/excel/test_readers.py
@@ -33,9 +33,21 @@ def ignore_xlrd_time_clock_warning():
@pytest.fixture(params=[
# Add any engines to test here
- pytest.param('xlrd', marks=td.skip_if_no('xlrd')),
- pytest.param('openpyxl', marks=td.skip_if_no('openpyxl')),
- pytest.param(None, marks=td.skip_if_no('xlrd')),
+ # When defusedxml is installed it triggers deprecation warnings for
+ # xlrd and openpyxl, so catch those here
+ pytest.param('xlrd', marks=[
+ td.skip_if_no('xlrd'),
+ pytest.mark.filterwarnings("ignore:.*(tree\\.iter|html argument)"),
+ ]),
+ pytest.param('openpyxl', marks=[
+ td.skip_if_no('openpyxl'),
+ pytest.mark.filterwarnings("ignore:.*html argument"),
+ ]),
+ pytest.param(None, marks=[
+ td.skip_if_no('xlrd'),
+ pytest.mark.filterwarnings("ignore:.*(tree\\.iter|html argument)"),
+ ]),
+ pytest.param("odf", marks=td.skip_if_no("odf")),
])
def engine(request):
"""
@@ -53,6 +65,11 @@ def cd_and_set_engine(self, engine, datapath, monkeypatch, read_ext):
"""
if engine == 'openpyxl' and read_ext == '.xls':
pytest.skip()
+ if engine == 'odf' and read_ext != '.ods':
+ pytest.skip()
+ if read_ext == ".ods" and engine != "odf":
+ pytest.skip()
+
func = partial(pd.read_excel, engine=engine)
monkeypatch.chdir(datapath("io", "data"))
monkeypatch.setattr(pd, 'read_excel', func)
@@ -62,14 +79,16 @@ def test_usecols_int(self, read_ext, df_ref):
# usecols as int
with tm.assert_produces_warning(FutureWarning,
- check_stacklevel=False):
+ check_stacklevel=False,
+ raise_on_extra_warnings=False):
with ignore_xlrd_time_clock_warning():
df1 = pd.read_excel("test1" + read_ext, "Sheet1",
index_col=0, usecols=3)
# usecols as int
with tm.assert_produces_warning(FutureWarning,
- check_stacklevel=False):
+ check_stacklevel=False,
+ raise_on_extra_warnings=False):
with ignore_xlrd_time_clock_warning():
df2 = pd.read_excel("test1" + read_ext, "Sheet2", skiprows=[1],
index_col=0, usecols=3)
@@ -439,6 +458,9 @@ def test_bad_engine_raises(self, read_ext):
@tm.network
def test_read_from_http_url(self, read_ext):
+ if read_ext == '.ods': # TODO: remove once on master
+ pytest.skip()
+
url = ('https://raw.github.com/pandas-dev/pandas/master/'
'pandas/tests/io/data/test1' + read_ext)
url_table = pd.read_excel(url)
@@ -736,6 +758,10 @@ def cd_and_set_engine(self, engine, datapath, monkeypatch, read_ext):
"""
Change directory and set engine for ExcelFile objects.
"""
+ if engine == 'odf' and read_ext != '.ods':
+ pytest.skip()
+ if read_ext == ".ods" and engine != "odf":
+ pytest.skip()
if engine == 'openpyxl' and read_ext == '.xls':
pytest.skip()
@@ -802,7 +828,8 @@ def test_excel_table_sheet_by_index(self, read_ext, df_ref):
df3 = pd.read_excel(excel, 0, index_col=0, skipfooter=1)
tm.assert_frame_equal(df3, df1.iloc[:-1])
- with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False,
+ raise_on_extra_warnings=False):
with pd.ExcelFile('test1' + read_ext) as excel:
df4 = pd.read_excel(excel, 0, index_col=0, skip_footer=1)
diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py
index 94e1435d4dfab..d749f0ec3e252 100644
--- a/pandas/tests/io/excel/test_xlrd.py
+++ b/pandas/tests/io/excel/test_xlrd.py
@@ -10,6 +10,12 @@
xlwt = pytest.importorskip("xlwt")
+@pytest.fixture(autouse=True)
+def skip_ods_files(read_ext):
+ if read_ext == ".ods":
+ pytest.skip("Not valid for xlrd")
+
+
def test_read_xlrd_book(read_ext, frame):
df = frame
| closes #2311
This is primarily intended for LibreOffice calc spreadsheets but will
also work with LO Writer and probably with LO Impress documents.
This is an alternate solution to https://github.com/pandas-dev/pandas/pull/9070
There are test cases with several different problematic LibreOffice spread sheets.
git diff upstream/master -u | flake8 appeared to pass.
... I didn't do the whats new entry. Though I expect there's some more work to do before submitting this. I just wanted to get the core code in for comments.
The open issues is, the workaround for https://github.com/pandas-dev/pandas/issues/25422 is embedded in the current code (so all my tests pass right now) but that, or a better solution should move closer to the iso 8601 parser.
Also I don't have the parser class hooked up to a read_excel or read_ods function.
Using read_excel bothers me some... because its not an excel file. I think it would be more clear if there was either a separate read_ods function or a generic read_spreadsheet function than just pressing read_excel into being a generic spreadsheet reader.
Also this just a reader. I had never gotten around to implementing a writer.
| https://api.github.com/repos/pandas-dev/pandas/pulls/25427 | 2019-02-24T06:59:48Z | 2019-07-03T21:45:44Z | 2019-07-03T21:45:43Z | 2019-11-09T15:04:12Z |
Backport PR #25289 on branch 0.24.x (BUG: fixed merging with empty frame containing an Int64 column (#25183)) | diff --git a/doc/source/whatsnew/v0.24.2.rst b/doc/source/whatsnew/v0.24.2.rst
index a7e522d27f8e2..8f4beb3f484a4 100644
--- a/doc/source/whatsnew/v0.24.2.rst
+++ b/doc/source/whatsnew/v0.24.2.rst
@@ -96,7 +96,7 @@ Bug Fixes
**Other**
- Bug in :meth:`Series.is_unique` where single occurrences of ``NaN`` were not considered unique (:issue:`25180`)
--
+- Bug in :func:`merge` when merging an empty ``DataFrame`` with an ``Int64`` column or a non-empty ``DataFrame`` with an ``Int64`` column that is all ``NaN`` (:issue:`25183`)
-
.. _whatsnew_0.242.contributors:
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py
index 640587b7f9f31..cb98274962656 100644
--- a/pandas/core/internals/concat.py
+++ b/pandas/core/internals/concat.py
@@ -190,6 +190,8 @@ def get_reindexed_values(self, empty_dtype, upcasted_na):
pass
elif getattr(self.block, 'is_sparse', False):
pass
+ elif getattr(self.block, 'is_extension', False):
+ pass
else:
missing_arr = np.empty(self.shape, dtype=empty_dtype)
missing_arr.fill(fill_value)
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index 1e60fdbebfeb3..9fe4049dd698b 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -39,6 +39,54 @@ def get_test_data(ngroups=NGROUPS, n=N):
return arr
+def get_series():
+ return [
+ pd.Series([1], dtype='int64'),
+ pd.Series([1], dtype='Int64'),
+ pd.Series([1.23]),
+ pd.Series(['foo']),
+ pd.Series([True]),
+ pd.Series([pd.Timestamp('2018-01-01')]),
+ pd.Series([pd.Timestamp('2018-01-01', tz='US/Eastern')]),
+ ]
+
+
+def get_series_na():
+ return [
+ pd.Series([np.nan], dtype='Int64'),
+ pd.Series([np.nan], dtype='float'),
+ pd.Series([np.nan], dtype='object'),
+ pd.Series([pd.NaT]),
+ ]
+
+
+@pytest.fixture(params=get_series(), ids=lambda x: x.dtype.name)
+def series_of_dtype(request):
+ """
+ A parametrized fixture returning a variety of Series of different
+ dtypes
+ """
+ return request.param
+
+
+@pytest.fixture(params=get_series(), ids=lambda x: x.dtype.name)
+def series_of_dtype2(request):
+ """
+ A duplicate of the series_of_dtype fixture, so that it can be used
+ twice by a single function
+ """
+ return request.param
+
+
+@pytest.fixture(params=get_series_na(), ids=lambda x: x.dtype.name)
+def series_of_dtype_all_na(request):
+ """
+ A parametrized fixture returning a variety of Series with all NA
+ values
+ """
+ return request.param
+
+
class TestMerge(object):
def setup_method(self, method):
@@ -428,6 +476,36 @@ def check2(exp, kwarg):
check1(exp_in, kwarg)
check2(exp_out, kwarg)
+ def test_merge_empty_frame(self, series_of_dtype, series_of_dtype2):
+ # GH 25183
+ df = pd.DataFrame({'key': series_of_dtype, 'value': series_of_dtype2},
+ columns=['key', 'value'])
+ df_empty = df[:0]
+ expected = pd.DataFrame({
+ 'value_x': pd.Series(dtype=df.dtypes['value']),
+ 'key': pd.Series(dtype=df.dtypes['key']),
+ 'value_y': pd.Series(dtype=df.dtypes['value']),
+ }, columns=['value_x', 'key', 'value_y'])
+ actual = df_empty.merge(df, on='key')
+ assert_frame_equal(actual, expected)
+
+ def test_merge_all_na_column(self, series_of_dtype,
+ series_of_dtype_all_na):
+ # GH 25183
+ df_left = pd.DataFrame(
+ {'key': series_of_dtype, 'value': series_of_dtype_all_na},
+ columns=['key', 'value'])
+ df_right = pd.DataFrame(
+ {'key': series_of_dtype, 'value': series_of_dtype_all_na},
+ columns=['key', 'value'])
+ expected = pd.DataFrame({
+ 'key': series_of_dtype,
+ 'value_x': series_of_dtype_all_na,
+ 'value_y': series_of_dtype_all_na,
+ }, columns=['key', 'value_x', 'value_y'])
+ actual = df_left.merge(df_right, on='key')
+ assert_frame_equal(actual, expected)
+
def test_merge_nosort(self):
# #2098, anything to do?
| Backport PR #25289: BUG: fixed merging with empty frame containing an Int64 column (#25183) | https://api.github.com/repos/pandas-dev/pandas/pulls/25426 | 2019-02-24T03:47:48Z | 2019-02-24T07:25:54Z | 2019-02-24T07:25:54Z | 2019-02-24T07:25:55Z |
DOC: Rewriting of ParserError doc + minor spacing | diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py
index 493ee65f63c6a..7d5a7f1a99e41 100644
--- a/pandas/errors/__init__.py
+++ b/pandas/errors/__init__.py
@@ -9,10 +9,10 @@
class PerformanceWarning(Warning):
"""
- Warning raised when there is a possible
- performance impact.
+ Warning raised when there is a possible performance impact.
"""
+
class UnsupportedFunctionCall(ValueError):
"""
Exception raised when attempting to call a numpy function
@@ -20,6 +20,7 @@ class UnsupportedFunctionCall(ValueError):
the object e.g. ``np.cumsum(groupby_object)``.
"""
+
class UnsortedIndexError(KeyError):
"""
Error raised when attempting to get a slice of a MultiIndex,
@@ -31,9 +32,15 @@ class UnsortedIndexError(KeyError):
class ParserError(ValueError):
"""
- Exception that is raised by an error encountered in `pd.read_csv`.
+ Exception that is raised by an error encountered in parsing file contents.
+
+ This is a generic error raised for errors encountered when functions like
+ `read_csv` or `read_html` are parsing contents of a file.
- e.g. HTML Parsing will raise this error.
+ See Also
+ --------
+ read_csv : Read CSV (comma-separated) file into a DataFrame.
+ read_html : Read HTML table into a DataFrame.
"""
@@ -182,4 +189,4 @@ def __str__(self):
else:
name = self.class_instance.__class__.__name__
msg = "This {methodtype} must be defined in the concrete class {name}"
- return (msg.format(methodtype=self.methodtype, name=name))
+ return msg.format(methodtype=self.methodtype, name=name)
| Follow-up to #25414.
| https://api.github.com/repos/pandas-dev/pandas/pulls/25421 | 2019-02-23T19:57:33Z | 2019-02-24T03:27:13Z | 2019-02-24T03:27:13Z | 2019-02-24T03:27:17Z |
fixed geo accessor example in extending.rst | diff --git a/doc/source/development/extending.rst b/doc/source/development/extending.rst
index e6928d9efde06..9e5034f6d3db0 100644
--- a/doc/source/development/extending.rst
+++ b/doc/source/development/extending.rst
@@ -33,8 +33,9 @@ decorate a class, providing the name of attribute to add. The class's
@staticmethod
def _validate(obj):
- if 'lat' not in obj.columns or 'lon' not in obj.columns:
- raise AttributeError("Must have 'lat' and 'lon'.")
+ # verify there is a column latitude and a column longitude
+ if 'latitude' not in obj.columns or 'longitude' not in obj.columns:
+ raise AttributeError("Must have 'latitude' and 'longitude'.")
@property
def center(self):
| The previous code was incompatible with the following paragraph. See the second block of code in https://pandas.pydata.org/pandas-docs/stable/development/extending.html#registering-custom-accessors
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
<details>
```python
import pandas as pd
import numpy as np
```
# Before
## Register the DataFrame accessor "geo"
```python
@pd.api.extensions.register_dataframe_accessor("geo")
class GeoAccessor(object):
def __init__(self, pandas_obj):
self._validate(pandas_obj)
self._obj = pandas_obj
@staticmethod
def _validate(obj):
if 'lat' not in obj.columns or 'lon' not in obj.columns:
raise AttributeError("Must have 'lat' and 'lon'.")
@property
def center(self):
# return the geographic center point of this DataFrame
lat = self._obj.latitude
lon = self._obj.longitude
return (float(lon.mean()), float(lat.mean()))
def plot(self):
# plot this array's data on a map, e.g., using Cartopy
pass
```
## Test the DataFrame accessor "geo"
```python
ds = pd.DataFrame({'longitude': np.linspace(0, 10),
'latitude': np.linspace(0, 20)})
ds.geo.center
```
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-3-71f0445704bc> in <module>()
1 ds = pd.DataFrame({'longitude': np.linspace(0, 10),
2 'latitude': np.linspace(0, 20)})
----> 3 ds.geo.center
~\Anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
5061 if (name in self._internal_names_set or name in self._metadata or
5062 name in self._accessors):
-> 5063 return object.__getattribute__(self, name)
5064 else:
5065 if self._info_axis._can_hold_identifiers_and_holds_name(name):
~\Anaconda3\lib\site-packages\pandas\core\accessor.py in __get__(self, obj, cls)
169 # we're accessing the attribute of the class, i.e., Dataset.geo
170 return self._accessor
--> 171 accessor_obj = self._accessor(obj)
172 # Replace the property with the accessor object. Inspired by:
173 # http://www.pydanny.com/cached-property.html
<ipython-input-2-114caa965d3b> in __init__(self, pandas_obj)
2 class GeoAccessor(object):
3 def __init__(self, pandas_obj):
----> 4 self._validate(pandas_obj)
5 self._obj = pandas_obj
6
<ipython-input-2-114caa965d3b> in _validate(obj)
8 def _validate(obj):
9 if 'lat' not in obj.columns or 'lon' not in obj.columns:
---> 10 raise AttributeError("Must have 'lat' and 'lon'.")
11
12 @property
AttributeError: Must have 'lat' and 'lon'.
# After
## Register the DataFrame accessor "geo"
```python
@pd.api.extensions.register_dataframe_accessor("geo")
class GeoAccessor(object):
def __init__(self, pandas_obj):
self._validate(pandas_obj)
self._obj = pandas_obj
@staticmethod
def _validate(obj):
# verify each column name contains 'lat' or 'lon'
for col in obj.columns:
if 'lat' not in col and 'lon' not in col:
raise AttributeError("Must have 'lat' and 'lon'.")
@property
def center(self):
# return the geographic center point of this DataFrame
lat = self._obj.latitude
lon = self._obj.longitude
return (float(lon.mean()), float(lat.mean()))
def plot(self):
# plot this array's data on a map, e.g., using Cartopy
pass
```
## Test the DataFrame accessor "geo"
```python
ds = pd.DataFrame({'longitude': np.linspace(0, 10),
'latitude': np.linspace(0, 20)})
ds.geo.center
```
(5.0, 10.0)
</details>
| https://api.github.com/repos/pandas-dev/pandas/pulls/25420 | 2019-02-23T19:47:34Z | 2019-02-25T22:35:46Z | 2019-02-25T22:35:46Z | 2019-02-25T22:35:46Z |
ENH: Add Series.str.casefold | diff --git a/doc/source/reference/series.rst b/doc/source/reference/series.rst
index a6ac40b5203bf..b406893e3414a 100644
--- a/doc/source/reference/series.rst
+++ b/doc/source/reference/series.rst
@@ -409,6 +409,7 @@ strings and apply several methods to it. These can be accessed like
:template: autosummary/accessor_method.rst
Series.str.capitalize
+ Series.str.casefold
Series.str.cat
Series.str.center
Series.str.contains
diff --git a/doc/source/user_guide/text.rst b/doc/source/user_guide/text.rst
index e4f60a761750d..6f21a7d9beb36 100644
--- a/doc/source/user_guide/text.rst
+++ b/doc/source/user_guide/text.rst
@@ -600,6 +600,7 @@ Method Summary
:meth:`~Series.str.partition`;Equivalent to ``str.partition``
:meth:`~Series.str.rpartition`;Equivalent to ``str.rpartition``
:meth:`~Series.str.lower`;Equivalent to ``str.lower``
+ :meth:`~Series.str.casefold`;Equivalent to ``str.casefold``
:meth:`~Series.str.upper`;Equivalent to ``str.upper``
:meth:`~Series.str.find`;Equivalent to ``str.find``
:meth:`~Series.str.rfind`;Equivalent to ``str.rfind``
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 170e7f14da397..b94a18d863a41 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -22,6 +22,7 @@ Other Enhancements
- Indexing of ``DataFrame`` and ``Series`` now accepts zerodim ``np.ndarray`` (:issue:`24919`)
- :meth:`Timestamp.replace` now supports the ``fold`` argument to disambiguate DST transition times (:issue:`25017`)
- :meth:`DataFrame.at_time` and :meth:`Series.at_time` now support :meth:`datetime.time` objects with timezones (:issue:`24043`)
+- ``Series.str`` has gained :meth:`Series.str.casefold` method to removes all case distinctions present in a string (:issue:`25405`)
- :meth:`DataFrame.set_index` now works for instances of ``abc.Iterator``, provided their output is of the same length as the calling frame (:issue:`22484`, :issue:`24984`)
- :meth:`DatetimeIndex.union` now supports the ``sort`` argument. The behaviour of the sort parameter matches that of :meth:`Index.union` (:issue:`24994`)
-
diff --git a/pandas/core/strings.py b/pandas/core/strings.py
index cc7a4db515c42..9577b07360f65 100644
--- a/pandas/core/strings.py
+++ b/pandas/core/strings.py
@@ -2926,7 +2926,7 @@ def rindex(self, sub, start=0, end=None):
_shared_docs['casemethods'] = ("""
Convert strings in the Series/Index to %(type)s.
-
+ %(version)s
Equivalent to :meth:`str.%(method)s`.
Returns
@@ -2943,6 +2943,7 @@ def rindex(self, sub, start=0, end=None):
remaining to lowercase.
Series.str.swapcase : Converts uppercase to lowercase and lowercase to
uppercase.
+ Series.str.casefold: Removes all case distinctions in the string.
Examples
--------
@@ -2989,12 +2990,15 @@ def rindex(self, sub, start=0, end=None):
3 sWaPcAsE
dtype: object
""")
- _shared_docs['lower'] = dict(type='lowercase', method='lower')
- _shared_docs['upper'] = dict(type='uppercase', method='upper')
- _shared_docs['title'] = dict(type='titlecase', method='title')
+ _shared_docs['lower'] = dict(type='lowercase', method='lower', version='')
+ _shared_docs['upper'] = dict(type='uppercase', method='upper', version='')
+ _shared_docs['title'] = dict(type='titlecase', method='title', version='')
_shared_docs['capitalize'] = dict(type='be capitalized',
- method='capitalize')
- _shared_docs['swapcase'] = dict(type='be swapcased', method='swapcase')
+ method='capitalize', version='')
+ _shared_docs['swapcase'] = dict(type='be swapcased', method='swapcase',
+ version='')
+ _shared_docs['casefold'] = dict(type='be casefolded', method='casefold',
+ version='\n .. versionadded:: 0.25.0\n')
lower = _noarg_wrapper(lambda x: x.lower(),
docstring=_shared_docs['casemethods'] %
_shared_docs['lower'])
@@ -3010,6 +3014,9 @@ def rindex(self, sub, start=0, end=None):
swapcase = _noarg_wrapper(lambda x: x.swapcase(),
docstring=_shared_docs['casemethods'] %
_shared_docs['swapcase'])
+ casefold = _noarg_wrapper(lambda x: x.casefold(),
+ docstring=_shared_docs['casemethods'] %
+ _shared_docs['casefold'])
_shared_docs['ismethods'] = ("""
Check whether all characters in each string are %(type)s.
diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py
index 7cea3be03d1a7..1ecfedc8685da 100644
--- a/pandas/tests/test_strings.py
+++ b/pandas/tests/test_strings.py
@@ -76,7 +76,7 @@ def assert_series_or_index_equal(left, right):
'len', 'lower', 'lstrip', 'partition',
'rpartition', 'rsplit', 'rstrip',
'slice', 'slice_replace', 'split',
- 'strip', 'swapcase', 'title', 'upper'
+ 'strip', 'swapcase', 'title', 'upper', 'casefold'
], [()] * 100, [{}] * 100))
ids, _, _ = zip(*_any_string_method) # use method name as fixture-id
@@ -3424,3 +3424,12 @@ def test_method_on_bytes(self):
expected = Series(np.array(
['ad', 'be', 'cf'], 'S2').astype(object))
tm.assert_series_equal(result, expected)
+
+ @pytest.mark.skipif(compat.PY2, reason='not in python2')
+ def test_casefold(self):
+ # GH25405
+ expected = Series(['ss', NA, 'case', 'ssd'])
+ s = Series(['ß', NA, 'case', 'ßd'])
+ result = s.str.casefold()
+
+ tm.assert_series_equal(result, expected)
| - [x] closes #25405
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25419 | 2019-02-23T19:41:19Z | 2019-02-28T21:21:40Z | 2019-02-28T21:21:39Z | 2019-02-28T21:21:48Z |
Correct a typo of version number for interpolate() | diff --git a/doc/source/user_guide/missing_data.rst b/doc/source/user_guide/missing_data.rst
index a462f01dcd14f..7883814e91c94 100644
--- a/doc/source/user_guide/missing_data.rst
+++ b/doc/source/user_guide/missing_data.rst
@@ -335,7 +335,7 @@ examined :ref:`in the API <api.dataframe.missing>`.
Interpolation
~~~~~~~~~~~~~
-.. versionadded:: 0.21.0
+.. versionadded:: 0.23.0
The ``limit_area`` keyword argument was added.
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 3647565123523..eb84a9a5810f4 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -6648,7 +6648,7 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None,
(interpolate).
* 'outside': Only fill NaNs outside valid values (extrapolate).
- .. versionadded:: 0.21.0
+ .. versionadded:: 0.23.0
downcast : optional, 'infer' or None, defaults to None
Downcast dtypes if possible.
| Correct a typo of version number in the docstring of _shared_docs['interpolat e'] which is the docstring for pandas.core.resample.Resampler.interpolate, pandas.DataFrame.interpolate, panda s.Series.interpolate, and pandas.Panel.interpolate, and in documentation/user_guide/missing_data about the limit_area keyword argument in interpolate(). The reference can be found at https://github.com/pandas-dev/pandas/issue s/8000#issuecomment-465802842.
| https://api.github.com/repos/pandas-dev/pandas/pulls/25418 | 2019-02-23T00:12:57Z | 2019-02-23T00:16:37Z | 2019-02-23T00:16:37Z | 2019-02-23T03:18:57Z |
DEP: add pytest-mock to environment.yml | diff --git a/environment.yml b/environment.yml
index 47fe8e4c2a640..ce68dccca0c07 100644
--- a/environment.yml
+++ b/environment.yml
@@ -20,6 +20,7 @@ dependencies:
- isort
- moto
- pytest>=4.0
+ - pytest-mock
- sphinx
- numpydoc
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 76aaeefa648f4..22c01ebcef7f0 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -11,6 +11,7 @@ hypothesis>=3.82
isort
moto
pytest>=4.0
+pytest-mock
sphinx
numpydoc
beautifulsoup4>=4.2.1
| Ran into errors when trying to run the test suite in a freshly installed conda environment. There's an error being caused by the fact that #25346 added `pytest-mock` as a dependency in all the CI jobs (to be able to use the `mocker` fixture), but didn't adapt `environment.yml`. This PR fixes that.
| https://api.github.com/repos/pandas-dev/pandas/pulls/25417 | 2019-02-23T00:07:04Z | 2019-02-23T18:36:38Z | 2019-02-23T18:36:38Z | 2019-03-07T17:33:35Z |
ERR: doc update for ParsingError | diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py
index c57d27ff03ac6..493ee65f63c6a 100644
--- a/pandas/errors/__init__.py
+++ b/pandas/errors/__init__.py
@@ -32,6 +32,8 @@ class UnsortedIndexError(KeyError):
class ParserError(ValueError):
"""
Exception that is raised by an error encountered in `pd.read_csv`.
+
+ e.g. HTML Parsing will raise this error.
"""
| Added documentation to Parse Error.
- [x] closes #22881
- [ ] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25414 | 2019-02-22T16:13:04Z | 2019-02-23T19:47:47Z | 2019-02-23T19:47:47Z | 2019-02-23T19:47:56Z |
DOC: Edited docstring of Interval | diff --git a/pandas/_libs/interval.pyx b/pandas/_libs/interval.pyx
index eb511b1adb28a..e86b692e9915e 100644
--- a/pandas/_libs/interval.pyx
+++ b/pandas/_libs/interval.pyx
@@ -150,9 +150,6 @@ cdef class Interval(IntervalMixin):
Left bound for the interval.
right : orderable scalar
Right bound for the interval.
- closed : {'left', 'right', 'both', 'neither'}, default 'right'
- Whether the interval is closed on the left-side, right-side, both or
- neither.
closed : {'right', 'left', 'both', 'neither'}, default 'right'
Whether the interval is closed on the left-side, right-side, both or
neither. See the Notes for more detailed explanation.
| The docstring contained a repeated segment, which I removed. | https://api.github.com/repos/pandas-dev/pandas/pulls/25410 | 2019-02-22T13:31:11Z | 2019-02-22T15:13:31Z | 2019-02-22T15:13:31Z | 2019-02-22T15:14:22Z |
CI: Set pytest minversion to 4.0.2 | diff --git a/ci/deps/azure-27-compat.yaml b/ci/deps/azure-27-compat.yaml
index c68b51fbd6644..a7784f17d1956 100644
--- a/ci/deps/azure-27-compat.yaml
+++ b/ci/deps/azure-27-compat.yaml
@@ -18,7 +18,7 @@ dependencies:
- xlsxwriter=0.5.2
- xlwt=0.7.5
# universal
- - pytest
+ - pytest>=4.0.2
- pytest-xdist
- pytest-mock
- isort
diff --git a/ci/deps/azure-27-locale.yaml b/ci/deps/azure-27-locale.yaml
index 5679c503caddc..8636a63d02fed 100644
--- a/ci/deps/azure-27-locale.yaml
+++ b/ci/deps/azure-27-locale.yaml
@@ -20,7 +20,7 @@ dependencies:
- xlsxwriter=0.5.2
- xlwt=0.7.5
# universal
- - pytest
+ - pytest>=4.0.2
- pytest-xdist
- pytest-mock
- hypothesis>=3.58.0
diff --git a/ci/deps/azure-36-locale_slow.yaml b/ci/deps/azure-36-locale_slow.yaml
index de1f4ad0e9a76..3f788e5ddcf39 100644
--- a/ci/deps/azure-36-locale_slow.yaml
+++ b/ci/deps/azure-36-locale_slow.yaml
@@ -26,7 +26,7 @@ dependencies:
- xlsxwriter
- xlwt
# universal
- - pytest
+ - pytest>=4.0.2
- pytest-xdist
- pytest-mock
- moto
diff --git a/ci/deps/azure-37-locale.yaml b/ci/deps/azure-37-locale.yaml
index a89e63a2b7d3a..9d598cddce91a 100644
--- a/ci/deps/azure-37-locale.yaml
+++ b/ci/deps/azure-37-locale.yaml
@@ -25,7 +25,7 @@ dependencies:
- xlsxwriter
- xlwt
# universal
- - pytest
+ - pytest>=4.0.2
- pytest-xdist
- pytest-mock
- isort
diff --git a/ci/deps/azure-37-numpydev.yaml b/ci/deps/azure-37-numpydev.yaml
index 3132de891299c..e58c1f599279c 100644
--- a/ci/deps/azure-37-numpydev.yaml
+++ b/ci/deps/azure-37-numpydev.yaml
@@ -6,7 +6,7 @@ dependencies:
- pytz
- Cython>=0.28.2
# universal
- - pytest
+ - pytest>=4.0.2
- pytest-xdist
- pytest-mock
- hypothesis>=3.58.0
diff --git a/ci/deps/azure-macos-35.yaml b/ci/deps/azure-macos-35.yaml
index 9710bcb5bf43d..2326e8092cc85 100644
--- a/ci/deps/azure-macos-35.yaml
+++ b/ci/deps/azure-macos-35.yaml
@@ -21,11 +21,11 @@ dependencies:
- xlrd
- xlsxwriter
- xlwt
- # universal
- - pytest
- - pytest-xdist
- - pytest-mock
- isort
- pip:
- python-dateutil==2.5.3
+ # universal
+ - pytest>=4.0.2
+ - pytest-xdist
+ - pytest-mock
- hypothesis>=3.58.0
diff --git a/ci/deps/azure-windows-27.yaml b/ci/deps/azure-windows-27.yaml
index 093c055e69553..f40efdfca3cbd 100644
--- a/ci/deps/azure-windows-27.yaml
+++ b/ci/deps/azure-windows-27.yaml
@@ -25,7 +25,7 @@ dependencies:
- xlwt
# universal
- cython>=0.28.2
- - pytest
+ - pytest>=4.0.2
- pytest-xdist
- pytest-mock
- moto
diff --git a/ci/deps/azure-windows-36.yaml b/ci/deps/azure-windows-36.yaml
index e9db271a75d9d..8517d340f2ba8 100644
--- a/ci/deps/azure-windows-36.yaml
+++ b/ci/deps/azure-windows-36.yaml
@@ -23,7 +23,7 @@ dependencies:
- xlwt
# universal
- cython>=0.28.2
- - pytest
+ - pytest>=4.0.2
- pytest-xdist
- pytest-mock
- hypothesis>=3.58.0
diff --git a/ci/deps/travis-27.yaml b/ci/deps/travis-27.yaml
index 71b224b2c68c2..a910af36a6b10 100644
--- a/ci/deps/travis-27.yaml
+++ b/ci/deps/travis-27.yaml
@@ -39,7 +39,7 @@ dependencies:
- xlsxwriter=0.5.2
- xlwt=0.7.5
# universal
- - pytest
+ - pytest>=4.0.2
- pytest-xdist
- pytest-mock
- moto==1.3.4
diff --git a/ci/deps/travis-36-doc.yaml b/ci/deps/travis-36-doc.yaml
index 1a65d292ef085..6f33bc58a8b21 100644
--- a/ci/deps/travis-36-doc.yaml
+++ b/ci/deps/travis-36-doc.yaml
@@ -41,6 +41,6 @@ dependencies:
- xlsxwriter
- xlwt
# universal
- - pytest
+ - pytest>=4.0.2
- pytest-xdist
- isort
diff --git a/ci/deps/travis-36-locale.yaml b/ci/deps/travis-36-locale.yaml
index 36dbb8013104a..34b289e6c0c2f 100644
--- a/ci/deps/travis-36-locale.yaml
+++ b/ci/deps/travis-36-locale.yaml
@@ -28,7 +28,7 @@ dependencies:
- xlsxwriter
- xlwt
# universal
- - pytest
+ - pytest>=4.0.2
- pytest-xdist
- pytest-mock
- moto
diff --git a/ci/deps/travis-36-slow.yaml b/ci/deps/travis-36-slow.yaml
index f4b9091c4300b..46875d59411d9 100644
--- a/ci/deps/travis-36-slow.yaml
+++ b/ci/deps/travis-36-slow.yaml
@@ -25,7 +25,7 @@ dependencies:
- xlsxwriter
- xlwt
# universal
- - pytest
+ - pytest>=4.0.2
- pytest-xdist
- pytest-mock
- moto
diff --git a/ci/deps/travis-36.yaml b/ci/deps/travis-36.yaml
index e22529784b5ec..06fc0d76a3d16 100644
--- a/ci/deps/travis-36.yaml
+++ b/ci/deps/travis-36.yaml
@@ -33,7 +33,7 @@ dependencies:
- xlsxwriter
- xlwt
# universal
- - pytest
+ - pytest>=4.0.2
- pytest-xdist
- pytest-cov
- pytest-mock
diff --git a/ci/deps/travis-37.yaml b/ci/deps/travis-37.yaml
index a8a5df5894ba5..f71d29fe13378 100644
--- a/ci/deps/travis-37.yaml
+++ b/ci/deps/travis-37.yaml
@@ -12,7 +12,7 @@ dependencies:
- nomkl
- pyarrow
- pytz
- - pytest
+ - pytest>=4.0.2
- pytest-xdist
- pytest-mock
- hypothesis>=3.58.0
diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst
index 511936467641e..1270bfec098e8 100644
--- a/doc/source/development/contributing.rst
+++ b/doc/source/development/contributing.rst
@@ -731,7 +731,7 @@ extensions in `numpy.testing
.. note::
- The earliest supported pytest version is 3.6.0.
+ The earliest supported pytest version is 4.0.2.
Writing tests
~~~~~~~~~~~~~
diff --git a/doc/source/install.rst b/doc/source/install.rst
index 92364fcc9ebd2..5310667c403e5 100644
--- a/doc/source/install.rst
+++ b/doc/source/install.rst
@@ -202,7 +202,7 @@ pandas is equipped with an exhaustive set of unit tests, covering about 97% of
the code base as of this writing. To run it on your machine to verify that
everything is working (and that you have all of the dependencies, soft and hard,
installed), make sure you have `pytest
-<http://docs.pytest.org/en/latest/>`__ >= 3.6 and `Hypothesis
+<http://docs.pytest.org/en/latest/>`__ >= 4.0.2 and `Hypothesis
<https://hypothesis.readthedocs.io/>`__ >= 3.58, then run:
::
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 170e7f14da397..23effdc0d17ee 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -63,6 +63,20 @@ is respected in indexing. (:issue:`24076`, :issue:`16785`)
df = pd.DataFrame([0], index=pd.DatetimeIndex(['2019-01-01'], tz='US/Pacific'))
df['2019-01-01 12:00:00+04:00':'2019-01-01 13:00:00+04:00']
+.. _whatsnew_0250.api_breaking.deps:
+
+Increased minimum versions for dependencies
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+We have updated our minimum supported versions of dependencies (:issue:`23519`).
+If installed, we now require:
+
++-----------------+-----------------+----------+
+| Package | Minimum Version | Required |
++=================+=================+==========+
+| pytest (dev) | 4.0.2 | |
++-----------------+-----------------+----------+
+
.. _whatsnew_0250.api.other:
Other API Changes
diff --git a/environment.yml b/environment.yml
index ce68dccca0c07..c1669c9f49017 100644
--- a/environment.yml
+++ b/environment.yml
@@ -19,7 +19,7 @@ dependencies:
- hypothesis>=3.82
- isort
- moto
- - pytest>=4.0
+ - pytest>=4.0.2
- pytest-mock
- sphinx
- numpydoc
diff --git a/pandas/util/_tester.py b/pandas/util/_tester.py
index 18e8d415459fd..19b1cc700261c 100644
--- a/pandas/util/_tester.py
+++ b/pandas/util/_tester.py
@@ -11,7 +11,7 @@ def test(extra_args=None):
try:
import pytest
except ImportError:
- raise ImportError("Need pytest>=3.0 to run tests")
+ raise ImportError("Need pytest>=4.0.2 to run tests")
try:
import hypothesis # noqa
except ImportError:
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 22c01ebcef7f0..be84c6f29fdeb 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -10,7 +10,7 @@ gitpython
hypothesis>=3.82
isort
moto
-pytest>=4.0
+pytest>=4.0.2
pytest-mock
sphinx
numpydoc
diff --git a/setup.cfg b/setup.cfg
index 956aa23839e73..84b8f69a83f16 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -57,6 +57,7 @@ split_penalty_after_opening_bracket = 1000000
split_penalty_logical_operator = 30
[tool:pytest]
+minversion = 4.0.2
testpaths = pandas
markers =
single: mark a test as single cpu only
| - [x] closes #23519
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25402 | 2019-02-21T15:53:07Z | 2019-02-28T12:59:33Z | 2019-02-28T12:59:33Z | 2019-02-28T14:30:12Z |
Mark test_pct_max_many_rows as high memory | diff --git a/pandas/tests/frame/test_rank.py b/pandas/tests/frame/test_rank.py
index 10c42e0d1a1cf..6bb9dea15d1ce 100644
--- a/pandas/tests/frame/test_rank.py
+++ b/pandas/tests/frame/test_rank.py
@@ -310,6 +310,7 @@ def test_rank_pct_true(self, method, exp):
tm.assert_frame_equal(result, expected)
@pytest.mark.single
+ @pytest.mark.high_memory
def test_pct_max_many_rows(self):
# GH 18271
df = DataFrame({'A': np.arange(2**24 + 1),
diff --git a/pandas/tests/series/test_rank.py b/pandas/tests/series/test_rank.py
index 510a51e002918..dfcda889269ee 100644
--- a/pandas/tests/series/test_rank.py
+++ b/pandas/tests/series/test_rank.py
@@ -499,6 +499,7 @@ def test_rank_first_pct(dtype, ser, exp):
@pytest.mark.single
+@pytest.mark.high_memory
def test_pct_max_many_rows():
# GH 18271
s = Series(np.arange(2**24 + 1))
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index 888cf78a1c66a..cb7426ce2f7c9 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -1484,6 +1484,7 @@ def test_too_many_ndims(self):
algos.rank(arr)
@pytest.mark.single
+ @pytest.mark.high_memory
@pytest.mark.parametrize('values', [
np.arange(2**24 + 1),
np.arange(2**25 + 2).reshape(2**24 + 1, 2)],
| Fixes issue #25384
- [ ] closes #25384
- [ ] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25400 | 2019-02-21T14:06:56Z | 2019-02-22T19:04:26Z | 2019-02-22T19:04:26Z | 2019-02-25T10:59:49Z |
BUG: pd.Series.interpolate non-numeric index column (21662) | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index ccf5c43280765..98fb2af19be64 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -222,7 +222,7 @@ Numeric
- Bug in :meth:`to_numeric` in which numbers were being coerced to float, even though ``errors`` was not ``coerce`` (:issue:`24910`)
- Bug in error messages in :meth:`DataFrame.corr` and :meth:`Series.corr`. Added the possibility of using a callable. (:issue:`25729`)
- Bug in :meth:`Series.divmod` and :meth:`Series.rdivmod` which would raise an (incorrect) ``ValueError`` rather than return a pair of :class:`Series` objects as result (:issue:`25557`)
--
+- Raises a helpful exception when a non-numeric index is sent to :meth:`interpolate` with methods which require numeric index. (:issue:`21662`)
-
-
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 1717b00664f92..de237d32235ca 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -25,10 +25,10 @@
from pandas.core.dtypes.cast import maybe_promote, maybe_upcast_putmask
from pandas.core.dtypes.common import (
ensure_int64, ensure_object, is_bool, is_bool_dtype,
- is_datetime64_any_dtype, is_datetime64tz_dtype, is_dict_like,
- is_extension_array_dtype, is_integer, is_list_like, is_number,
- is_numeric_dtype, is_object_dtype, is_period_arraylike, is_re_compilable,
- is_scalar, is_timedelta64_dtype, pandas_dtype)
+ is_datetime64_any_dtype, is_datetime64_dtype, is_datetime64tz_dtype,
+ is_dict_like, is_extension_array_dtype, is_integer, is_list_like,
+ is_number, is_numeric_dtype, is_object_dtype, is_period_arraylike,
+ is_re_compilable, is_scalar, is_timedelta64_dtype, pandas_dtype)
from pandas.core.dtypes.generic import ABCDataFrame, ABCPanel, ABCSeries
from pandas.core.dtypes.inference import is_hashable
from pandas.core.dtypes.missing import isna, notna
@@ -6863,6 +6863,18 @@ def interpolate(self, method='linear', axis=0, limit=None, inplace=False,
index = np.arange(len(_maybe_transposed_self._get_axis(alt_ax)))
else:
index = _maybe_transposed_self._get_axis(alt_ax)
+ methods = {"index", "values", "nearest", "time"}
+ is_numeric_or_datetime = (
+ is_numeric_dtype(index) or
+ is_datetime64_dtype(index) or
+ is_timedelta64_dtype(index)
+ )
+ if method not in methods and not is_numeric_or_datetime:
+ raise ValueError(
+ "Index column must be numeric or datetime type when "
+ "using {method} method other than linear. "
+ "Try setting a numeric or datetime index column before "
+ "interpolating.".format(method=method))
if isna(index).any():
raise NotImplementedError("Interpolation with NaNs in the index "
diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py
index 2163914f915b2..403fdb383d81a 100644
--- a/pandas/tests/series/test_missing.py
+++ b/pandas/tests/series/test_missing.py
@@ -870,6 +870,22 @@ def nontemporal_method(request):
return method, kwargs
+@pytest.fixture(params=['linear', 'slinear', 'zero', 'quadratic', 'cubic',
+ 'barycentric', 'krogh', 'polynomial', 'spline',
+ 'piecewise_polynomial', 'from_derivatives', 'pchip',
+ 'akima', ])
+def interp_methods_ind(request):
+ """ Fixture that returns a (method name, required kwargs) pair to
+ be tested for various Index types.
+
+ This fixture does not include methods - 'time', 'index', 'nearest',
+ 'values' as a parameterization
+ """
+ method = request.param
+ kwargs = dict(order=1) if method in ('spline', 'polynomial') else dict()
+ return method, kwargs
+
+
class TestSeriesInterpolateData():
def test_interpolate(self, datetime_series, string_series):
ts = Series(np.arange(len(datetime_series), dtype=float),
@@ -1397,3 +1413,55 @@ def test_nonzero_warning(self):
ser = pd.Series([1, 0, 3, 4])
with tm.assert_produces_warning(FutureWarning):
ser.nonzero()
+
+ @pytest.mark.parametrize(
+ "ind",
+ [
+ ['a', 'b', 'c', 'd'],
+ pd.period_range(start="2019-01-01", periods=4),
+ pd.interval_range(start=0, end=4),
+ ])
+ def test_interp_non_timedelta_index(self, interp_methods_ind, ind):
+ # gh 21662
+ df = pd.DataFrame([0, 1, np.nan, 3], index=ind)
+
+ method, kwargs = interp_methods_ind
+ if method == "pchip":
+ _skip_if_no_pchip()
+
+ if method == "linear":
+ result = df[0].interpolate(**kwargs)
+ expected = pd.Series([0.0, 1.0, 2.0, 3.0], name=0, index=ind)
+ assert_series_equal(result, expected)
+ else:
+ expected_error = (
+ "Index column must be numeric or datetime type when "
+ "using {method} method other than linear. "
+ "Try setting a numeric or datetime index column before "
+ "interpolating.".format(method=method))
+ with pytest.raises(ValueError, match=expected_error):
+ df[0].interpolate(method=method, **kwargs)
+
+ def test_interpolate_timedelta_index(self, interp_methods_ind):
+ """
+ Tests for non numerical index types - object, period, timedelta
+ Note that all methods except time, index, nearest and values
+ are tested here.
+ """
+ # gh 21662
+ ind = pd.timedelta_range(start=1, periods=4)
+ df = pd.DataFrame([0, 1, np.nan, 3], index=ind)
+
+ method, kwargs = interp_methods_ind
+ if method == "pchip":
+ _skip_if_no_pchip()
+
+ if method in {"linear", "pchip"}:
+ result = df[0].interpolate(method=method, **kwargs)
+ expected = pd.Series([0.0, 1.0, 2.0, 3.0], name=0, index=ind)
+ assert_series_equal(result, expected)
+ else:
+ pytest.skip(
+ "This interpolation method is not supported for "
+ "Timedelta Index yet."
+ )
| - [x] closes #21662
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
Raises a helpful exception when a non-numeric index is sent to ```interpolate``` with methods which require numeric index. Skipped a few methods which can also work on datetime index.
| https://api.github.com/repos/pandas-dev/pandas/pulls/25394 | 2019-02-21T06:10:16Z | 2019-03-24T23:34:05Z | 2019-03-24T23:34:05Z | 2019-03-25T01:59:03Z |
DOC: Fix typo of see also in DataFrame stat funcs | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 6e79c02d7dbdd..3647565123523 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -10866,7 +10866,7 @@ def _doc_parms(cls):
Series.max : Return the maximum.
Series.idxmin : Return the index of the minimum.
Series.idxmax : Return the index of the maximum.
-DataFrame.min : Return the sum over the requested axis.
+DataFrame.sum : Return the sum over the requested axis.
DataFrame.min : Return the minimum over the requested axis.
DataFrame.max : Return the maximum over the requested axis.
DataFrame.idxmin : Return the index of the minimum over the requested axis.
| fix typo of DataFrame stat functions. | https://api.github.com/repos/pandas-dev/pandas/pulls/25388 | 2019-02-20T14:21:15Z | 2019-02-20T15:50:59Z | 2019-02-20T15:50:59Z | 2019-02-20T15:51:04Z |
Backport PR #25329 on branch 0.24.x (REGR: fix TimedeltaIndex sum and datetime subtraction with NaT (#25282, #25317)) | diff --git a/doc/source/whatsnew/v0.24.2.rst b/doc/source/whatsnew/v0.24.2.rst
index f528c058d2868..a7e522d27f8e2 100644
--- a/doc/source/whatsnew/v0.24.2.rst
+++ b/doc/source/whatsnew/v0.24.2.rst
@@ -26,6 +26,8 @@ Fixed Regressions
- Fixed regression in :meth:`DataFrame.duplicated()`, where empty dataframe was not returning a boolean dtyped Series. (:issue:`25184`)
- Fixed regression in :meth:`Series.min` and :meth:`Series.max` where ``numeric_only=True`` was ignored when the ``Series`` contained ```Categorical`` data (:issue:`25299`)
+- Fixed regression in subtraction between :class:`Series` objects with ``datetime64[ns]`` dtype incorrectly raising ``OverflowError`` when the `Series` on the right contains null values (:issue:`25317`)
+- Fixed regression in :class:`TimedeltaIndex` where `np.sum(index)` incorrectly returned a zero-dimensional object instead of a scalar (:issue:`25282`)
- Fixed regression in ``IntervalDtype`` construction where passing an incorrect string with 'Interval' as a prefix could result in a ``RecursionError``. (:issue:`25338`)
.. _whatsnew_0242.enhancements:
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index d7a8417a71be2..69cb787e0b888 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -720,11 +720,11 @@ def _sub_datetime_arraylike(self, other):
self_i8 = self.asi8
other_i8 = other.asi8
+ arr_mask = self._isnan | other._isnan
new_values = checked_add_with_arr(self_i8, -other_i8,
- arr_mask=self._isnan)
+ arr_mask=arr_mask)
if self._hasnans or other._hasnans:
- mask = (self._isnan) | (other._isnan)
- new_values[mask] = iNaT
+ new_values[arr_mask] = iNaT
return new_values.view('timedelta64[ns]')
def _add_offset(self, offset):
diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py
index 4f0c96f7927da..bb61ac2f96da5 100644
--- a/pandas/core/arrays/timedeltas.py
+++ b/pandas/core/arrays/timedeltas.py
@@ -190,6 +190,8 @@ def __init__(self, values, dtype=_TD_DTYPE, freq=None, copy=False):
"ndarray, or Series or Index containing one of those."
)
raise ValueError(msg.format(type(values).__name__))
+ if values.ndim != 1:
+ raise ValueError("Only 1-dimensional input arrays are supported.")
if values.dtype == 'i8':
# for compat with datetime/timedelta/period shared methods,
@@ -945,6 +947,9 @@ def sequence_to_td64ns(data, copy=False, unit="ns", errors="raise"):
.format(dtype=data.dtype))
data = np.array(data, copy=copy)
+ if data.ndim != 1:
+ raise ValueError("Only 1-dimensional input arrays are supported.")
+
assert data.dtype == 'm8[ns]', data
return data, inferred_freq
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 2fa034670e885..55a32f1fd4fb7 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -665,7 +665,8 @@ def __array_wrap__(self, result, context=None):
"""
Gets called after a ufunc.
"""
- if is_bool_dtype(result):
+ result = lib.item_from_zerodim(result)
+ if is_bool_dtype(result) or lib.is_scalar(result):
return result
attrs = self._get_attributes_dict()
diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py
index f97a1651163e8..acf4075feb94a 100644
--- a/pandas/tests/arithmetic/test_datetime64.py
+++ b/pandas/tests/arithmetic/test_datetime64.py
@@ -1434,6 +1434,20 @@ def test_dt64arr_add_sub_offset_ndarray(self, tz_naive_fixture,
class TestDatetime64OverflowHandling(object):
# TODO: box + de-duplicate
+ def test_dt64_overflow_masking(self, box_with_array):
+ # GH#25317
+ left = Series([Timestamp('1969-12-31')])
+ right = Series([NaT])
+
+ left = tm.box_expected(left, box_with_array)
+ right = tm.box_expected(right, box_with_array)
+
+ expected = TimedeltaIndex([NaT])
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = left - right
+ tm.assert_equal(result, expected)
+
def test_dt64_series_arith_overflow(self):
# GH#12534, fixed by GH#19024
dt = pd.Timestamp('1700-01-31')
diff --git a/pandas/tests/arrays/test_timedeltas.py b/pandas/tests/arrays/test_timedeltas.py
index 6b4662ca02e80..1fec533a14a6f 100644
--- a/pandas/tests/arrays/test_timedeltas.py
+++ b/pandas/tests/arrays/test_timedeltas.py
@@ -9,6 +9,18 @@
class TestTimedeltaArrayConstructor(object):
+ def test_only_1dim_accepted(self):
+ # GH#25282
+ arr = np.array([0, 1, 2, 3], dtype='m8[h]').astype('m8[ns]')
+
+ with pytest.raises(ValueError, match="Only 1-dimensional"):
+ # 2-dim
+ TimedeltaArray(arr.reshape(2, 2))
+
+ with pytest.raises(ValueError, match="Only 1-dimensional"):
+ # 0-dim
+ TimedeltaArray(arr[[0]].squeeze())
+
def test_freq_validation(self):
# ensure that the public constructor cannot create an invalid instance
arr = np.array([0, 0, 1], dtype=np.int64) * 3600 * 10**9
@@ -51,6 +63,16 @@ def test_copy(self):
class TestTimedeltaArray(object):
+ def test_np_sum(self):
+ # GH#25282
+ vals = np.arange(5, dtype=np.int64).view('m8[h]').astype('m8[ns]')
+ arr = TimedeltaArray(vals)
+ result = np.sum(arr)
+ assert result == vals.sum()
+
+ result = np.sum(pd.TimedeltaIndex(arr))
+ assert result == vals.sum()
+
def test_from_sequence_dtype(self):
msg = "dtype .*object.* cannot be converted to timedelta64"
with pytest.raises(ValueError, match=msg):
| Backport PR #25329: REGR: fix TimedeltaIndex sum and datetime subtraction with NaT (#25282, #25317) | https://api.github.com/repos/pandas-dev/pandas/pulls/25385 | 2019-02-20T10:53:05Z | 2019-02-20T12:01:52Z | 2019-02-20T12:01:52Z | 2019-02-20T12:01:53Z |
CLN: (re-)enable infer_dtype to catch complex | diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index 1f0f0a408aee8..34ceeb20e260e 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -939,6 +939,7 @@ _TYPE_MAP = {
'float32': 'floating',
'float64': 'floating',
'f': 'floating',
+ 'complex64': 'complex',
'complex128': 'complex',
'c': 'complex',
'string': 'string' if PY2 else 'bytes',
@@ -1305,6 +1306,9 @@ def infer_dtype(value: object, skipna: object=None) -> str:
elif is_decimal(val):
return 'decimal'
+ elif is_complex(val):
+ return 'complex'
+
elif util.is_float_object(val):
if is_float_array(values):
return 'floating'
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py
index 49a66efaffc11..187b37d4f788e 100644
--- a/pandas/tests/dtypes/test_inference.py
+++ b/pandas/tests/dtypes/test_inference.py
@@ -618,6 +618,37 @@ def test_decimals(self):
result = lib.infer_dtype(arr, skipna=True)
assert result == 'decimal'
+ # complex is compatible with nan, so skipna has no effect
+ @pytest.mark.parametrize('skipna', [True, False])
+ def test_complex(self, skipna):
+ # gets cast to complex on array construction
+ arr = np.array([1.0, 2.0, 1 + 1j])
+ result = lib.infer_dtype(arr, skipna=skipna)
+ assert result == 'complex'
+
+ arr = np.array([1.0, 2.0, 1 + 1j], dtype='O')
+ result = lib.infer_dtype(arr, skipna=skipna)
+ assert result == 'mixed'
+
+ # gets cast to complex on array construction
+ arr = np.array([1, np.nan, 1 + 1j])
+ result = lib.infer_dtype(arr, skipna=skipna)
+ assert result == 'complex'
+
+ arr = np.array([1.0, np.nan, 1 + 1j], dtype='O')
+ result = lib.infer_dtype(arr, skipna=skipna)
+ assert result == 'mixed'
+
+ # complex with nans stays complex
+ arr = np.array([1 + 1j, np.nan, 3 + 3j], dtype='O')
+ result = lib.infer_dtype(arr, skipna=skipna)
+ assert result == 'complex'
+
+ # test smaller complex dtype; will pass through _try_infer_map fastpath
+ arr = np.array([1 + 1j, np.nan, 3 + 3j], dtype=np.complex64)
+ result = lib.infer_dtype(arr, skipna=skipna)
+ assert result == 'complex'
+
def test_string(self):
pass
| - [x] takes a small bite out of #23554
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
`complex` should already be inferred according to the docstring, but isn't. I'm hitting this while working on my PR for #23833 so splitting that off as a separate change.
| https://api.github.com/repos/pandas-dev/pandas/pulls/25382 | 2019-02-20T08:05:21Z | 2019-02-21T13:53:43Z | 2019-02-21T13:53:43Z | 2019-02-22T07:00:33Z |
DOC: edited whatsnew typo | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index afde665407d18..db8f12669bb69 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -28,7 +28,7 @@ Other Enhancements
Backwards incompatible API changes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- :meth:`Timestamp.strptime` will now rise a NotImplementedError (:issue:`21257`)
+- :meth:`Timestamp.strptime` will now raise a NotImplementedError (:issue:`25016`)
.. _whatsnew_0250.api.other:
| xref: redoing the whatsnew entry for PR #25124. Typos were caought by @h-vetinari .
| https://api.github.com/repos/pandas-dev/pandas/pulls/25381 | 2019-02-20T06:22:35Z | 2019-02-20T14:06:50Z | 2019-02-20T14:06:50Z | 2019-04-15T18:29:37Z |
Backport PR #25338 on branch 0.24.x (Interval dtype fix) | diff --git a/doc/source/whatsnew/v0.24.2.rst b/doc/source/whatsnew/v0.24.2.rst
index 8e59c2300e7ca..f528c058d2868 100644
--- a/doc/source/whatsnew/v0.24.2.rst
+++ b/doc/source/whatsnew/v0.24.2.rst
@@ -26,6 +26,7 @@ Fixed Regressions
- Fixed regression in :meth:`DataFrame.duplicated()`, where empty dataframe was not returning a boolean dtyped Series. (:issue:`25184`)
- Fixed regression in :meth:`Series.min` and :meth:`Series.max` where ``numeric_only=True`` was ignored when the ``Series`` contained ```Categorical`` data (:issue:`25299`)
+- Fixed regression in ``IntervalDtype`` construction where passing an incorrect string with 'Interval' as a prefix could result in a ``RecursionError``. (:issue:`25338`)
.. _whatsnew_0242.enhancements:
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index f84471c3b04e8..b73f55329e25b 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -932,13 +932,18 @@ def construct_from_string(cls, string):
attempt to construct this type from a string, raise a TypeError
if its not possible
"""
- if (isinstance(string, compat.string_types) and
- (string.startswith('interval') or
- string.startswith('Interval'))):
- return cls(string)
+ if not isinstance(string, compat.string_types):
+ msg = "a string needs to be passed, got type {typ}"
+ raise TypeError(msg.format(typ=type(string)))
+
+ if (string.lower() == 'interval' or
+ cls._match.search(string) is not None):
+ return cls(string)
- msg = "a string needs to be passed, got type {typ}"
- raise TypeError(msg.format(typ=type(string)))
+ msg = ('Incorrectly formatted string passed to constructor. '
+ 'Valid formats include Interval or Interval[dtype] '
+ 'where dtype is numeric, datetime, or timedelta')
+ raise TypeError(msg)
@property
def type(self):
@@ -979,7 +984,7 @@ def is_dtype(cls, dtype):
return True
else:
return False
- except ValueError:
+ except (ValueError, TypeError):
return False
else:
return False
diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py
index 0fe0a845f5129..71eaf504bdc46 100644
--- a/pandas/tests/dtypes/test_dtypes.py
+++ b/pandas/tests/dtypes/test_dtypes.py
@@ -501,10 +501,11 @@ def test_construction_not_supported(self, subtype):
with pytest.raises(TypeError, match=msg):
IntervalDtype(subtype)
- def test_construction_errors(self):
+ @pytest.mark.parametrize('subtype', ['xx', 'IntervalA', 'Interval[foo]'])
+ def test_construction_errors(self, subtype):
msg = 'could not construct IntervalDtype'
with pytest.raises(TypeError, match=msg):
- IntervalDtype('xx')
+ IntervalDtype(subtype)
def test_construction_from_string(self):
result = IntervalDtype('interval[int64]')
@@ -513,7 +514,7 @@ def test_construction_from_string(self):
assert is_dtype_equal(self.dtype, result)
@pytest.mark.parametrize('string', [
- 'foo', 'foo[int64]', 0, 3.14, ('a', 'b'), None])
+ 0, 3.14, ('a', 'b'), None])
def test_construction_from_string_errors(self, string):
# these are invalid entirely
msg = 'a string needs to be passed, got type'
@@ -522,10 +523,12 @@ def test_construction_from_string_errors(self, string):
IntervalDtype.construct_from_string(string)
@pytest.mark.parametrize('string', [
- 'interval[foo]'])
+ 'foo', 'foo[int64]', 'IntervalA'])
def test_construction_from_string_error_subtype(self, string):
# this is an invalid subtype
- msg = 'could not construct IntervalDtype'
+ msg = ("Incorrectly formatted string passed to constructor. "
+ r"Valid formats include Interval or Interval\[dtype\] "
+ "where dtype is numeric, datetime, or timedelta")
with pytest.raises(TypeError, match=msg):
IntervalDtype.construct_from_string(string)
@@ -549,6 +552,7 @@ def test_is_dtype(self):
assert not IntervalDtype.is_dtype('U')
assert not IntervalDtype.is_dtype('S')
assert not IntervalDtype.is_dtype('foo')
+ assert not IntervalDtype.is_dtype('IntervalA')
assert not IntervalDtype.is_dtype(np.object_)
assert not IntervalDtype.is_dtype(np.int64)
assert not IntervalDtype.is_dtype(np.float64)
diff --git a/pandas/tests/series/test_operators.py b/pandas/tests/series/test_operators.py
index 4d3c9926fc5ae..b2aac441db195 100644
--- a/pandas/tests/series/test_operators.py
+++ b/pandas/tests/series/test_operators.py
@@ -563,6 +563,13 @@ def test_comp_ops_df_compat(self):
with pytest.raises(ValueError, match=msg):
left.to_frame() < right.to_frame()
+ def test_compare_series_interval_keyword(self):
+ # GH 25338
+ s = Series(['IntervalA', 'IntervalB', 'IntervalC'])
+ result = s == 'IntervalA'
+ expected = Series([True, False, False])
+ assert_series_equal(result, expected)
+
class TestSeriesFlexComparisonOps(object):
| Backport PR #25338: Interval dtype fix | https://api.github.com/repos/pandas-dev/pandas/pulls/25380 | 2019-02-20T03:51:44Z | 2019-02-20T08:05:50Z | 2019-02-20T08:05:50Z | 2019-02-20T08:05:50Z |
Backport PR #25371 on branch 0.24.x (Remove spurious MultiIndex creation in `_set_axis_name`) | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 1d8077873e1ea..45a03f19bb3bb 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1331,7 +1331,6 @@ def _set_axis_name(self, name, axis=0, inplace=False):
cat 4
monkey 2
"""
- pd.MultiIndex.from_product([["mammal"], ['dog', 'cat', 'monkey']])
axis = self._get_axis_number(axis)
idx = self._get_axis(axis).set_names(name)
| Backport PR #25371: Remove spurious MultiIndex creation in `_set_axis_name` | https://api.github.com/repos/pandas-dev/pandas/pulls/25372 | 2019-02-19T13:13:05Z | 2019-02-19T13:52:12Z | 2019-02-19T13:52:12Z | 2019-02-19T13:52:13Z |
Remove spurious MultiIndex creation in `_set_axis_name` | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 3a73861086bed..6e79c02d7dbdd 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1333,7 +1333,6 @@ def _set_axis_name(self, name, axis=0, inplace=False):
cat 4
monkey 2
"""
- pd.MultiIndex.from_product([["mammal"], ['dog', 'cat', 'monkey']])
axis = self._get_axis_number(axis)
idx = self._get_axis(axis).set_names(name)
| * Resovles #25370
* Introduced by #22969
- [x] closes #25370
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ N/A ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25371 | 2019-02-19T11:45:56Z | 2019-02-19T13:12:35Z | 2019-02-19T13:12:35Z | 2019-02-19T13:12:41Z |
BUG: Fix potential segfault after pd.Categorical(pd.Series(...), categories=...) | diff --git a/doc/source/whatsnew/v0.24.2.rst b/doc/source/whatsnew/v0.24.2.rst
index a7e522d27f8e2..f2d7e473fe11d 100644
--- a/doc/source/whatsnew/v0.24.2.rst
+++ b/doc/source/whatsnew/v0.24.2.rst
@@ -30,6 +30,8 @@ Fixed Regressions
- Fixed regression in :class:`TimedeltaIndex` where `np.sum(index)` incorrectly returned a zero-dimensional object instead of a scalar (:issue:`25282`)
- Fixed regression in ``IntervalDtype`` construction where passing an incorrect string with 'Interval' as a prefix could result in a ``RecursionError``. (:issue:`25338`)
+- Fixed regression in :class:`Categorical`, where constructing it from a categorical ``Series`` and an explicit ``categories=`` that differed from that in the ``Series`` created an invalid object which could trigger segfaults. (:issue:`25318`)
+
.. _whatsnew_0242.enhancements:
Enhancements
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 79e565df94eae..337312553262d 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -323,14 +323,6 @@ def __init__(self, values, categories=None, ordered=None, dtype=None,
# we may have dtype.categories be None, and we need to
# infer categories in a factorization step futher below
- if is_categorical(values):
- # GH23814, for perf, if values._values already an instance of
- # Categorical, set values to codes, and run fastpath
- if (isinstance(values, (ABCSeries, ABCIndexClass)) and
- isinstance(values._values, type(self))):
- values = values._values.codes.copy()
- fastpath = True
-
if fastpath:
self._codes = coerce_indexer_dtype(values, dtype.categories)
self._dtype = self._dtype.update_dtype(dtype)
@@ -382,7 +374,7 @@ def __init__(self, values, categories=None, ordered=None, dtype=None,
dtype = CategoricalDtype(categories, dtype.ordered)
elif is_categorical_dtype(values):
- old_codes = (values.cat.codes if isinstance(values, ABCSeries)
+ old_codes = (values._values.codes if isinstance(values, ABCSeries)
else values.codes)
codes = _recode_for_categories(old_codes, values.dtype.categories,
dtype.categories)
@@ -2625,6 +2617,9 @@ def _recode_for_categories(codes, old_categories, new_categories):
if len(old_categories) == 0:
# All null anyway, so just retain the nulls
return codes.copy()
+ elif new_categories.equals(old_categories):
+ # Same categories, so no need to actually recode
+ return codes.copy()
indexer = coerce_indexer_dtype(new_categories.get_indexer(old_categories),
new_categories)
new_codes = take_1d(indexer, codes.copy(), fill_value=-1)
diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py
index 25c299692ceca..f07e3aba53cd4 100644
--- a/pandas/tests/arrays/categorical/test_constructors.py
+++ b/pandas/tests/arrays/categorical/test_constructors.py
@@ -212,6 +212,18 @@ def test_constructor(self):
c = Categorical(np.array([], dtype='int64'), # noqa
categories=[3, 2, 1], ordered=True)
+ def test_constructor_with_existing_categories(self):
+ # GH25318: constructing with pd.Series used to bogusly skip recoding
+ # categories
+ c0 = Categorical(["a", "b", "c", "a"])
+ c1 = Categorical(["a", "b", "c", "a"], categories=["b", "c"])
+
+ c2 = Categorical(c0, categories=c1.categories)
+ tm.assert_categorical_equal(c1, c2)
+
+ c3 = Categorical(Series(c0), categories=c1.categories)
+ tm.assert_categorical_equal(c1, c3)
+
def test_constructor_not_sequence(self):
# https://github.com/pandas-dev/pandas/issues/16022
msg = r"^Parameter 'categories' must be list-like, was"
| Closes #25318
| https://api.github.com/repos/pandas-dev/pandas/pulls/25368 | 2019-02-19T08:07:48Z | 2019-03-03T02:36:37Z | 2019-03-03T02:36:37Z | 2019-03-03T02:36:37Z |
#23049: test for Fatal Stack Overflow stemming From Misuse of astype(… | diff --git a/pandas/tests/frame/test_combine_concat.py b/pandas/tests/frame/test_combine_concat.py
index 59497153c8524..c2364dc135a9a 100644
--- a/pandas/tests/frame/test_combine_concat.py
+++ b/pandas/tests/frame/test_combine_concat.py
@@ -504,6 +504,16 @@ def test_concat_numerical_names(self):
names=[1, 2]))
tm.assert_frame_equal(result, expected)
+ def test_concat_astype_dup_col(self):
+ # gh 23049
+ df = pd.DataFrame([{'a': 'b'}])
+ df = pd.concat([df, df], axis=1)
+
+ result = df.astype('category')
+ expected = pd.DataFrame(np.array(["b", "b"]).reshape(1, 2),
+ columns=["a", "a"]).astype("category")
+ tm.assert_frame_equal(result, expected)
+
class TestDataFrameCombineFirst(TestData):
| …'category')
- [x] closes #23049
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
The referenced issue seems to be solved in the current master. So added a test for the edge case.
| https://api.github.com/repos/pandas-dev/pandas/pulls/25366 | 2019-02-19T06:31:01Z | 2019-02-19T13:14:25Z | 2019-02-19T13:14:25Z | 2019-02-19T18:55:22Z |
DOC: modify typos in Contributing section | diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst
index c9d6845107dfc..511936467641e 100644
--- a/doc/source/development/contributing.rst
+++ b/doc/source/development/contributing.rst
@@ -54,7 +54,7 @@ Bug reports must:
...
```
-#. Include the full version string of *pandas* and its dependencies. You can use the built in function::
+#. Include the full version string of *pandas* and its dependencies. You can use the built-in function::
>>> import pandas as pd
>>> pd.show_versions()
@@ -211,7 +211,7 @@ See the full conda docs `here <http://conda.pydata.org/docs>`__.
Creating a Python Environment (pip)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-If you aren't using conda for you development environment, follow these instructions.
+If you aren't using conda for your development environment, follow these instructions.
You'll need to have at least python3.5 installed on your system.
.. code-block:: none
@@ -484,7 +484,7 @@ contributing them to the project::
./ci/code_checks.sh
-The script verify the linting of code files, it looks for common mistake patterns
+The script verifies the linting of code files, it looks for common mistake patterns
(like missing spaces around sphinx directives that make the documentation not
being rendered properly) and it also validates the doctests. It is possible to
run the checks independently by using the parameters ``lint``, ``patterns`` and
@@ -675,7 +675,7 @@ Otherwise, you need to do it manually:
You'll also need to
-1. write a new test that asserts a warning is issued when calling with the deprecated argument
+1. Write a new test that asserts a warning is issued when calling with the deprecated argument
2. Update all of pandas existing tests and code to use the new argument
See :ref:`contributing.warnings` for more.
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
I participated in an open source sprint day today. This is my first attempt to request a PR to contribute to open source. I made changes to fix a few minor typos. | https://api.github.com/repos/pandas-dev/pandas/pulls/25365 | 2019-02-19T05:48:42Z | 2019-02-19T08:45:51Z | 2019-02-19T08:45:51Z | 2019-02-20T08:01:39Z |
Backport PR #25352: TST: xfail excel styler tests, xref GH25351 | diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py
index 717e9bc23c6b1..e4dd18db37eac 100644
--- a/pandas/tests/io/test_excel.py
+++ b/pandas/tests/io/test_excel.py
@@ -2417,7 +2417,10 @@ def style(df):
['', '', '']],
index=df.index, columns=df.columns)
- def assert_equal_style(cell1, cell2):
+ def assert_equal_style(cell1, cell2, engine):
+ if engine in ['xlsxwriter', 'openpyxl']:
+ pytest.xfail(reason=("GH25351: failing on some attribute "
+ "comparisons in {}".format(engine)))
# XXX: should find a better way to check equality
assert cell1.alignment.__dict__ == cell2.alignment.__dict__
assert cell1.border.__dict__ == cell2.border.__dict__
@@ -2461,7 +2464,7 @@ def custom_converter(css):
assert len(col1) == len(col2)
for cell1, cell2 in zip(col1, col2):
assert cell1.value == cell2.value
- assert_equal_style(cell1, cell2)
+ assert_equal_style(cell1, cell2, engine)
n_cells += 1
# ensure iteration actually happened:
@@ -2519,7 +2522,7 @@ def custom_converter(css):
assert cell1.number_format == 'General'
assert cell2.number_format == '0%'
else:
- assert_equal_style(cell1, cell2)
+ assert_equal_style(cell1, cell2, engine)
assert cell1.value == cell2.value
n_cells += 1
@@ -2537,7 +2540,7 @@ def custom_converter(css):
assert not cell1.font.bold
assert cell2.font.bold
else:
- assert_equal_style(cell1, cell2)
+ assert_equal_style(cell1, cell2, engine)
assert cell1.value == cell2.value
n_cells += 1
| Backports https://github.com/pandas-dev/pandas/pull/25352, as the excel tests are also failing on 0.24.x (cc @jreback ) | https://api.github.com/repos/pandas-dev/pandas/pulls/25363 | 2019-02-18T15:17:54Z | 2019-02-19T08:44:04Z | 2019-02-19T08:44:04Z | 2019-02-19T08:44:49Z |
Backport PR #25360 on branch 0.24.x (DOC: Correct doc mistake in combiner func) | diff --git a/doc/source/getting_started/basics.rst b/doc/source/getting_started/basics.rst
index 02cbc7e2c3b6d..bbec7b5de1d2e 100644
--- a/doc/source/getting_started/basics.rst
+++ b/doc/source/getting_started/basics.rst
@@ -505,7 +505,7 @@ So, for instance, to reproduce :meth:`~DataFrame.combine_first` as above:
.. ipython:: python
def combiner(x, y):
- np.where(pd.isna(x), y, x)
+ return np.where(pd.isna(x), y, x)
df1.combine(df2, combiner)
.. _basics.stats:
| Backport PR #25360: DOC: Correct doc mistake in combiner func | https://api.github.com/repos/pandas-dev/pandas/pulls/25361 | 2019-02-18T13:30:26Z | 2019-02-18T13:34:29Z | 2019-02-18T13:34:29Z | 2019-02-18T18:38:29Z |
DOC: Correct doc mistake in combiner func | diff --git a/doc/source/getting_started/basics.rst b/doc/source/getting_started/basics.rst
index 02cbc7e2c3b6d..bbec7b5de1d2e 100644
--- a/doc/source/getting_started/basics.rst
+++ b/doc/source/getting_started/basics.rst
@@ -505,7 +505,7 @@ So, for instance, to reproduce :meth:`~DataFrame.combine_first` as above:
.. ipython:: python
def combiner(x, y):
- np.where(pd.isna(x), y, x)
+ return np.where(pd.isna(x), y, x)
df1.combine(df2, combiner)
.. _basics.stats:
| Closes #25359.
| https://api.github.com/repos/pandas-dev/pandas/pulls/25360 | 2019-02-18T10:27:49Z | 2019-02-18T13:29:56Z | 2019-02-18T13:29:56Z | 2019-02-18T19:00:44Z |
DOC: Fix #24268 by updating description for keep in Series.nlargest | diff --git a/pandas/core/series.py b/pandas/core/series.py
index cada6663ce651..f6598ed1ee614 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -3098,8 +3098,10 @@ def nlargest(self, n=5, keep='first'):
When there are duplicate values that cannot all fit in a
Series of `n` elements:
- - ``first`` : take the first occurrences based on the index order
- - ``last`` : take the last occurrences based on the index order
+ - ``first`` : return the first `n` occurrences in order
+ of appearance.
+ - ``last`` : return the last `n` occurrences in reverse
+ order of appearance.
- ``all`` : keep all occurrences. This can result in a Series of
size larger than `n`.
@@ -3194,8 +3196,10 @@ def nsmallest(self, n=5, keep='first'):
When there are duplicate values that cannot all fit in a
Series of `n` elements:
- - ``first`` : take the first occurrences based on the index order
- - ``last`` : take the last occurrences based on the index order
+ - ``first`` : return the first `n` occurrences in order
+ of appearance.
+ - ``last`` : return the last `n` occurrences in reverse
+ order of appearance.
- ``all`` : keep all occurrences. This can result in a Series of
size larger than `n`.
@@ -3236,7 +3240,7 @@ def nsmallest(self, n=5, keep='first'):
Monserat 5200
dtype: int64
- The `n` largest elements where ``n=5`` by default.
+ The `n` smallest elements where ``n=5`` by default.
>>> s.nsmallest()
Monserat 5200
| Fix #24268 by updating the description of `keep` in Series.nlargest
- [x] closes #24268
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25358 | 2019-02-18T08:38:09Z | 2019-03-05T03:07:09Z | 2019-03-05T03:07:08Z | 2019-03-05T03:07:09Z |
CLN: Parmeterize test cases | diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index 9d0bce3b342b4..806bd7f2b7c93 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -704,45 +704,29 @@ def test_complex(self):
# Complex data type should raise error
pytest.raises(ValueError, df.to_sql, 'test_complex', self.conn)
- def test_to_sql_index_label(self):
- temp_frame = DataFrame({'col1': range(4)})
-
+ @pytest.mark.parametrize("index_name,index_label,expected", [
# no index name, defaults to 'index'
- sql.to_sql(temp_frame, 'test_index_label', self.conn)
- frame = sql.read_sql_query('SELECT * FROM test_index_label', self.conn)
- assert frame.columns[0] == 'index'
-
+ (None, None, "index"),
# specifying index_label
- sql.to_sql(temp_frame, 'test_index_label', self.conn,
- if_exists='replace', index_label='other_label')
- frame = sql.read_sql_query('SELECT * FROM test_index_label', self.conn)
- assert frame.columns[0] == "other_label"
-
+ (None, "other_label", "other_label"),
# using the index name
- temp_frame.index.name = 'index_name'
- sql.to_sql(temp_frame, 'test_index_label', self.conn,
- if_exists='replace')
- frame = sql.read_sql_query('SELECT * FROM test_index_label', self.conn)
- assert frame.columns[0] == "index_name"
-
+ ("index_name", None, "index_name"),
# has index name, but specifying index_label
- sql.to_sql(temp_frame, 'test_index_label', self.conn,
- if_exists='replace', index_label='other_label')
- frame = sql.read_sql_query('SELECT * FROM test_index_label', self.conn)
- assert frame.columns[0] == "other_label"
-
+ ("index_name", "other_label", "other_label"),
# index name is integer
- temp_frame.index.name = 0
- sql.to_sql(temp_frame, 'test_index_label', self.conn,
- if_exists='replace')
- frame = sql.read_sql_query('SELECT * FROM test_index_label', self.conn)
- assert frame.columns[0] == "0"
-
- temp_frame.index.name = None
+ (0, None, "0"),
+ # index name is None but index label is integer
+ (None, 0, "0"),
+ ])
+ def test_to_sql_index_label(self, index_name,
+ index_label, expected):
+ temp_frame = DataFrame({'col1': range(4)})
+ temp_frame.index.name = index_name
+ query = 'SELECT * FROM test_index_label'
sql.to_sql(temp_frame, 'test_index_label', self.conn,
- if_exists='replace', index_label=0)
- frame = sql.read_sql_query('SELECT * FROM test_index_label', self.conn)
- assert frame.columns[0] == "0"
+ index_label=index_label)
+ frame = sql.read_sql_query(query, self.conn)
+ assert frame.columns[0] == expected
def test_to_sql_index_label_multiindex(self):
temp_frame = DataFrame({'col1': range(4)},
| - [x] xref #22624
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
| https://api.github.com/repos/pandas-dev/pandas/pulls/25355 | 2019-02-17T19:04:46Z | 2019-03-09T02:02:56Z | 2019-03-09T02:02:56Z | 2019-03-09T02:03:01Z |
TST: xfail excel styler tests, xref GH25351 | diff --git a/pandas/_libs/src/compat_helper.h b/pandas/_libs/src/compat_helper.h
index 462f53392adee..078069fb48af2 100644
--- a/pandas/_libs/src/compat_helper.h
+++ b/pandas/_libs/src/compat_helper.h
@@ -29,8 +29,8 @@ the macro, which restores compat.
#ifndef PYPY_VERSION
# if PY_VERSION_HEX < 0x03070000 && defined(PySlice_GetIndicesEx)
# undef PySlice_GetIndicesEx
-# endif
-#endif
+# endif // PY_VERSION_HEX
+#endif // PYPY_VERSION
PANDAS_INLINE int slice_get_indices(PyObject *s,
Py_ssize_t length,
@@ -44,7 +44,7 @@ PANDAS_INLINE int slice_get_indices(PyObject *s,
#else
return PySlice_GetIndicesEx((PySliceObject *)s, length, start,
stop, step, slicelength);
-#endif
+#endif // PY_VERSION_HEX
}
#endif // PANDAS__LIBS_SRC_COMPAT_HELPER_H_
diff --git a/pandas/_libs/src/inline_helper.h b/pandas/_libs/src/inline_helper.h
index 397ec8e7b2cb8..e203a05d2eb56 100644
--- a/pandas/_libs/src/inline_helper.h
+++ b/pandas/_libs/src/inline_helper.h
@@ -19,7 +19,7 @@ The full license is in the LICENSE file, distributed with this software.
#define PANDAS_INLINE static inline
#else
#define PANDAS_INLINE
- #endif
-#endif
+ #endif // __GNUC__
+#endif // PANDAS_INLINE
#endif // PANDAS__LIBS_SRC_INLINE_HELPER_H_
diff --git a/pandas/_libs/src/parse_helper.h b/pandas/_libs/src/parse_helper.h
index b71131bee7008..6fcd2ed0a9ea0 100644
--- a/pandas/_libs/src/parse_helper.h
+++ b/pandas/_libs/src/parse_helper.h
@@ -30,7 +30,7 @@ int to_double(char *item, double *p_value, char sci, char decimal,
#if PY_VERSION_HEX < 0x02060000
#define PyBytes_Check PyString_Check
#define PyBytes_AS_STRING PyString_AS_STRING
-#endif
+#endif // PY_VERSION_HEX
int floatify(PyObject *str, double *result, int *maybe_int) {
int status;
diff --git a/pandas/_libs/src/parser/io.c b/pandas/_libs/src/parser/io.c
index 19271c78501ba..f578ce138e274 100644
--- a/pandas/_libs/src/parser/io.c
+++ b/pandas/_libs/src/parser/io.c
@@ -15,7 +15,7 @@ The full license is in the LICENSE file, distributed with this software.
#ifndef O_BINARY
#define O_BINARY 0
-#endif /* O_BINARY */
+#endif // O_BINARY
/*
On-disk FILE, uncompressed
@@ -277,4 +277,4 @@ void *buffer_mmap_bytes(void *source, size_t nbytes, size_t *bytes_read,
return NULL;
}
-#endif
+#endif // HAVE_MMAP
diff --git a/pandas/_libs/src/parser/io.h b/pandas/_libs/src/parser/io.h
index d22e8ddaea88d..074322c7bdf78 100644
--- a/pandas/_libs/src/parser/io.h
+++ b/pandas/_libs/src/parser/io.h
@@ -25,7 +25,7 @@ typedef struct _file_source {
#if !defined(_WIN32) && !defined(HAVE_MMAP)
#define HAVE_MMAP
-#endif
+#endif // HAVE_MMAP
typedef struct _memory_map {
int fd;
diff --git a/pandas/_libs/src/parser/tokenizer.c b/pandas/_libs/src/parser/tokenizer.c
index a86af7c5416de..6acf3c3de0c91 100644
--- a/pandas/_libs/src/parser/tokenizer.c
+++ b/pandas/_libs/src/parser/tokenizer.c
@@ -1480,7 +1480,7 @@ int main(int argc, char *argv[]) {
return 0;
}
-#endif
+#endif // TEST
// ---------------------------------------------------------------------------
// Implementation of xstrtod
diff --git a/pandas/_libs/src/parser/tokenizer.h b/pandas/_libs/src/parser/tokenizer.h
index c32c061c7fa89..ce9dd39b16222 100644
--- a/pandas/_libs/src/parser/tokenizer.h
+++ b/pandas/_libs/src/parser/tokenizer.h
@@ -42,7 +42,7 @@ See LICENSE for the license
#if defined(_MSC_VER)
#define strtoll _strtoi64
-#endif
+#endif // _MSC_VER
/*
@@ -75,7 +75,7 @@ See LICENSE for the license
#define TRACE(X) printf X;
#else
#define TRACE(X)
-#endif
+#endif // VERBOSE
#define PARSER_OUT_OF_MEMORY -1
diff --git a/pandas/_libs/tslibs/src/datetime/np_datetime.c b/pandas/_libs/tslibs/src/datetime/np_datetime.c
index 866c9ca9d3ac7..87866d804503e 100644
--- a/pandas/_libs/tslibs/src/datetime/np_datetime.c
+++ b/pandas/_libs/tslibs/src/datetime/np_datetime.c
@@ -30,7 +30,7 @@ This file is derived from NumPy 1.7. See NUMPY_LICENSE.txt
#if PY_MAJOR_VERSION >= 3
#define PyInt_AsLong PyLong_AsLong
-#endif
+#endif // PyInt_AsLong
const npy_datetimestruct _NS_MIN_DTS = {
1677, 9, 21, 0, 12, 43, 145225, 0, 0};
diff --git a/pandas/_libs/tslibs/src/datetime/np_datetime_strings.c b/pandas/_libs/tslibs/src/datetime/np_datetime_strings.c
index 05ccdd13598fb..207da4b8f8340 100644
--- a/pandas/_libs/tslibs/src/datetime/np_datetime_strings.c
+++ b/pandas/_libs/tslibs/src/datetime/np_datetime_strings.c
@@ -609,7 +609,7 @@ int make_iso_8601_datetime(npy_datetimestruct *dts, char *outstr, int outlen,
tmplen = _snprintf(substr, sublen, "%04" NPY_INT64_FMT, dts->year);
#else
tmplen = snprintf(substr, sublen, "%04" NPY_INT64_FMT, dts->year);
-#endif
+#endif // _WIN32
/* If it ran out of space or there isn't space for the NULL terminator */
if (tmplen < 0 || tmplen > sublen) {
goto string_too_short;
diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py
index 8c92db734168b..09b2d86bde3d3 100644
--- a/pandas/tests/io/test_excel.py
+++ b/pandas/tests/io/test_excel.py
@@ -2413,7 +2413,10 @@ def style(df):
['', '', '']],
index=df.index, columns=df.columns)
- def assert_equal_style(cell1, cell2):
+ def assert_equal_style(cell1, cell2, engine):
+ if engine in ['xlsxwriter', 'openpyxl']:
+ pytest.xfail(reason=("GH25351: failing on some attribute "
+ "comparisons in {}".format(engine)))
# XXX: should find a better way to check equality
assert cell1.alignment.__dict__ == cell2.alignment.__dict__
assert cell1.border.__dict__ == cell2.border.__dict__
@@ -2457,7 +2460,7 @@ def custom_converter(css):
assert len(col1) == len(col2)
for cell1, cell2 in zip(col1, col2):
assert cell1.value == cell2.value
- assert_equal_style(cell1, cell2)
+ assert_equal_style(cell1, cell2, engine)
n_cells += 1
# ensure iteration actually happened:
@@ -2515,7 +2518,7 @@ def custom_converter(css):
assert cell1.number_format == 'General'
assert cell2.number_format == '0%'
else:
- assert_equal_style(cell1, cell2)
+ assert_equal_style(cell1, cell2, engine)
assert cell1.value == cell2.value
n_cells += 1
@@ -2533,7 +2536,7 @@ def custom_converter(css):
assert not cell1.font.bold
assert cell2.font.bold
else:
- assert_equal_style(cell1, cell2)
+ assert_equal_style(cell1, cell2, engine)
assert cell1.value == cell2.value
n_cells += 1
diff --git a/pandas/util/move.c b/pandas/util/move.c
index 9bb662d50cb3f..188d7b79b35d2 100644
--- a/pandas/util/move.c
+++ b/pandas/util/move.c
@@ -19,15 +19,15 @@ The full license is in the LICENSE file, distributed with this software.
/* in python 3, we cannot intern bytes objects so this is always false */
#define PyString_CHECK_INTERNED(cs) 0
-#endif /* !COMPILING_IN_PY2 */
+#endif // !COMPILING_IN_PY2
#ifndef Py_TPFLAGS_HAVE_GETCHARBUFFER
#define Py_TPFLAGS_HAVE_GETCHARBUFFER 0
-#endif
+#endif // Py_TPFLAGS_HAVE_GETCHARBUFFER
#ifndef Py_TPFLAGS_HAVE_NEWBUFFER
#define Py_TPFLAGS_HAVE_NEWBUFFER 0
-#endif
+#endif // Py_TPFLAGS_HAVE_NEWBUFFER
static PyObject *badmove; /* bad move exception class */
@@ -85,14 +85,14 @@ static PyBufferProcs stolenbuf_as_buffer = {
(getbufferproc) stolenbuf_getbuffer,
};
-#else /* Python 3 */
+#else // Python 3
static PyBufferProcs stolenbuf_as_buffer = {
(getbufferproc) stolenbuf_getbuffer,
NULL,
};
-#endif /* COMPILING_IN_PY2 */
+#endif // COMPILING_IN_PY2
PyDoc_STRVAR(stolenbuf_doc,
"A buffer that is wrapping a stolen bytes object's buffer.");
@@ -208,7 +208,7 @@ static PyModuleDef move_module = {
-1,
methods,
};
-#endif /* !COMPILING_IN_PY2 */
+#endif // !COMPILING_IN_PY2
PyDoc_STRVAR(
badmove_doc,
@@ -231,7 +231,7 @@ PyInit__move(void)
#else
#define ERROR_RETURN
init_move(void)
-#endif /* !COMPILING_IN_PY2 */
+#endif // !COMPILING_IN_PY2
{
PyObject *m;
@@ -250,7 +250,7 @@ init_move(void)
if (!(m = PyModule_Create(&move_module)))
#else
if (!(m = Py_InitModule(MODULE_NAME, methods)))
-#endif /* !COMPILING_IN_PY2 */
+#endif // !COMPILING_IN_PY2
{
return ERROR_RETURN;
}
@@ -269,5 +269,5 @@ init_move(void)
#if !COMPILING_IN_PY2
return m;
-#endif /* !COMPILING_IN_PY2 */
+#endif // !COMPILING_IN_PY2
}
| xref #25351 | https://api.github.com/repos/pandas-dev/pandas/pulls/25352 | 2019-02-17T15:02:02Z | 2019-02-17T17:27:07Z | 2019-02-17T17:27:07Z | 2019-02-17T17:29:52Z |
TST: use a fixed seed to have the same uniques across python versions | diff --git a/ci/deps/azure-27-compat.yaml b/ci/deps/azure-27-compat.yaml
index 8899e22bdf6cf..986855c464852 100644
--- a/ci/deps/azure-27-compat.yaml
+++ b/ci/deps/azure-27-compat.yaml
@@ -20,6 +20,7 @@ dependencies:
# universal
- pytest
- pytest-xdist
+ - pytest-mock
- pip:
- html5lib==1.0b2
- beautifulsoup4==4.2.1
diff --git a/ci/deps/azure-27-locale.yaml b/ci/deps/azure-27-locale.yaml
index 0846ef5e8264e..f73079ecbe3d2 100644
--- a/ci/deps/azure-27-locale.yaml
+++ b/ci/deps/azure-27-locale.yaml
@@ -22,6 +22,7 @@ dependencies:
# universal
- pytest
- pytest-xdist
+ - pytest-mock
- hypothesis>=3.58.0
- pip:
- html5lib==1.0b2
diff --git a/ci/deps/azure-36-locale_slow.yaml b/ci/deps/azure-36-locale_slow.yaml
index c7d2334623501..6b8d38fd25082 100644
--- a/ci/deps/azure-36-locale_slow.yaml
+++ b/ci/deps/azure-36-locale_slow.yaml
@@ -28,6 +28,7 @@ dependencies:
# universal
- pytest
- pytest-xdist
+ - pytest-mock
- moto
- pip:
- hypothesis>=3.58.0
diff --git a/ci/deps/azure-37-locale.yaml b/ci/deps/azure-37-locale.yaml
index b5a05c49b8083..569b71dae003b 100644
--- a/ci/deps/azure-37-locale.yaml
+++ b/ci/deps/azure-37-locale.yaml
@@ -27,6 +27,7 @@ dependencies:
# universal
- pytest
- pytest-xdist
+ - pytest-mock
- pip:
- hypothesis>=3.58.0
- moto # latest moto in conda-forge fails with 3.7, move to conda dependencies when this is fixed
diff --git a/ci/deps/azure-37-numpydev.yaml b/ci/deps/azure-37-numpydev.yaml
index 99ae228f25de3..a37be124cc546 100644
--- a/ci/deps/azure-37-numpydev.yaml
+++ b/ci/deps/azure-37-numpydev.yaml
@@ -8,6 +8,7 @@ dependencies:
# universal
- pytest
- pytest-xdist
+ - pytest-mock
- hypothesis>=3.58.0
- pip:
- "git+git://github.com/dateutil/dateutil.git"
diff --git a/ci/deps/azure-macos-35.yaml b/ci/deps/azure-macos-35.yaml
index 58abbabce3d86..d1fe926744ecd 100644
--- a/ci/deps/azure-macos-35.yaml
+++ b/ci/deps/azure-macos-35.yaml
@@ -24,6 +24,7 @@ dependencies:
# universal
- pytest
- pytest-xdist
+ - pytest-mock
- pip:
- python-dateutil==2.5.3
- hypothesis>=3.58.0
diff --git a/ci/deps/azure-windows-27.yaml b/ci/deps/azure-windows-27.yaml
index b1533b071fa74..74faeed83c387 100644
--- a/ci/deps/azure-windows-27.yaml
+++ b/ci/deps/azure-windows-27.yaml
@@ -27,5 +27,6 @@ dependencies:
- cython>=0.28.2
- pytest
- pytest-xdist
+ - pytest-mock
- moto
- hypothesis>=3.58.0
diff --git a/ci/deps/azure-windows-36.yaml b/ci/deps/azure-windows-36.yaml
index 7b132a134c44e..94d67b3d37788 100644
--- a/ci/deps/azure-windows-36.yaml
+++ b/ci/deps/azure-windows-36.yaml
@@ -25,4 +25,5 @@ dependencies:
- cython>=0.28.2
- pytest
- pytest-xdist
+ - pytest-mock
- hypothesis>=3.58.0
diff --git a/ci/deps/travis-27.yaml b/ci/deps/travis-27.yaml
index 2624797b24fa1..4915c003bce4e 100644
--- a/ci/deps/travis-27.yaml
+++ b/ci/deps/travis-27.yaml
@@ -41,6 +41,7 @@ dependencies:
# universal
- pytest
- pytest-xdist
+ - pytest-mock
- moto==1.3.4
- hypothesis>=3.58.0
- pip:
diff --git a/ci/deps/travis-36-locale.yaml b/ci/deps/travis-36-locale.yaml
index 2b38465c04512..2a7692f10752c 100644
--- a/ci/deps/travis-36-locale.yaml
+++ b/ci/deps/travis-36-locale.yaml
@@ -30,6 +30,7 @@ dependencies:
# universal
- pytest
- pytest-xdist
+ - pytest-mock
- moto
- pip:
- hypothesis>=3.58.0
diff --git a/ci/deps/travis-36-slow.yaml b/ci/deps/travis-36-slow.yaml
index a6ffdb95e5e7c..7934d179c8618 100644
--- a/ci/deps/travis-36-slow.yaml
+++ b/ci/deps/travis-36-slow.yaml
@@ -27,5 +27,6 @@ dependencies:
# universal
- pytest
- pytest-xdist
+ - pytest-mock
- moto
- hypothesis>=3.58.0
diff --git a/ci/deps/travis-36.yaml b/ci/deps/travis-36.yaml
index 74db888d588f4..857c3fadfdaeb 100644
--- a/ci/deps/travis-36.yaml
+++ b/ci/deps/travis-36.yaml
@@ -36,6 +36,7 @@ dependencies:
- pytest
- pytest-xdist
- pytest-cov
+ - pytest-mock
- hypothesis>=3.58.0
- pip:
- brotlipy
diff --git a/ci/deps/travis-37.yaml b/ci/deps/travis-37.yaml
index c503124d8cd26..125750191de7d 100644
--- a/ci/deps/travis-37.yaml
+++ b/ci/deps/travis-37.yaml
@@ -14,6 +14,7 @@ dependencies:
- pytz
- pytest
- pytest-xdist
+ - pytest-mock
- hypothesis>=3.58.0
- s3fs
- pip:
diff --git a/pandas/tests/io/formats/test_console.py b/pandas/tests/io/formats/test_console.py
index 45c5e982c1c48..a3e0e195f4864 100644
--- a/pandas/tests/io/formats/test_console.py
+++ b/pandas/tests/io/formats/test_console.py
@@ -78,13 +78,12 @@ def test_detect_console_encoding_fallback_to_default(monkeypatch, std, locale):
@pytest.mark.parametrize("size", ['', ['']])
-def test_terminal_unknown_dimensions(monkeypatch, size):
- mock = pytest.importorskip("unittest.mock")
+def test_terminal_unknown_dimensions(monkeypatch, size, mocker):
def communicate(*args, **kwargs):
return size
- monkeypatch.setattr('subprocess.Popen', mock.Mock())
+ monkeypatch.setattr('subprocess.Popen', mocker.Mock())
monkeypatch.setattr('subprocess.Popen.return_value.returncode', None)
monkeypatch.setattr(
'subprocess.Popen.return_value.communicate', communicate)
diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py
index ceccb48194f85..71b100401ec21 100644
--- a/pandas/tests/resample/test_datetime_index.py
+++ b/pandas/tests/resample/test_datetime_index.py
@@ -1160,9 +1160,13 @@ def test_resample_nunique_with_date_gap():
@pytest.mark.parametrize('k', [10, 100, 1000])
def test_resample_group_info(n, k):
# GH10914
+
+ # use a fixed seed to always have the same uniques
+ prng = np.random.RandomState(1234)
+
dr = date_range(start='2015-08-27', periods=n // 10, freq='T')
- ts = Series(np.random.randint(0, n // k, n).astype('int64'),
- index=np.random.choice(dr, n))
+ ts = Series(prng.randint(0, n // k, n).astype('int64'),
+ index=prng.choice(dr, n))
left = ts.resample('30T').nunique()
ix = date_range(start=ts.index.min(), end=ts.index.max(),
| https://api.github.com/repos/pandas-dev/pandas/pulls/25346 | 2019-02-16T19:24:34Z | 2019-02-16T20:41:05Z | 2019-02-16T20:41:05Z | 2019-03-11T16:50:51Z | |
Backport PR #25304 on branch 0.24.x (BUG: Fix passing of numeric_only argument for categorical reduce) | diff --git a/doc/source/whatsnew/v0.24.2.rst b/doc/source/whatsnew/v0.24.2.rst
index 0c66df3129b2d..8e59c2300e7ca 100644
--- a/doc/source/whatsnew/v0.24.2.rst
+++ b/doc/source/whatsnew/v0.24.2.rst
@@ -25,6 +25,7 @@ Fixed Regressions
- Fixed regression in :meth:`DataFrame.apply` causing ``RecursionError`` when ``dict``-like classes were passed as argument. (:issue:`25196`)
- Fixed regression in :meth:`DataFrame.duplicated()`, where empty dataframe was not returning a boolean dtyped Series. (:issue:`25184`)
+- Fixed regression in :meth:`Series.min` and :meth:`Series.max` where ``numeric_only=True`` was ignored when the ``Series`` contained ```Categorical`` data (:issue:`25299`)
.. _whatsnew_0242.enhancements:
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 35b662eaae9a5..3f38785e6619e 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -2173,7 +2173,7 @@ def _reverse_indexer(self):
return result
# reduction ops #
- def _reduce(self, name, axis=0, skipna=True, **kwargs):
+ def _reduce(self, name, axis=0, **kwargs):
func = getattr(self, name, None)
if func is None:
msg = 'Categorical cannot perform the operation {op}'
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 0c8e697c572e8..3ed4e2e12ed73 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -3610,8 +3610,12 @@ def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None,
if axis is not None:
self._get_axis_number(axis)
- # dispatch to ExtensionArray interface
- if isinstance(delegate, ExtensionArray):
+ if isinstance(delegate, Categorical):
+ # TODO deprecate numeric_only argument for Categorical and use
+ # skipna as well, see GH25303
+ return delegate._reduce(name, numeric_only=numeric_only, **kwds)
+ elif isinstance(delegate, ExtensionArray):
+ # dispatch to ExtensionArray interface
return delegate._reduce(name, skipna=skipna, **kwds)
elif is_datetime64_dtype(delegate):
# use DatetimeIndex implementation to handle skipna correctly
diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py
index 173f719edd465..8520855d14918 100644
--- a/pandas/tests/reductions/test_reductions.py
+++ b/pandas/tests/reductions/test_reductions.py
@@ -960,6 +960,27 @@ def test_min_max(self):
assert np.isnan(_min)
assert _max == 1
+ def test_min_max_numeric_only(self):
+ # TODO deprecate numeric_only argument for Categorical and use
+ # skipna as well, see GH25303
+ cat = Series(Categorical(
+ ["a", "b", np.nan, "a"], categories=['b', 'a'], ordered=True))
+
+ _min = cat.min()
+ _max = cat.max()
+ assert np.isnan(_min)
+ assert _max == "a"
+
+ _min = cat.min(numeric_only=True)
+ _max = cat.max(numeric_only=True)
+ assert _min == "b"
+ assert _max == "a"
+
+ _min = cat.min(numeric_only=False)
+ _max = cat.max(numeric_only=False)
+ assert np.isnan(_min)
+ assert _max == "a"
+
class TestSeriesMode(object):
# Note: the name TestSeriesMode indicates these tests
| Backport PR #25304: BUG: Fix passing of numeric_only argument for categorical reduce | https://api.github.com/repos/pandas-dev/pandas/pulls/25344 | 2019-02-16T18:50:01Z | 2019-02-16T19:52:37Z | 2019-02-16T19:52:37Z | 2019-02-16T19:52:38Z |
Backport PR #25088 on branch 0.24.x (Fixes Formatting Exception) | diff --git a/doc/source/whatsnew/v0.24.2.rst b/doc/source/whatsnew/v0.24.2.rst
index f17c4974cd450..d0308c82daffc 100644
--- a/doc/source/whatsnew/v0.24.2.rst
+++ b/doc/source/whatsnew/v0.24.2.rst
@@ -53,6 +53,7 @@ Bug Fixes
**I/O**
+- Better handling of terminal printing when the terminal dimensions are not known (:issue:`25080`);
- Bug in reading a HDF5 table-format ``DataFrame`` created in Python 2, in Python 3 (:issue:`24925`)
- Bug in reading a JSON with ``orient='table'`` generated by :meth:`DataFrame.to_json` with ``index=False`` (:issue:`25170`)
- Bug where float indexes could have misaligned values when printing (:issue:`25061`)
diff --git a/pandas/io/formats/terminal.py b/pandas/io/formats/terminal.py
index bb34259d710c7..cf2383955d593 100644
--- a/pandas/io/formats/terminal.py
+++ b/pandas/io/formats/terminal.py
@@ -15,6 +15,7 @@
import os
import shutil
+import subprocess
from pandas.compat import PY3
@@ -94,22 +95,29 @@ def _get_terminal_size_tput():
# get terminal width
# src: http://stackoverflow.com/questions/263890/how-do-i-find-the-width
# -height-of-a-terminal-window
+
try:
- import subprocess
proc = subprocess.Popen(["tput", "cols"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
- output = proc.communicate(input=None)
- cols = int(output[0])
+ output_cols = proc.communicate(input=None)
proc = subprocess.Popen(["tput", "lines"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
- output = proc.communicate(input=None)
- rows = int(output[0])
- return (cols, rows)
+ output_rows = proc.communicate(input=None)
except OSError:
return None
+ try:
+ # Some terminals (e.g. spyder) may report a terminal size of '',
+ # making the `int` fail.
+
+ cols = int(output_cols[0])
+ rows = int(output_rows[0])
+ return cols, rows
+ except (ValueError, IndexError):
+ return None
+
def _get_terminal_size_linux():
def ioctl_GWINSZ(fd):
diff --git a/pandas/tests/io/formats/test_console.py b/pandas/tests/io/formats/test_console.py
index 055763bf62d6e..45c5e982c1c48 100644
--- a/pandas/tests/io/formats/test_console.py
+++ b/pandas/tests/io/formats/test_console.py
@@ -1,6 +1,9 @@
+import subprocess # noqa: F401
+
import pytest
from pandas.io.formats.console import detect_console_encoding
+from pandas.io.formats.terminal import _get_terminal_size_tput
class MockEncoding(object): # TODO(py27): replace with mock
@@ -72,3 +75,19 @@ def test_detect_console_encoding_fallback_to_default(monkeypatch, std, locale):
context.setattr('sys.stdout', MockEncoding(std))
context.setattr('sys.getdefaultencoding', lambda: 'sysDefaultEncoding')
assert detect_console_encoding() == 'sysDefaultEncoding'
+
+
+@pytest.mark.parametrize("size", ['', ['']])
+def test_terminal_unknown_dimensions(monkeypatch, size):
+ mock = pytest.importorskip("unittest.mock")
+
+ def communicate(*args, **kwargs):
+ return size
+
+ monkeypatch.setattr('subprocess.Popen', mock.Mock())
+ monkeypatch.setattr('subprocess.Popen.return_value.returncode', None)
+ monkeypatch.setattr(
+ 'subprocess.Popen.return_value.communicate', communicate)
+ result = _get_terminal_size_tput()
+
+ assert result is None
| Backport PR #25088: Fixes Formatting Exception | https://api.github.com/repos/pandas-dev/pandas/pulls/25343 | 2019-02-16T16:34:59Z | 2019-02-16T17:57:13Z | 2019-02-16T17:57:13Z | 2019-02-16T17:59:38Z |
Backport PR #25264 on branch 0.24.x (BUG: groupby.transform retains timezone information) | diff --git a/doc/source/whatsnew/v0.24.2.rst b/doc/source/whatsnew/v0.24.2.rst
index f17c4974cd450..0c78cf01ad300 100644
--- a/doc/source/whatsnew/v0.24.2.rst
+++ b/doc/source/whatsnew/v0.24.2.rst
@@ -78,7 +78,7 @@ Bug Fixes
**Reshaping**
--
+- Bug in :meth:`pandas.core.groupby.GroupBy.transform` where applying a function to a timezone aware column would return a timezone naive result (:issue:`24198`)
- Bug in :func:`DataFrame.join` when joining on a timezone aware :class:`DatetimeIndex` (:issue:`23931`)
-
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index c5142a4ee98cc..5be98b013384d 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -965,7 +965,7 @@ def _transform_fast(self, func, func_nm):
ids, _, ngroup = self.grouper.group_info
cast = self._transform_should_cast(func_nm)
- out = algorithms.take_1d(func().values, ids)
+ out = algorithms.take_1d(func()._values, ids)
if cast:
out = self._try_cast(out, self.obj)
return Series(out, index=self.obj.index, name=self.obj.name)
diff --git a/pandas/tests/groupby/test_transform.py b/pandas/tests/groupby/test_transform.py
index f120402e6e8ca..b645073fcf72a 100644
--- a/pandas/tests/groupby/test_transform.py
+++ b/pandas/tests/groupby/test_transform.py
@@ -834,3 +834,14 @@ def demean_rename(x):
tm.assert_frame_equal(result, expected)
result_single = df.groupby('group').value.transform(demean_rename)
tm.assert_series_equal(result_single, expected['value'])
+
+
+@pytest.mark.parametrize('func', [min, max, np.min, np.max, 'first', 'last'])
+def test_groupby_transform_timezone_column(func):
+ # GH 24198
+ ts = pd.to_datetime('now', utc=True).tz_convert('Asia/Singapore')
+ result = pd.DataFrame({'end_time': [ts], 'id': [1]})
+ result['max_end_time'] = result.groupby('id').end_time.transform(func)
+ expected = pd.DataFrame([[ts, 1, ts]], columns=['end_time', 'id',
+ 'max_end_time'])
+ tm.assert_frame_equal(result, expected)
| Backport PR #25264: BUG: groupby.transform retains timezone information | https://api.github.com/repos/pandas-dev/pandas/pulls/25342 | 2019-02-16T16:32:35Z | 2019-02-16T17:28:04Z | 2019-02-16T17:28:04Z | 2019-02-16T17:28:38Z |
Interval dtype fix | diff --git a/doc/source/whatsnew/v0.24.2.rst b/doc/source/whatsnew/v0.24.2.rst
index 8e59c2300e7ca..f528c058d2868 100644
--- a/doc/source/whatsnew/v0.24.2.rst
+++ b/doc/source/whatsnew/v0.24.2.rst
@@ -26,6 +26,7 @@ Fixed Regressions
- Fixed regression in :meth:`DataFrame.duplicated()`, where empty dataframe was not returning a boolean dtyped Series. (:issue:`25184`)
- Fixed regression in :meth:`Series.min` and :meth:`Series.max` where ``numeric_only=True`` was ignored when the ``Series`` contained ```Categorical`` data (:issue:`25299`)
+- Fixed regression in ``IntervalDtype`` construction where passing an incorrect string with 'Interval' as a prefix could result in a ``RecursionError``. (:issue:`25338`)
.. _whatsnew_0242.enhancements:
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index 640d43f3b0e03..11a132c4d14ee 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -931,13 +931,18 @@ def construct_from_string(cls, string):
attempt to construct this type from a string, raise a TypeError
if its not possible
"""
- if (isinstance(string, compat.string_types) and
- (string.startswith('interval') or
- string.startswith('Interval'))):
- return cls(string)
+ if not isinstance(string, compat.string_types):
+ msg = "a string needs to be passed, got type {typ}"
+ raise TypeError(msg.format(typ=type(string)))
+
+ if (string.lower() == 'interval' or
+ cls._match.search(string) is not None):
+ return cls(string)
- msg = "a string needs to be passed, got type {typ}"
- raise TypeError(msg.format(typ=type(string)))
+ msg = ('Incorrectly formatted string passed to constructor. '
+ 'Valid formats include Interval or Interval[dtype] '
+ 'where dtype is numeric, datetime, or timedelta')
+ raise TypeError(msg)
@property
def type(self):
@@ -978,7 +983,7 @@ def is_dtype(cls, dtype):
return True
else:
return False
- except ValueError:
+ except (ValueError, TypeError):
return False
else:
return False
diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py
index 710f215686eab..1c1442d6f2f23 100644
--- a/pandas/tests/dtypes/test_dtypes.py
+++ b/pandas/tests/dtypes/test_dtypes.py
@@ -511,10 +511,11 @@ def test_construction_not_supported(self, subtype):
with pytest.raises(TypeError, match=msg):
IntervalDtype(subtype)
- def test_construction_errors(self):
+ @pytest.mark.parametrize('subtype', ['xx', 'IntervalA', 'Interval[foo]'])
+ def test_construction_errors(self, subtype):
msg = 'could not construct IntervalDtype'
with pytest.raises(TypeError, match=msg):
- IntervalDtype('xx')
+ IntervalDtype(subtype)
def test_construction_from_string(self):
result = IntervalDtype('interval[int64]')
@@ -523,7 +524,7 @@ def test_construction_from_string(self):
assert is_dtype_equal(self.dtype, result)
@pytest.mark.parametrize('string', [
- 'foo', 'foo[int64]', 0, 3.14, ('a', 'b'), None])
+ 0, 3.14, ('a', 'b'), None])
def test_construction_from_string_errors(self, string):
# these are invalid entirely
msg = 'a string needs to be passed, got type'
@@ -532,10 +533,12 @@ def test_construction_from_string_errors(self, string):
IntervalDtype.construct_from_string(string)
@pytest.mark.parametrize('string', [
- 'interval[foo]'])
+ 'foo', 'foo[int64]', 'IntervalA'])
def test_construction_from_string_error_subtype(self, string):
# this is an invalid subtype
- msg = 'could not construct IntervalDtype'
+ msg = ("Incorrectly formatted string passed to constructor. "
+ r"Valid formats include Interval or Interval\[dtype\] "
+ "where dtype is numeric, datetime, or timedelta")
with pytest.raises(TypeError, match=msg):
IntervalDtype.construct_from_string(string)
@@ -559,6 +562,7 @@ def test_is_dtype(self):
assert not IntervalDtype.is_dtype('U')
assert not IntervalDtype.is_dtype('S')
assert not IntervalDtype.is_dtype('foo')
+ assert not IntervalDtype.is_dtype('IntervalA')
assert not IntervalDtype.is_dtype(np.object_)
assert not IntervalDtype.is_dtype(np.int64)
assert not IntervalDtype.is_dtype(np.float64)
diff --git a/pandas/tests/series/test_operators.py b/pandas/tests/series/test_operators.py
index 4d3c9926fc5ae..b2aac441db195 100644
--- a/pandas/tests/series/test_operators.py
+++ b/pandas/tests/series/test_operators.py
@@ -563,6 +563,13 @@ def test_comp_ops_df_compat(self):
with pytest.raises(ValueError, match=msg):
left.to_frame() < right.to_frame()
+ def test_compare_series_interval_keyword(self):
+ # GH 25338
+ s = Series(['IntervalA', 'IntervalB', 'IntervalC'])
+ result = s == 'IntervalA'
+ expected = Series([True, False, False])
+ assert_series_equal(result, expected)
+
class TestSeriesFlexComparisonOps(object):
| - [x] closes #25283
- [x] test added to ensure pd.api.types.IntervalDtype('IntervalA') throws TypeError
- [x] test added to ensure pd.api.types.IntervalDtype.construct_from_string('IntervalA') throws TypeError
- [x] test added to ensure pd.api.types.IntervalDtype.is_dtype('IntervalA') returns false
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] test added to ensure * `Series(['IntervalA', 'IntervalB', 'IntervalC']) == 'IntervalA'` returns the expected boolean series
- [x] what's new note added to doc/source/whatsnew/v0.24.2.rst documenting regression fix | https://api.github.com/repos/pandas-dev/pandas/pulls/25338 | 2019-02-15T23:53:58Z | 2019-02-20T03:51:05Z | 2019-02-20T03:51:05Z | 2019-02-20T04:00:57Z |
Doc: corrects spelling in generic.py | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index e2308836d982a..b1fcbba7bd7ec 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -7604,16 +7604,16 @@ def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,
using the `level` parameter:
>>> arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'],
- ... ['Capitve', 'Wild', 'Capitve', 'Wild']]
+ ... ['Captive', 'Wild', 'Captive', 'Wild']]
>>> index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type'))
>>> df = pd.DataFrame({'Max Speed' : [390., 350., 30., 20.]},
... index=index)
>>> df
Max Speed
Animal Type
- Falcon Capitve 390.0
+ Falcon Captive 390.0
Wild 350.0
- Parrot Capitve 30.0
+ Parrot Captive 30.0
Wild 20.0
>>> df.groupby(level=0).mean()
Max Speed
@@ -7623,7 +7623,7 @@ def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,
>>> df.groupby(level=1).mean()
Max Speed
Type
- Capitve 210.0
+ Captive 210.0
Wild 185.0
"""
from pandas.core.groupby.groupby import groupby
| Corrects spelling of capitve to captive.
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25333 | 2019-02-15T14:56:48Z | 2019-02-15T18:42:46Z | 2019-02-15T18:42:46Z | 2019-02-15T18:43:02Z |
REGR: fix TimedeltaIndex sum and datetime subtraction with NaT (#25282, #25317) | diff --git a/doc/source/whatsnew/v0.24.2.rst b/doc/source/whatsnew/v0.24.2.rst
index f528c058d2868..a7e522d27f8e2 100644
--- a/doc/source/whatsnew/v0.24.2.rst
+++ b/doc/source/whatsnew/v0.24.2.rst
@@ -26,6 +26,8 @@ Fixed Regressions
- Fixed regression in :meth:`DataFrame.duplicated()`, where empty dataframe was not returning a boolean dtyped Series. (:issue:`25184`)
- Fixed regression in :meth:`Series.min` and :meth:`Series.max` where ``numeric_only=True`` was ignored when the ``Series`` contained ```Categorical`` data (:issue:`25299`)
+- Fixed regression in subtraction between :class:`Series` objects with ``datetime64[ns]`` dtype incorrectly raising ``OverflowError`` when the `Series` on the right contains null values (:issue:`25317`)
+- Fixed regression in :class:`TimedeltaIndex` where `np.sum(index)` incorrectly returned a zero-dimensional object instead of a scalar (:issue:`25282`)
- Fixed regression in ``IntervalDtype`` construction where passing an incorrect string with 'Interval' as a prefix could result in a ``RecursionError``. (:issue:`25338`)
.. _whatsnew_0242.enhancements:
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index cd8e8ed520ddc..75cf658423210 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -720,11 +720,11 @@ def _sub_datetime_arraylike(self, other):
self_i8 = self.asi8
other_i8 = other.asi8
+ arr_mask = self._isnan | other._isnan
new_values = checked_add_with_arr(self_i8, -other_i8,
- arr_mask=self._isnan)
+ arr_mask=arr_mask)
if self._hasnans or other._hasnans:
- mask = (self._isnan) | (other._isnan)
- new_values[mask] = iNaT
+ new_values[arr_mask] = iNaT
return new_values.view('timedelta64[ns]')
def _add_offset(self, offset):
diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py
index 06e2bf76fcf96..74fe8072e6924 100644
--- a/pandas/core/arrays/timedeltas.py
+++ b/pandas/core/arrays/timedeltas.py
@@ -190,6 +190,8 @@ def __init__(self, values, dtype=_TD_DTYPE, freq=None, copy=False):
"ndarray, or Series or Index containing one of those."
)
raise ValueError(msg.format(type(values).__name__))
+ if values.ndim != 1:
+ raise ValueError("Only 1-dimensional input arrays are supported.")
if values.dtype == 'i8':
# for compat with datetime/timedelta/period shared methods,
@@ -945,6 +947,9 @@ def sequence_to_td64ns(data, copy=False, unit="ns", errors="raise"):
.format(dtype=data.dtype))
data = np.array(data, copy=copy)
+ if data.ndim != 1:
+ raise ValueError("Only 1-dimensional input arrays are supported.")
+
assert data.dtype == 'm8[ns]', data
return data, inferred_freq
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index f2c8ac6e9b413..b5f3c929a7f36 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -665,7 +665,8 @@ def __array_wrap__(self, result, context=None):
"""
Gets called after a ufunc.
"""
- if is_bool_dtype(result):
+ result = lib.item_from_zerodim(result)
+ if is_bool_dtype(result) or lib.is_scalar(result):
return result
attrs = self._get_attributes_dict()
diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py
index 405dc0805a285..c81a371f37dc1 100644
--- a/pandas/tests/arithmetic/test_datetime64.py
+++ b/pandas/tests/arithmetic/test_datetime64.py
@@ -1440,6 +1440,20 @@ def test_dt64arr_add_sub_offset_ndarray(self, tz_naive_fixture,
class TestDatetime64OverflowHandling(object):
# TODO: box + de-duplicate
+ def test_dt64_overflow_masking(self, box_with_array):
+ # GH#25317
+ left = Series([Timestamp('1969-12-31')])
+ right = Series([NaT])
+
+ left = tm.box_expected(left, box_with_array)
+ right = tm.box_expected(right, box_with_array)
+
+ expected = TimedeltaIndex([NaT])
+ expected = tm.box_expected(expected, box_with_array)
+
+ result = left - right
+ tm.assert_equal(result, expected)
+
def test_dt64_series_arith_overflow(self):
# GH#12534, fixed by GH#19024
dt = pd.Timestamp('1700-01-31')
diff --git a/pandas/tests/arrays/test_timedeltas.py b/pandas/tests/arrays/test_timedeltas.py
index 6b4662ca02e80..1fec533a14a6f 100644
--- a/pandas/tests/arrays/test_timedeltas.py
+++ b/pandas/tests/arrays/test_timedeltas.py
@@ -9,6 +9,18 @@
class TestTimedeltaArrayConstructor(object):
+ def test_only_1dim_accepted(self):
+ # GH#25282
+ arr = np.array([0, 1, 2, 3], dtype='m8[h]').astype('m8[ns]')
+
+ with pytest.raises(ValueError, match="Only 1-dimensional"):
+ # 2-dim
+ TimedeltaArray(arr.reshape(2, 2))
+
+ with pytest.raises(ValueError, match="Only 1-dimensional"):
+ # 0-dim
+ TimedeltaArray(arr[[0]].squeeze())
+
def test_freq_validation(self):
# ensure that the public constructor cannot create an invalid instance
arr = np.array([0, 0, 1], dtype=np.int64) * 3600 * 10**9
@@ -51,6 +63,16 @@ def test_copy(self):
class TestTimedeltaArray(object):
+ def test_np_sum(self):
+ # GH#25282
+ vals = np.arange(5, dtype=np.int64).view('m8[h]').astype('m8[ns]')
+ arr = TimedeltaArray(vals)
+ result = np.sum(arr)
+ assert result == vals.sum()
+
+ result = np.sum(pd.TimedeltaIndex(arr))
+ assert result == vals.sum()
+
def test_from_sequence_dtype(self):
msg = "dtype .*object.* cannot be converted to timedelta64"
with pytest.raises(ValueError, match=msg):
| closes #25282
closes #25317
- [x] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25329 | 2019-02-15T02:53:40Z | 2019-02-20T10:52:02Z | 2019-02-20T10:52:02Z | 2019-02-20T14:39:53Z |
DOC: Improvement docstring of DataFrame.rank() | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index e2308836d982a..2e534d25bcfca 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -8286,34 +8286,85 @@ def last(self, offset):
def rank(self, axis=0, method='average', numeric_only=None,
na_option='keep', ascending=True, pct=False):
"""
- Compute numerical data ranks (1 through n) along axis. Equal values are
- assigned a rank that is the average of the ranks of those values.
+ Compute numerical data ranks (1 through n) along axis.
+
+ By default, equal values are assigned a rank that is the average of the
+ ranks of those values.
Parameters
----------
axis : {0 or 'index', 1 or 'columns'}, default 0
- index to direct ranking
- method : {'average', 'min', 'max', 'first', 'dense'}
- * average: average rank of group
- * min: lowest rank in group
- * max: highest rank in group
+ Index to direct ranking.
+ method : {'average', 'min', 'max', 'first', 'dense'}, default 'average'
+ How to rank the group of records that have the same value
+ (i.e. ties):
+
+ * average: average rank of the group
+ * min: lowest rank in the group
+ * max: highest rank in the group
* first: ranks assigned in order they appear in the array
* dense: like 'min', but rank always increases by 1 between groups
- numeric_only : boolean, default None
- Include only float, int, boolean data. Valid only for DataFrame or
- Panel objects
- na_option : {'keep', 'top', 'bottom'}
- * keep: leave NA values where they are
- * top: smallest rank if ascending
- * bottom: smallest rank if descending
- ascending : boolean, default True
- False for ranks by high (1) to low (N)
- pct : boolean, default False
- Computes percentage rank of data
+ numeric_only : bool, optional
+ For DataFrame objects, rank only numeric columns if set to True.
+ na_option : {'keep', 'top', 'bottom'}, default 'keep'
+ How to rank NaN values:
+
+ * keep: assign NaN rank to NaN values
+ * top: assign smallest rank to NaN values if ascending
+ * bottom: assign highest rank to NaN values if ascending
+ ascending : bool, default True
+ Whether or not the elements should be ranked in ascending order.
+ pct : bool, default False
+ Whether or not to display the returned rankings in percentile
+ form.
Returns
-------
- ranks : same type as caller
+ same type as caller
+ Return a Series or DataFrame with data ranks as values.
+
+ See Also
+ --------
+ core.groupby.GroupBy.rank : Rank of values within each group.
+
+ Examples
+ --------
+
+ >>> df = pd.DataFrame(data={'Animal': ['cat', 'penguin', 'dog',
+ ... 'spider', 'snake'],
+ ... 'Number_legs': [4, 2, 4, 8, np.nan]})
+ >>> df
+ Animal Number_legs
+ 0 cat 4.0
+ 1 penguin 2.0
+ 2 dog 4.0
+ 3 spider 8.0
+ 4 snake NaN
+
+ The following example shows how the method behaves with the above
+ parameters:
+
+ * default_rank: this is the default behaviour obtained without using
+ any parameter.
+ * max_rank: setting ``method = 'max'`` the records that have the
+ same values are ranked using the highest rank (e.g.: since 'cat'
+ and 'dog' are both in the 2nd and 3rd position, rank 3 is assigned.)
+ * NA_bottom: choosing ``na_option = 'bottom'``, if there are records
+ with NaN values they are placed at the bottom of the ranking.
+ * pct_rank: when setting ``pct = True``, the ranking is expressed as
+ percentile rank.
+
+ >>> df['default_rank'] = df['Number_legs'].rank()
+ >>> df['max_rank'] = df['Number_legs'].rank(method='max')
+ >>> df['NA_bottom'] = df['Number_legs'].rank(na_option='bottom')
+ >>> df['pct_rank'] = df['Number_legs'].rank(pct=True)
+ >>> df
+ Animal Number_legs default_rank max_rank NA_bottom pct_rank
+ 0 cat 4.0 2.5 3.0 2.5 0.625
+ 1 penguin 2.0 1.0 1.0 1.0 0.250
+ 2 dog 4.0 2.5 3.0 2.5 0.625
+ 3 spider 8.0 4.0 4.0 4.0 1.000
+ 4 snake NaN NaN NaN 5.0 NaN
"""
axis = self._get_axis_number(axis)
| - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
I have made the changes requested in the pull request #23263
This is the output of the docstring validation:
```
3 Errors found:
Parameter "method" description should finish with "."
Parameter "na_option" description should finish with "."
The first line of the Returns section should contain only the type, unless multiple values are being returned
```
In the previous pull request I have been told that I could ignore these 3 errors.
Please let me know if I can further improve the docstring.
Thanks a lot | https://api.github.com/repos/pandas-dev/pandas/pulls/25328 | 2019-02-15T00:51:58Z | 2019-05-06T18:56:50Z | 2019-05-06T18:56:50Z | 2019-05-06T18:57:01Z |
#14873: test for groupby.agg coercing booleans | diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py
index 9de8a08809009..0c2e74c0b735f 100644
--- a/pandas/tests/groupby/aggregate/test_aggregate.py
+++ b/pandas/tests/groupby/aggregate/test_aggregate.py
@@ -286,3 +286,20 @@ def test_multi_function_flexible_mix(df):
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
result = grouped.aggregate(d)
tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_agg_coercing_bools():
+ # issue 14873
+ dat = pd.DataFrame(
+ {'a': [1, 1, 2, 2], 'b': [0, 1, 2, 3], 'c': [None, None, 1, 1]})
+ gp = dat.groupby('a')
+
+ index = Index([1, 2], name='a')
+
+ result = gp['b'].aggregate(lambda x: (x != 0).all())
+ expected = Series([False, True], index=index, name='b')
+ tm.assert_series_equal(result, expected)
+
+ result = gp['c'].aggregate(lambda x: x.isnull().all())
+ expected = Series([True, False], index=index, name='c')
+ tm.assert_series_equal(result, expected)
| - [x] closes #14873
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
The referenced issue seems to be solved in the current master. So added a test for the edge case. | https://api.github.com/repos/pandas-dev/pandas/pulls/25327 | 2019-02-14T20:17:59Z | 2019-02-19T14:11:42Z | 2019-02-19T14:11:42Z | 2019-02-19T14:35:41Z |
Backport PR #25323 on branch 0.24.x (Skipped broken Py2 / Windows test) | diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py
index e22b9a0ef25e3..92b4e5a99041a 100644
--- a/pandas/tests/test_downstream.py
+++ b/pandas/tests/test_downstream.py
@@ -9,7 +9,7 @@
import numpy as np # noqa
import pytest
-from pandas.compat import PY36
+from pandas.compat import PY2, PY36, is_platform_windows
from pandas import DataFrame
from pandas.util import testing as tm
@@ -58,6 +58,8 @@ def test_xarray(df):
assert df.to_xarray() is not None
+@pytest.mark.skipif(is_platform_windows() and PY2,
+ reason="Broken on Windows / Py2")
def test_oo_optimizable():
# GH 21071
subprocess.check_call([sys.executable, "-OO", "-c", "import pandas"])
| Backport PR #25323: Skipped broken Py2 / Windows test | https://api.github.com/repos/pandas-dev/pandas/pulls/25325 | 2019-02-14T17:28:21Z | 2019-02-15T09:20:58Z | 2019-02-15T09:20:58Z | 2019-02-15T09:20:58Z |
Skipped broken Py2 / Windows test | diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py
index e22b9a0ef25e3..92b4e5a99041a 100644
--- a/pandas/tests/test_downstream.py
+++ b/pandas/tests/test_downstream.py
@@ -9,7 +9,7 @@
import numpy as np # noqa
import pytest
-from pandas.compat import PY36
+from pandas.compat import PY2, PY36, is_platform_windows
from pandas import DataFrame
from pandas.util import testing as tm
@@ -58,6 +58,8 @@ def test_xarray(df):
assert df.to_xarray() is not None
+@pytest.mark.skipif(is_platform_windows() and PY2,
+ reason="Broken on Windows / Py2")
def test_oo_optimizable():
# GH 21071
subprocess.check_call([sys.executable, "-OO", "-c", "import pandas"])
| quick workaround for #25293
@jreback | https://api.github.com/repos/pandas-dev/pandas/pulls/25323 | 2019-02-14T16:51:27Z | 2019-02-14T17:27:28Z | 2019-02-14T17:27:28Z | 2019-02-14T17:29:33Z |
#9236: test for the DataFrame.groupby with MultiIndex having pd.NaT | diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 1ae8efd2f6867..12a5d494648fc 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -1698,3 +1698,19 @@ def test_groupby_agg_ohlc_non_first():
result = df.groupby(pd.Grouper(freq='D')).agg(['sum', 'ohlc'])
tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_multiindex_nat():
+ # GH 9236
+ values = [
+ (pd.NaT, 'a'),
+ (datetime(2012, 1, 2), 'a'),
+ (datetime(2012, 1, 2), 'b'),
+ (datetime(2012, 1, 3), 'a')
+ ]
+ mi = pd.MultiIndex.from_tuples(values, names=['date', None])
+ ser = pd.Series([3, 2, 2.5, 4], index=mi)
+
+ result = ser.groupby(level=1).mean()
+ expected = pd.Series([3., 2.5], index=["a", "b"])
+ assert_series_equal(result, expected)
| - [x] closes #9236
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
The referenced issue seems to be solved in the current master. So added a test for the edge case. | https://api.github.com/repos/pandas-dev/pandas/pulls/25310 | 2019-02-13T22:10:35Z | 2019-02-19T13:32:42Z | 2019-02-19T13:32:42Z | 2019-02-19T18:55:20Z |
Rt05 documentation error fix issue 25108 | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index eacab199cc0be..ac6aade106ce6 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -241,8 +241,8 @@ fi
### DOCSTRINGS ###
if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then
- MSG='Validate docstrings (GL06, GL07, GL09, SS04, PR03, PR05, PR10, EX04, RT04, SS05, SA05)' ; echo $MSG
- $BASE_DIR/scripts/validate_docstrings.py --format=azure --errors=GL06,GL07,GL09,SS04,PR03,PR04,PR05,EX04,RT04,SS05,SA05
+ MSG='Validate docstrings (GL06, GL07, GL09, SS04, PR03, PR05, PR10, EX04, RT04, RT05, SS05, SA05)' ; echo $MSG
+ $BASE_DIR/scripts/validate_docstrings.py --format=azure --errors=GL06,GL07,GL09,SS04,PR03,PR04,PR05,EX04,RT04,RT05,SS05,SA05
RET=$(($RET + $?)) ; echo $MSG "DONE"
fi
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 77681f6ac3f93..c5c8f47ad6dba 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -291,7 +291,7 @@ def unique(values):
unique values.
If the input is an Index, the return is an Index
If the input is a Categorical dtype, the return is a Categorical
- If the input is a Series/ndarray, the return will be an ndarray
+ If the input is a Series/ndarray, the return will be an ndarray.
See Also
--------
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index ab58f86e0a6bc..d7d0882bbcc94 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -1292,7 +1292,7 @@ def __array__(self, dtype=None):
values : numpy array
A numpy array of either the specified dtype or,
if dtype==None (default), the same dtype as
- categorical.categories.dtype
+ categorical.categories.dtype.
"""
ret = take_1d(self.categories.values, self._codes)
if dtype and not is_dtype_equal(dtype, self.categories.dtype):
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 73e799f9e0a36..84536ac72a455 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -154,7 +154,7 @@ def strftime(self, date_format):
Returns
-------
Index
- Index of formatted strings
+ Index of formatted strings.
See Also
--------
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 7ac18b79daba1..cf97c94f6d129 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2743,7 +2743,7 @@ def set_value(self, index, col, value, takeable=False):
-------
DataFrame
If label pair is contained, will be reference to calling DataFrame,
- otherwise a new object
+ otherwise a new object.
"""
warnings.warn("set_value is deprecated and will be removed "
"in a future release. Please use "
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 1a404630b660e..e2308836d982a 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -4953,7 +4953,7 @@ def pipe(self, func, *args, **kwargs):
If DataFrame.agg is called with a single function, returns a Series
If DataFrame.agg is called with several functions, returns a DataFrame
If Series.agg is called with single function, returns a scalar
- If Series.agg is called with several functions, returns a Series
+ If Series.agg is called with several functions, returns a Series.
%(see_also)s
@@ -5349,7 +5349,7 @@ def get_values(self):
Returns
-------
numpy.ndarray
- Numpy representation of DataFrame
+ Numpy representation of DataFrame.
See Also
--------
@@ -5428,7 +5428,7 @@ def get_ftype_counts(self):
-------
dtype : Series
Series with the count of columns with each type and
- sparsity (dense/sparse)
+ sparsity (dense/sparse).
See Also
--------
@@ -6657,7 +6657,7 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None,
-------
Series or DataFrame
Returns the same object type as the caller, interpolated at
- some or all ``NaN`` values
+ some or all ``NaN`` values.
See Also
--------
@@ -6877,11 +6877,11 @@ def asof(self, where, subset=None):
-------
scalar, Series, or DataFrame
- Scalar : when `self` is a Series and `where` is a scalar
+ Scalar : when `self` is a Series and `where` is a scalar.
Series: when `self` is a Series and `where` is an array-like,
- or when `self` is a DataFrame and `where` is a scalar
+ or when `self` is a DataFrame and `where` is a scalar.
DataFrame : when `self` is a DataFrame and `where` is an
- array-like
+ array-like.
See Also
--------
@@ -7235,7 +7235,7 @@ def clip(self, lower=None, upper=None, axis=None, inplace=False,
-------
Series or DataFrame
Same type as calling object with the values outside the
- clip boundaries replaced
+ clip boundaries replaced.
Examples
--------
@@ -8386,7 +8386,7 @@ def ranker(data):
Returns
-------
(left, right) : (%(klass)s, type of other)
- Aligned objects
+ Aligned objects.
""")
@Appender(_shared_docs['align'] % _shared_doc_kwargs)
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index cf813f4c3030b..f2c8ac6e9b413 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -1828,7 +1828,7 @@ def isna(self):
Returns
-------
numpy.ndarray
- A boolean array of whether my values are NA
+ A boolean array of whether my values are NA.
See Also
--------
@@ -3098,9 +3098,9 @@ def reindex(self, target, method=None, level=None, limit=None,
Returns
-------
new_index : pd.Index
- Resulting index
+ Resulting index.
indexer : np.ndarray or None
- Indices of output values in original index
+ Indices of output values in original index.
"""
# GH6552: preserve names when reindexing to non-named target
@@ -4259,7 +4259,7 @@ def shift(self, periods=1, freq=None):
Returns
-------
pandas.Index
- Shifted index
+ Shifted index.
See Also
--------
@@ -4422,7 +4422,7 @@ def set_value(self, arr, key, value):
in the target are marked by -1.
missing : ndarray of int
An indexer into the target of the values not found.
- These correspond to the -1 in the indexer array
+ These correspond to the -1 in the indexer array.
"""
@Appender(_index_shared_docs['get_indexer_non_unique'] % _index_doc_kwargs)
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index e2237afbcac0f..efb77b5d155a1 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -1956,7 +1956,7 @@ def swaplevel(self, i=-2, j=-1):
Returns
-------
MultiIndex
- A new MultiIndex
+ A new MultiIndex.
.. versionchanged:: 0.18.1
@@ -2053,9 +2053,9 @@ def sortlevel(self, level=0, ascending=True, sort_remaining=True):
Returns
-------
sorted_index : pd.MultiIndex
- Resulting index
+ Resulting index.
indexer : np.ndarray
- Indices of output values in original index
+ Indices of output values in original index.
"""
from pandas.core.sorting import indexer_from_factorized
diff --git a/pandas/core/panel.py b/pandas/core/panel.py
index dda5533f1ea7b..1555542079d80 100644
--- a/pandas/core/panel.py
+++ b/pandas/core/panel.py
@@ -540,7 +540,7 @@ def set_value(self, *args, **kwargs):
-------
panel : Panel
If label combo is contained, will be reference to calling Panel,
- otherwise a new object
+ otherwise a new object.
"""
warnings.warn("set_value is deprecated and will be removed "
"in a future release. Please use "
@@ -803,7 +803,7 @@ def major_xs(self, key):
Returns
-------
y : DataFrame
- Index -> minor axis, columns -> items
+ Index -> minor axis, columns -> items.
Notes
-----
@@ -827,7 +827,7 @@ def minor_xs(self, key):
Returns
-------
y : DataFrame
- Index -> major axis, columns -> items
+ Index -> major axis, columns -> items.
Notes
-----
diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py
index 312a108ad3380..0fa80de812c5f 100644
--- a/pandas/core/reshape/melt.py
+++ b/pandas/core/reshape/melt.py
@@ -230,7 +230,7 @@ def wide_to_long(df, stubnames, i, j, sep="", suffix=r'\d+'):
-------
DataFrame
A DataFrame that contains each stub name as a variable, with new index
- (i, j)
+ (i, j).
Notes
-----
diff --git a/pandas/core/series.py b/pandas/core/series.py
index b2011fdcdee98..31c6247436418 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1215,7 +1215,7 @@ def set_value(self, label, value, takeable=False):
-------
Series
If label is contained, will be reference to calling Series,
- otherwise a new object
+ otherwise a new object.
"""
warnings.warn("set_value is deprecated and will be removed "
"in a future release. Please use "
@@ -1648,10 +1648,19 @@ def unique(self):
Returns
-------
ndarray or ExtensionArray
- The unique values returned as a NumPy array. In case of an
- extension-array backed Series, a new
- :class:`~api.extensions.ExtensionArray` of that type with just
- the unique values is returned. This includes
+ The unique values returned as a NumPy array. See Notes.
+
+ See Also
+ --------
+ unique : Top-level unique method for any 1-d array-like object.
+ Index.unique : Return Index with unique values from an Index object.
+
+ Notes
+ -----
+ Returns the unique values as a NumPy array. In case of an
+ extension-array backed Series, a new
+ :class:`~api.extensions.ExtensionArray` of that type with just
+ the unique values is returned. This includes
* Categorical
* Period
@@ -1660,11 +1669,6 @@ def unique(self):
* Sparse
* IntegerNA
- See Also
- --------
- unique : Top-level unique method for any 1-d array-like object.
- Index.unique : Return Index with unique values from an Index object.
-
Examples
--------
>>> pd.Series([2, 1, 3, 3], name='A').unique()
diff --git a/pandas/core/tools/numeric.py b/pandas/core/tools/numeric.py
index b8a7eb5b0c570..08ce649d8602c 100644
--- a/pandas/core/tools/numeric.py
+++ b/pandas/core/tools/numeric.py
@@ -59,7 +59,7 @@ def to_numeric(arg, errors='raise', downcast=None):
Returns
-------
ret : numeric if parsing succeeded.
- Return type depends on input. Series if Series, otherwise ndarray
+ Return type depends on input. Series if Series, otherwise ndarray.
See Also
--------
diff --git a/pandas/core/window.py b/pandas/core/window.py
index fb37d790f950c..9e29fdb94c1e0 100644
--- a/pandas/core/window.py
+++ b/pandas/core/window.py
@@ -1271,7 +1271,7 @@ def skew(self, **kwargs):
-------
Series or DataFrame
Returned object type is determined by the caller of the %(name)s
- calculation
+ calculation.
See Also
--------
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py
index cd6e3505d71db..c8b5dc6b9b7c0 100644
--- a/pandas/io/formats/style.py
+++ b/pandas/io/formats/style.py
@@ -435,7 +435,7 @@ def render(self, **kwargs):
Returns
-------
rendered : str
- The rendered HTML
+ The rendered HTML.
Notes
-----
diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py
index a525b9cff1182..2c672f235f1e1 100644
--- a/pandas/plotting/_core.py
+++ b/pandas/plotting/_core.py
@@ -2050,9 +2050,17 @@ def plot_series(data, kind='line', ax=None, # Series unique
Returns
-------
- result :
+ result
+ See Notes.
- The return type depends on the `return_type` parameter:
+ See Also
+ --------
+ Series.plot.hist: Make a histogram.
+ matplotlib.pyplot.boxplot : Matplotlib equivalent plot.
+
+ Notes
+ -----
+ The return type depends on the `return_type` parameter:
* 'axes' : object of class matplotlib.axes.Axes
* 'dict' : dict of matplotlib.lines.Line2D objects
@@ -2063,13 +2071,6 @@ def plot_series(data, kind='line', ax=None, # Series unique
* :class:`~pandas.Series`
* :class:`~numpy.array` (for ``return_type = None``)
- See Also
- --------
- Series.plot.hist: Make a histogram.
- matplotlib.pyplot.boxplot : Matplotlib equivalent plot.
-
- Notes
- -----
Use ``return_type='dict'`` when you want to tweak the appearance
of the lines after plotting. In this case a dict containing the Lines
making up the boxes, caps, fliers, medians, and whiskers is returned.
@@ -3332,7 +3333,7 @@ def area(self, x=None, y=None, **kwds):
Returns
-------
matplotlib.axes.Axes or numpy.ndarray
- Area plot, or array of area plots if subplots is True
+ Area plot, or array of area plots if subplots is True.
See Also
--------
diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py
index 62a33245f99ef..21592a5b4a0a1 100644
--- a/pandas/plotting/_misc.py
+++ b/pandas/plotting/_misc.py
@@ -390,7 +390,7 @@ def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds):
Returns
-------
fig : matplotlib.figure.Figure
- Matplotlib figure
+ Matplotlib figure.
See Also
--------
diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py
index f591b24f5b648..4802447cbc99d 100644
--- a/pandas/tseries/frequencies.py
+++ b/pandas/tseries/frequencies.py
@@ -68,7 +68,7 @@ def to_offset(freq):
Returns
-------
delta : DateOffset
- None if freq is None
+ None if freq is None.
Raises
------
| - [x] closes #25108
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] updates CI script to check for future testing automation | https://api.github.com/repos/pandas-dev/pandas/pulls/25309 | 2019-02-13T20:41:40Z | 2019-02-14T19:18:09Z | 2019-02-14T19:18:05Z | 2019-02-14T20:37:45Z |
BUG: Groupby.agg with reduction function with tz aware data | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index a6f7395f5177e..f847c1d827186 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -229,8 +229,8 @@ Groupby/Resample/Rolling
- Bug in :meth:`pandas.core.resample.Resampler.agg` with a timezone aware index where ``OverflowError`` would raise when passing a list of functions (:issue:`22660`)
- Bug in :meth:`pandas.core.groupby.DataFrameGroupBy.nunique` in which the names of column levels were lost (:issue:`23222`)
--
--
+- Bug in :func:`pandas.core.groupby.GroupBy.agg` when applying a aggregation function to timezone aware data (:issue:`23683`)
+- Bug in :func:`pandas.core.groupby.GroupBy.first` and :func:`pandas.core.groupby.GroupBy.last` where timezone information would be dropped (:issue:`21603`)
Reshaping
diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx
index 507567cf480d7..517d59c399179 100644
--- a/pandas/_libs/reduction.pyx
+++ b/pandas/_libs/reduction.pyx
@@ -342,7 +342,9 @@ cdef class SeriesGrouper:
index = None
else:
values = dummy.values
- if dummy.dtype != self.arr.dtype:
+ # GH 23683: datetimetz types are equivalent to datetime types here
+ if (dummy.dtype != self.arr.dtype
+ and values.dtype != self.arr.dtype):
raise ValueError('Dummy array must be same dtype')
if not values.flags.contiguous:
values = values.copy()
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index c364f069bf53d..926da40deaff2 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -26,7 +26,8 @@ class providing the base-class of operations.
from pandas.core.dtypes.cast import maybe_downcast_to_dtype
from pandas.core.dtypes.common import (
- ensure_float, is_extension_array_dtype, is_numeric_dtype, is_scalar)
+ ensure_float, is_datetime64tz_dtype, is_extension_array_dtype,
+ is_numeric_dtype, is_scalar)
from pandas.core.dtypes.missing import isna, notna
from pandas.api.types import (
@@ -766,7 +767,21 @@ def _try_cast(self, result, obj, numeric_only=False):
dtype = obj.dtype
if not is_scalar(result):
- if is_extension_array_dtype(dtype):
+ if is_datetime64tz_dtype(dtype):
+ # GH 23683
+ # Prior results _may_ have been generated in UTC.
+ # Ensure we localize to UTC first before converting
+ # to the target timezone
+ try:
+ result = obj._values._from_sequence(
+ result, dtype='datetime64[ns, UTC]'
+ )
+ result = result.astype(dtype)
+ except TypeError:
+ # _try_cast was called at a point where the result
+ # was already tz-aware
+ pass
+ elif is_extension_array_dtype(dtype):
# The function can return something of any type, so check
# if the type is compatible with the calling EA.
try:
diff --git a/pandas/tests/groupby/aggregate/test_other.py b/pandas/tests/groupby/aggregate/test_other.py
index b5214b11bddcc..cacfdb7694de1 100644
--- a/pandas/tests/groupby/aggregate/test_other.py
+++ b/pandas/tests/groupby/aggregate/test_other.py
@@ -512,3 +512,18 @@ def test_agg_list_like_func():
expected = pd.DataFrame({'A': [str(x) for x in range(3)],
'B': [[str(x)] for x in range(3)]})
tm.assert_frame_equal(result, expected)
+
+
+def test_agg_lambda_with_timezone():
+ # GH 23683
+ df = pd.DataFrame({
+ 'tag': [1, 1],
+ 'date': [
+ pd.Timestamp('2018-01-01', tz='UTC'),
+ pd.Timestamp('2018-01-02', tz='UTC')]
+ })
+ result = df.groupby('tag').agg({'date': lambda e: e.head(1)})
+ expected = pd.DataFrame([pd.Timestamp('2018-01-01', tz='UTC')],
+ index=pd.Index([1], name='tag'),
+ columns=['date'])
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/groupby/test_nth.py b/pandas/tests/groupby/test_nth.py
index 255d9a8acf2d0..7a3d189d3020e 100644
--- a/pandas/tests/groupby/test_nth.py
+++ b/pandas/tests/groupby/test_nth.py
@@ -278,6 +278,26 @@ def test_first_last_tz(data, expected_first, expected_last):
assert_frame_equal(result, expected[['id', 'time']])
+@pytest.mark.parametrize('method, ts, alpha', [
+ ['first', Timestamp('2013-01-01', tz='US/Eastern'), 'a'],
+ ['last', Timestamp('2013-01-02', tz='US/Eastern'), 'b']
+])
+def test_first_last_tz_multi_column(method, ts, alpha):
+ # GH 21603
+ df = pd.DataFrame({'group': [1, 1, 2],
+ 'category_string': pd.Series(list('abc')).astype(
+ 'category'),
+ 'datetimetz': pd.date_range('20130101', periods=3,
+ tz='US/Eastern')})
+ result = getattr(df.groupby('group'), method)()
+ expepcted = pd.DataFrame({'category_string': [alpha, 'c'],
+ 'datetimetz': [ts,
+ Timestamp('2013-01-03',
+ tz='US/Eastern')]},
+ index=pd.Index([1, 2], name='group'))
+ assert_frame_equal(result, expepcted)
+
+
def test_nth_multi_index_as_expected():
# PR 9090, related to issue 8979
# test nth on MultiIndex
| - [x] closes #23683
- [x] closes #21603
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25308 | 2019-02-13T19:55:07Z | 2019-02-28T17:38:48Z | 2019-02-28T17:38:48Z | 2019-02-28T17:39:01Z |
DOC: fix misspellings | diff --git a/doc/source/user_guide/groupby.rst b/doc/source/user_guide/groupby.rst
index 2c2e5c5425216..e4dd82afcdf65 100644
--- a/doc/source/user_guide/groupby.rst
+++ b/doc/source/user_guide/groupby.rst
@@ -1317,7 +1317,7 @@ arbitrary function, for example:
df.groupby(['Store', 'Product']).pipe(mean)
where ``mean`` takes a GroupBy object and finds the mean of the Revenue and Quantity
-columns repectively for each Store-Product combination. The ``mean`` function can
+columns respectively for each Store-Product combination. The ``mean`` function can
be any function that takes in a GroupBy object; the ``.pipe`` will pass the GroupBy
object as a parameter into the function you specify.
diff --git a/doc/source/whatsnew/v0.10.0.rst b/doc/source/whatsnew/v0.10.0.rst
index bc2a4918bc27b..2d6550bb6888d 100644
--- a/doc/source/whatsnew/v0.10.0.rst
+++ b/doc/source/whatsnew/v0.10.0.rst
@@ -370,7 +370,7 @@ Updated PyTables Support
df1.get_dtype_counts()
- performance improvements on table writing
-- support for arbitrarly indexed dimensions
+- support for arbitrarily indexed dimensions
- ``SparseSeries`` now has a ``density`` property (:issue:`2384`)
- enable ``Series.str.strip/lstrip/rstrip`` methods to take an input argument
to strip arbitrary characters (:issue:`2411`)
diff --git a/doc/source/whatsnew/v0.16.1.rst b/doc/source/whatsnew/v0.16.1.rst
index 7621cb9c1e27c..cbcb23e356577 100644
--- a/doc/source/whatsnew/v0.16.1.rst
+++ b/doc/source/whatsnew/v0.16.1.rst
@@ -136,7 +136,7 @@ groupby operations on the index will preserve the index nature as well
reindexing operations, will return a resulting index based on the type of the passed
indexer, meaning that passing a list will return a plain-old-``Index``; indexing with
a ``Categorical`` will return a ``CategoricalIndex``, indexed according to the categories
-of the PASSED ``Categorical`` dtype. This allows one to arbitrarly index these even with
+of the PASSED ``Categorical`` dtype. This allows one to arbitrarily index these even with
values NOT in the categories, similarly to how you can reindex ANY pandas index.
.. code-block:: ipython
| Signed-off-by: Takuya Noguchi <takninnovationresearch@gmail.com> | https://api.github.com/repos/pandas-dev/pandas/pulls/25305 | 2019-02-13T14:37:24Z | 2019-02-15T04:07:55Z | 2019-02-15T04:07:55Z | 2019-02-15T04:07:59Z |
BUG: Fix passing of numeric_only argument for categorical reduce | diff --git a/doc/source/whatsnew/v0.24.2.rst b/doc/source/whatsnew/v0.24.2.rst
index f17c4974cd450..089da5f13c73f 100644
--- a/doc/source/whatsnew/v0.24.2.rst
+++ b/doc/source/whatsnew/v0.24.2.rst
@@ -25,6 +25,7 @@ Fixed Regressions
- Fixed regression in :meth:`DataFrame.apply` causing ``RecursionError`` when ``dict``-like classes were passed as argument. (:issue:`25196`)
- Fixed regression in :meth:`DataFrame.duplicated()`, where empty dataframe was not returning a boolean dtyped Series. (:issue:`25184`)
+- Fixed regression in :meth:`Series.min` and :meth:`Series.max` where ``numeric_only=True`` was ignored when the ``Series`` contained ```Categorical`` data (:issue:`25299`)
.. _whatsnew_0242.enhancements:
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index d7d0882bbcc94..6b977e34ae7f8 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -2172,7 +2172,7 @@ def _reverse_indexer(self):
return result
# reduction ops #
- def _reduce(self, name, axis=0, skipna=True, **kwargs):
+ def _reduce(self, name, axis=0, **kwargs):
func = getattr(self, name, None)
if func is None:
msg = 'Categorical cannot perform the operation {op}'
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 31c6247436418..a5dfe8d43c336 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -3678,8 +3678,12 @@ def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None,
if axis is not None:
self._get_axis_number(axis)
- # dispatch to ExtensionArray interface
- if isinstance(delegate, ExtensionArray):
+ if isinstance(delegate, Categorical):
+ # TODO deprecate numeric_only argument for Categorical and use
+ # skipna as well, see GH25303
+ return delegate._reduce(name, numeric_only=numeric_only, **kwds)
+ elif isinstance(delegate, ExtensionArray):
+ # dispatch to ExtensionArray interface
return delegate._reduce(name, skipna=skipna, **kwds)
elif is_datetime64_dtype(delegate):
# use DatetimeIndex implementation to handle skipna correctly
diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py
index 173f719edd465..8520855d14918 100644
--- a/pandas/tests/reductions/test_reductions.py
+++ b/pandas/tests/reductions/test_reductions.py
@@ -960,6 +960,27 @@ def test_min_max(self):
assert np.isnan(_min)
assert _max == 1
+ def test_min_max_numeric_only(self):
+ # TODO deprecate numeric_only argument for Categorical and use
+ # skipna as well, see GH25303
+ cat = Series(Categorical(
+ ["a", "b", np.nan, "a"], categories=['b', 'a'], ordered=True))
+
+ _min = cat.min()
+ _max = cat.max()
+ assert np.isnan(_min)
+ assert _max == "a"
+
+ _min = cat.min(numeric_only=True)
+ _max = cat.max(numeric_only=True)
+ assert _min == "b"
+ assert _max == "a"
+
+ _min = cat.min(numeric_only=False)
+ _max = cat.max(numeric_only=False)
+ assert np.isnan(_min)
+ assert _max == "a"
+
class TestSeriesMode(object):
# Note: the name TestSeriesMode indicates these tests
| See https://github.com/pandas-dev/pandas/issues/25303 and https://github.com/pandas-dev/pandas/issues/25299
- [x] closes https://github.com/pandas-dev/pandas/issues/25299
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25304 | 2019-02-13T14:10:56Z | 2019-02-16T18:49:51Z | 2019-02-16T18:49:51Z | 2019-02-16T18:49:58Z |
BUG: OverflowError in resample.agg with tz data | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 95362521f3b9f..286d267f024a1 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -172,7 +172,7 @@ Plotting
Groupby/Resample/Rolling
^^^^^^^^^^^^^^^^^^^^^^^^
--
+- Bug in :meth:`pandas.core.resample.Resampler.agg` with a timezone aware index where ``OverflowError`` would raise when passing a list of functions (:issue:`22660`)
-
-
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index df91c71cfe238..0e3dae61561c1 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -1010,7 +1010,7 @@ def get_loc(self, key, method=None, tolerance=None):
except (KeyError, ValueError, TypeError):
try:
return self._get_string_slice(key)
- except (TypeError, KeyError, ValueError):
+ except (TypeError, KeyError, ValueError, OverflowError):
pass
try:
diff --git a/pandas/tests/resample/test_resample_api.py b/pandas/tests/resample/test_resample_api.py
index 69acf4ba6bde8..97f1e07380ef9 100644
--- a/pandas/tests/resample/test_resample_api.py
+++ b/pandas/tests/resample/test_resample_api.py
@@ -549,3 +549,25 @@ def test_selection_api_validation():
exp.index.name = 'd'
assert_frame_equal(exp, df.resample('2D', level='d').sum())
+
+
+@pytest.mark.parametrize('col_name', ['t2', 't2x', 't2q', 'T_2M',
+ 't2p', 't2m', 't2m1', 'T2M'])
+def test_agg_with_datetime_index_list_agg_func(col_name):
+ # GH 22660
+ # The parametrized column names would get converted to dates by our
+ # date parser. Some would result in OutOfBoundsError (ValueError) while
+ # others would result in OverflowError when passed into Timestamp.
+ # We catch these errors and move on to the correct branch.
+ df = pd.DataFrame(list(range(200)),
+ index=pd.date_range(start='2017-01-01', freq='15min',
+ periods=200, tz='Europe/Berlin'),
+ columns=[col_name])
+ result = df.resample('1d').aggregate(['mean'])
+ expected = pd.DataFrame([47.5, 143.5, 195.5],
+ index=pd.date_range(start='2017-01-01', freq='D',
+ periods=3, tz='Europe/Berlin'),
+ columns=pd.MultiIndex(levels=[[col_name],
+ ['mean']],
+ codes=[[0], [0]]))
+ assert_frame_equal(result, expected)
| - [x] closes #22660
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25297 | 2019-02-13T07:42:48Z | 2019-02-16T17:22:41Z | 2019-02-16T17:22:41Z | 2019-02-16T22:34:09Z |
DOC/CLN: Fix various docstring errors | diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index d7d0882bbcc94..c2b024c9ae12e 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -214,7 +214,7 @@ def contains(cat, key, container):
class Categorical(ExtensionArray, PandasObject):
"""
- Represent a categorical variable in classic R / S-plus fashion
+ Represent a categorical variable in classic R / S-plus fashion.
`Categoricals` can only take on only a limited, and usually fixed, number
of possible values (`categories`). In contrast to statistical categorical
@@ -235,7 +235,7 @@ class Categorical(ExtensionArray, PandasObject):
The unique categories for this categorical. If not given, the
categories are assumed to be the unique values of `values` (sorted, if
possible, otherwise in the order in which they appear).
- ordered : boolean, (default False)
+ ordered : bool, default False
Whether or not this categorical is treated as a ordered categorical.
If True, the resulting categorical will be ordered.
An ordered categorical respects, when sorted, the order of its
@@ -253,7 +253,7 @@ class Categorical(ExtensionArray, PandasObject):
codes : ndarray
The codes (integer positions, which point to the categories) of this
categorical, read only.
- ordered : boolean
+ ordered : bool
Whether or not this Categorical is ordered.
dtype : CategoricalDtype
The instance of ``CategoricalDtype`` storing the ``categories``
@@ -297,7 +297,7 @@ class Categorical(ExtensionArray, PandasObject):
Ordered `Categoricals` can be sorted according to the custom order
of the categories and can have a min and max value.
- >>> c = pd.Categorical(['a','b','c','a','b','c'], ordered=True,
+ >>> c = pd.Categorical(['a', 'b', 'c', 'a', 'b', 'c'], ordered=True,
... categories=['c', 'b', 'a'])
>>> c
[a, b, c, a, b, c]
@@ -618,7 +618,7 @@ def from_codes(cls, codes, categories=None, ordered=None, dtype=None):
----------
codes : array-like, integers
An integer array, where each integer points to a category in
- categories or dtype.categories, or else is -1 for NaN
+ categories or dtype.categories, or else is -1 for NaN.
categories : index-like, optional
The categories for the categorical. Items need to be unique.
If the categories are not given here, then they must be provided
@@ -700,7 +700,7 @@ def _set_categories(self, categories, fastpath=False):
Parameters
----------
- fastpath : boolean (default: False)
+ fastpath : bool, default False
Don't perform validation of the categories for uniqueness or nulls
Examples
@@ -747,15 +747,15 @@ def _set_dtype(self, dtype):
def set_ordered(self, value, inplace=False):
"""
- Set the ordered attribute to the boolean value
+ Set the ordered attribute to the boolean value.
Parameters
----------
- value : boolean to set whether this categorical is ordered (True) or
- not (False)
- inplace : boolean (default: False)
- Whether or not to set the ordered attribute inplace or return a copy
- of this categorical with ordered set to the value
+ value : bool
+ Set whether this categorical is ordered (True) or not (False).
+ inplace : bool, default False
+ Whether or not to set the ordered attribute in-place or return
+ a copy of this categorical with ordered set to the value.
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
new_dtype = CategoricalDtype(self.categories, ordered=value)
@@ -770,9 +770,9 @@ def as_ordered(self, inplace=False):
Parameters
----------
- inplace : boolean (default: False)
- Whether or not to set the ordered attribute inplace or return a copy
- of this categorical with ordered set to True
+ inplace : bool, default False
+ Whether or not to set the ordered attribute in-place or return
+ a copy of this categorical with ordered set to True.
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
return self.set_ordered(True, inplace=inplace)
@@ -783,9 +783,9 @@ def as_unordered(self, inplace=False):
Parameters
----------
- inplace : boolean (default: False)
- Whether or not to set the ordered attribute inplace or return a copy
- of this categorical with ordered set to False
+ inplace : bool, default False
+ Whether or not to set the ordered attribute in-place or return
+ a copy of this categorical with ordered set to False.
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
return self.set_ordered(False, inplace=inplace)
@@ -815,19 +815,19 @@ def set_categories(self, new_categories, ordered=None, rename=False,
----------
new_categories : Index-like
The categories in new order.
- ordered : boolean, (default: False)
+ ordered : bool, default False
Whether or not the categorical is treated as a ordered categorical.
If not given, do not change the ordered information.
- rename : boolean (default: False)
+ rename : bool, default False
Whether or not the new_categories should be considered as a rename
of the old categories or as reordered categories.
- inplace : boolean (default: False)
- Whether or not to reorder the categories inplace or return a copy of
- this categorical with reordered categories.
+ inplace : bool, default False
+ Whether or not to reorder the categories in-place or return a copy
+ of this categorical with reordered categories.
Returns
-------
- cat : Categorical with reordered categories or None if inplace.
+ Categorical with reordered categories or None if inplace.
Raises
------
@@ -890,7 +890,7 @@ def rename_categories(self, new_categories, inplace=False):
Currently, Series are considered list like. In a future version
of pandas they'll be considered dict-like.
- inplace : boolean (default: False)
+ inplace : bool, default False
Whether or not to rename the categories inplace or return a copy of
this categorical with renamed categories.
@@ -967,10 +967,10 @@ def reorder_categories(self, new_categories, ordered=None, inplace=False):
----------
new_categories : Index-like
The categories in new order.
- ordered : boolean, optional
+ ordered : bool, optional
Whether or not the categorical is treated as a ordered categorical.
If not given, do not change the ordered information.
- inplace : boolean (default: False)
+ inplace : bool, default False
Whether or not to reorder the categories inplace or return a copy of
this categorical with reordered categories.
@@ -1010,7 +1010,7 @@ def add_categories(self, new_categories, inplace=False):
----------
new_categories : category or list-like of category
The new categories to be included.
- inplace : boolean (default: False)
+ inplace : bool, default False
Whether or not to add the categories inplace or return a copy of
this categorical with added categories.
@@ -1060,7 +1060,7 @@ def remove_categories(self, removals, inplace=False):
----------
removals : category or list of categories
The categories which should be removed.
- inplace : boolean (default: False)
+ inplace : bool, default False
Whether or not to remove the categories inplace or return a copy of
this categorical with removed categories.
@@ -1108,7 +1108,7 @@ def remove_unused_categories(self, inplace=False):
Parameters
----------
- inplace : boolean (default: False)
+ inplace : bool, default False
Whether or not to drop unused categories inplace or return a copy of
this categorical with unused categories dropped.
@@ -1460,7 +1460,7 @@ def value_counts(self, dropna=True):
Parameters
----------
- dropna : boolean, default True
+ dropna : bool, default True
Don't include counts of NaN.
Returns
@@ -1581,9 +1581,9 @@ def sort_values(self, inplace=False, ascending=True, na_position='last'):
Parameters
----------
- inplace : boolean, default False
+ inplace : bool, default False
Do operation in place.
- ascending : boolean, default True
+ ascending : bool, default True
Order ascending. Passing False orders descending. The
ordering parameter provides the method by which the
category values are organized.
@@ -2239,7 +2239,7 @@ def mode(self, dropna=True):
Parameters
----------
- dropna : boolean, default True
+ dropna : bool, default True
Don't consider counts of NaN/NaT.
.. versionadded:: 0.24.0
@@ -2332,7 +2332,7 @@ def equals(self, other):
Returns
-------
- are_equal : boolean
+ bool
"""
if self.is_dtype_equal(other):
if self.categories.equals(other.categories):
@@ -2356,7 +2356,7 @@ def is_dtype_equal(self, other):
Returns
-------
- are_equal : boolean
+ bool
"""
try:
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index 1b2a4da389dc4..cd8e8ed520ddc 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -799,14 +799,14 @@ def tz_convert(self, tz):
Parameters
----------
- tz : string, pytz.timezone, dateutil.tz.tzfile or None
+ tz : str, pytz.timezone, dateutil.tz.tzfile or None
Time zone for time. Corresponding timestamps would be converted
to this time zone of the Datetime Array/Index. A `tz` of None will
convert to UTC and remove the timezone information.
Returns
-------
- normalized : same type as self
+ Array or Index
Raises
------
@@ -842,7 +842,7 @@ def tz_convert(self, tz):
With the ``tz=None``, we can remove the timezone (after converting
to UTC if necessary):
- >>> dti = pd.date_range(start='2014-08-01 09:00',freq='H',
+ >>> dti = pd.date_range(start='2014-08-01 09:00', freq='H',
... periods=3, tz='Europe/Berlin')
>>> dti
@@ -882,7 +882,7 @@ def tz_localize(self, tz, ambiguous='raise', nonexistent='raise',
Parameters
----------
- tz : string, pytz.timezone, dateutil.tz.tzfile or None
+ tz : str, pytz.timezone, dateutil.tz.tzfile or None
Time zone to convert timestamps to. Passing ``None`` will
remove the time zone information preserving local time.
ambiguous : 'infer', 'NaT', bool array, default 'raise'
@@ -930,7 +930,7 @@ def tz_localize(self, tz, ambiguous='raise', nonexistent='raise',
Returns
-------
- result : same type as self
+ Same type as self
Array/Index converted to the specified time zone.
Raises
@@ -970,43 +970,39 @@ def tz_localize(self, tz, ambiguous='raise', nonexistent='raise',
Be careful with DST changes. When there is sequential data, pandas can
infer the DST time:
- >>> s = pd.to_datetime(pd.Series([
- ... '2018-10-28 01:30:00',
- ... '2018-10-28 02:00:00',
- ... '2018-10-28 02:30:00',
- ... '2018-10-28 02:00:00',
- ... '2018-10-28 02:30:00',
- ... '2018-10-28 03:00:00',
- ... '2018-10-28 03:30:00']))
+ >>> s = pd.to_datetime(pd.Series(['2018-10-28 01:30:00',
+ ... '2018-10-28 02:00:00',
+ ... '2018-10-28 02:30:00',
+ ... '2018-10-28 02:00:00',
+ ... '2018-10-28 02:30:00',
+ ... '2018-10-28 03:00:00',
+ ... '2018-10-28 03:30:00']))
>>> s.dt.tz_localize('CET', ambiguous='infer')
- 2018-10-28 01:30:00+02:00 0
- 2018-10-28 02:00:00+02:00 1
- 2018-10-28 02:30:00+02:00 2
- 2018-10-28 02:00:00+01:00 3
- 2018-10-28 02:30:00+01:00 4
- 2018-10-28 03:00:00+01:00 5
- 2018-10-28 03:30:00+01:00 6
- dtype: int64
+ 0 2018-10-28 01:30:00+02:00
+ 1 2018-10-28 02:00:00+02:00
+ 2 2018-10-28 02:30:00+02:00
+ 3 2018-10-28 02:00:00+01:00
+ 4 2018-10-28 02:30:00+01:00
+ 5 2018-10-28 03:00:00+01:00
+ 6 2018-10-28 03:30:00+01:00
+ dtype: datetime64[ns, CET]
In some cases, inferring the DST is impossible. In such cases, you can
pass an ndarray to the ambiguous parameter to set the DST explicitly
- >>> s = pd.to_datetime(pd.Series([
- ... '2018-10-28 01:20:00',
- ... '2018-10-28 02:36:00',
- ... '2018-10-28 03:46:00']))
+ >>> s = pd.to_datetime(pd.Series(['2018-10-28 01:20:00',
+ ... '2018-10-28 02:36:00',
+ ... '2018-10-28 03:46:00']))
>>> s.dt.tz_localize('CET', ambiguous=np.array([True, True, False]))
- 0 2018-10-28 01:20:00+02:00
- 1 2018-10-28 02:36:00+02:00
- 2 2018-10-28 03:46:00+01:00
- dtype: datetime64[ns, CET]
+ 0 2015-03-29 03:00:00+02:00
+ 1 2015-03-29 03:30:00+02:00
+ dtype: datetime64[ns, Europe/Warsaw]
If the DST transition causes nonexistent times, you can shift these
dates forward or backwards with a timedelta object or `'shift_forward'`
or `'shift_backwards'`.
- >>> s = pd.to_datetime(pd.Series([
- ... '2015-03-29 02:30:00',
- ... '2015-03-29 03:30:00']))
+ >>> s = pd.to_datetime(pd.Series(['2015-03-29 02:30:00',
+ ... '2015-03-29 03:30:00']))
>>> s.dt.tz_localize('Europe/Warsaw', nonexistent='shift_forward')
0 2015-03-29 03:00:00+02:00
1 2015-03-29 03:30:00+02:00
@@ -1129,7 +1125,7 @@ def to_period(self, freq=None):
Parameters
----------
- freq : string or Offset, optional
+ freq : str or Offset, optional
One of pandas' :ref:`offset strings <timeseries.offset_aliases>`
or an Offset object. Will be inferred by default.
@@ -1150,7 +1146,7 @@ def to_period(self, freq=None):
Examples
--------
- >>> df = pd.DataFrame({"y": [1,2,3]},
+ >>> df = pd.DataFrame({"y": [1, 2, 3]},
... index=pd.to_datetime(["2000-03-31 00:00:00",
... "2000-05-31 00:00:00",
... "2000-08-31 00:00:00"]))
diff --git a/pandas/core/base.py b/pandas/core/base.py
index 5a98e83c65884..7fdc64a8d9f85 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -794,7 +794,7 @@ def array(self):
Returns
-------
- array : ExtensionArray
+ ExtensionArray
An ExtensionArray of the values stored within. For extension
types, this is the actual array. For NumPy native types, this
is a thin (no copy) wrapper around :class:`numpy.ndarray`.
@@ -1022,7 +1022,7 @@ def max(self, axis=None, skipna=True):
def argmax(self, axis=None, skipna=True):
"""
- Return a ndarray of the maximum argument indexer.
+ Return an ndarray of the maximum argument indexer.
Parameters
----------
@@ -1087,6 +1087,10 @@ def argmin(self, axis=None, skipna=True):
Dummy argument for consistency with Series
skipna : bool, default True
+ Returns
+ -------
+ numpy.ndarray
+
See Also
--------
numpy.ndarray.argmin
@@ -1102,6 +1106,10 @@ def tolist(self):
(for str, int, float) or a pandas scalar
(for Timestamp/Timedelta/Interval/Period)
+ Returns
+ -------
+ list
+
See Also
--------
numpy.ndarray.tolist
@@ -1162,7 +1170,7 @@ def _map_values(self, mapper, na_action=None):
Returns
-------
- applied : Union[Index, MultiIndex], inferred
+ Union[Index, MultiIndex], inferred
The output of the mapping function applied to the index.
If the function returns a tuple with more than one element
a MultiIndex will be returned.
@@ -1246,7 +1254,7 @@ def value_counts(self, normalize=False, sort=True, ascending=False,
Returns
-------
- counts : Series
+ Series
See Also
--------
@@ -1363,7 +1371,7 @@ def is_unique(self):
Returns
-------
- is_unique : boolean
+ bool
"""
return self.nunique(dropna=False) == len(self)
@@ -1377,7 +1385,7 @@ def is_monotonic(self):
Returns
-------
- is_monotonic : boolean
+ bool
"""
from pandas import Index
return Index(self).is_monotonic
@@ -1394,7 +1402,7 @@ def is_monotonic_decreasing(self):
Returns
-------
- is_monotonic_decreasing : boolean
+ bool
"""
from pandas import Index
return Index(self).is_monotonic_decreasing
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index cf97c94f6d129..a239ff4b4d5db 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -6346,6 +6346,8 @@ def apply(self, func, axis=0, broadcast=None, raw=False, reduce=None,
Returns
-------
Series or DataFrame
+ Result of applying ``func`` along the given axis of the
+ DataFrame.
See Also
--------
@@ -6364,7 +6366,7 @@ def apply(self, func, axis=0, broadcast=None, raw=False, reduce=None,
Examples
--------
- >>> df = pd.DataFrame([[4, 9],] * 3, columns=['A', 'B'])
+ >>> df = pd.DataFrame([[4, 9]] * 3, columns=['A', 'B'])
>>> df
A B
0 4 9
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index b1fcbba7bd7ec..3a73861086bed 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -5959,17 +5959,18 @@ def fillna(self, value=None, method=None, axis=None, inplace=False,
value : scalar, dict, Series, or DataFrame
Value to use to fill holes (e.g. 0), alternately a
dict/Series/DataFrame of values specifying which value to use for
- each index (for a Series) or column (for a DataFrame). (values not
- in the dict/Series/DataFrame will not be filled). This value cannot
+ each index (for a Series) or column (for a DataFrame). Values not
+ in the dict/Series/DataFrame will not be filled. This value cannot
be a list.
method : {'backfill', 'bfill', 'pad', 'ffill', None}, default None
Method to use for filling holes in reindexed Series
pad / ffill: propagate last valid observation forward to next valid
- backfill / bfill: use NEXT valid observation to fill gap
+ backfill / bfill: use next valid observation to fill gap.
axis : %(axes_single_arg)s
- inplace : boolean, default False
- If True, fill in place. Note: this will modify any
- other views on this object, (e.g. a no-copy slice for a column in a
+ Axis along which to fill missing values.
+ inplace : bool, default False
+ If True, fill in-place. Note: this will modify any
+ other views on this object (e.g., a no-copy slice for a column in a
DataFrame).
limit : int, default None
If method is specified, this is the maximum number of consecutive
@@ -5979,18 +5980,20 @@ def fillna(self, value=None, method=None, axis=None, inplace=False,
maximum number of entries along the entire axis where NaNs will be
filled. Must be greater than 0 if not None.
downcast : dict, default is None
- a dict of item->dtype of what to downcast if possible,
+ A dict of item->dtype of what to downcast if possible,
or the string 'infer' which will try to downcast to an appropriate
- equal type (e.g. float64 to int64 if possible)
+ equal type (e.g. float64 to int64 if possible).
Returns
-------
- filled : %(klass)s
+ %(klass)s
+ Object with missing values filled.
See Also
--------
interpolate : Fill NaN values using interpolation.
- reindex, asfreq
+ reindex : Conform object to new index.
+ asfreq : Convert TimeSeries to specified frequency.
Examples
--------
@@ -5998,7 +6001,7 @@ def fillna(self, value=None, method=None, axis=None, inplace=False,
... [3, 4, np.nan, 1],
... [np.nan, np.nan, np.nan, 5],
... [np.nan, 3, np.nan, 4]],
- ... columns=list('ABCD'))
+ ... columns=list('ABCD'))
>>> df
A B C D
0 NaN 2.0 NaN 0
@@ -6752,7 +6755,7 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None,
Note how the first entry in column 'b' remains ``NaN``, because there
is no entry befofe it to use for interpolation.
- >>> df = pd.DataFrame([(0.0, np.nan, -1.0, 1.0),
+ >>> df = pd.DataFrame([(0.0, np.nan, -1.0, 1.0),
... (np.nan, 2.0, np.nan, np.nan),
... (2.0, 3.0, np.nan, 9.0),
... (np.nan, 4.0, -4.0, 16.0)],
@@ -7221,9 +7224,9 @@ def clip(self, lower=None, upper=None, axis=None, inplace=False,
upper : float or array_like, default None
Maximum threshold value. All values above this
threshold will be set to it.
- axis : int or string axis name, optional
+ axis : int or str axis name, optional
Align object with lower and upper along the given axis.
- inplace : boolean, default False
+ inplace : bool, default False
Whether to perform the operation in place on the data.
.. versionadded:: 0.21.0
@@ -7345,7 +7348,7 @@ def clip_upper(self, threshold, axis=None, inplace=False):
axis : {0 or 'index', 1 or 'columns'}, default 0
Align object with `threshold` along the given axis.
- inplace : boolean, default False
+ inplace : bool, default False
Whether to perform the operation in place on the data.
.. versionadded:: 0.21.0
@@ -7426,7 +7429,7 @@ def clip_lower(self, threshold, axis=None, inplace=False):
axis : {0 or 'index', 1 or 'columns'}, default 0
Align `self` with `threshold` along the given axis.
- inplace : boolean, default False
+ inplace : bool, default False
Whether to perform the operation in place on the data.
.. versionadded:: 0.21.0
@@ -7583,9 +7586,9 @@ def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,
Examples
--------
- >>> df = pd.DataFrame({'Animal' : ['Falcon', 'Falcon',
- ... 'Parrot', 'Parrot'],
- ... 'Max Speed' : [380., 370., 24., 26.]})
+ >>> df = pd.DataFrame({'Animal': ['Falcon', 'Falcon',
+ ... 'Parrot', 'Parrot'],
+ ... 'Max Speed': [380., 370., 24., 26.]})
>>> df
Animal Max Speed
0 Falcon 380.0
@@ -7606,8 +7609,8 @@ def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,
>>> arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'],
... ['Captive', 'Wild', 'Captive', 'Wild']]
>>> index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type'))
- >>> df = pd.DataFrame({'Max Speed' : [390., 350., 30., 20.]},
- ... index=index)
+ >>> df = pd.DataFrame({'Max Speed': [390., 350., 30., 20.]},
+ ... index=index)
>>> df
Max Speed
Animal Type
@@ -7740,14 +7743,14 @@ def at_time(self, time, asof=False, axis=None):
Parameters
----------
- time : datetime.time or string
+ time : datetime.time or str
axis : {0 or 'index', 1 or 'columns'}, default 0
.. versionadded:: 0.24.0
Returns
-------
- values_at_time : same type as caller
+ Series or DataFrame
Raises
------
@@ -7765,7 +7768,7 @@ def at_time(self, time, asof=False, axis=None):
Examples
--------
>>> i = pd.date_range('2018-04-09', periods=4, freq='12H')
- >>> ts = pd.DataFrame({'A': [1,2,3,4]}, index=i)
+ >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i)
>>> ts
A
2018-04-09 00:00:00 1
@@ -7800,17 +7803,17 @@ def between_time(self, start_time, end_time, include_start=True,
Parameters
----------
- start_time : datetime.time or string
- end_time : datetime.time or string
- include_start : boolean, default True
- include_end : boolean, default True
+ start_time : datetime.time or str
+ end_time : datetime.time or str
+ include_start : bool, default True
+ include_end : bool, default True
axis : {0 or 'index', 1 or 'columns'}, default 0
.. versionadded:: 0.24.0
Returns
-------
- values_between_time : same type as caller
+ Series or DataFrame
Raises
------
@@ -7828,7 +7831,7 @@ def between_time(self, start_time, end_time, include_start=True,
Examples
--------
>>> i = pd.date_range('2018-04-09', periods=4, freq='1D20min')
- >>> ts = pd.DataFrame({'A': [1,2,3,4]}, index=i)
+ >>> ts = pd.DataFrame({'A': [1, 2, 3, 4]}, index=i)
>>> ts
A
2018-04-09 00:00:00 1
diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py
index 53671e00e88b4..a6c945ac2e464 100644
--- a/pandas/core/reshape/concat.py
+++ b/pandas/core/reshape/concat.py
@@ -38,15 +38,15 @@ def concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,
If a dict is passed, the sorted keys will be used as the `keys`
argument, unless it is passed, in which case the values will be
selected (see below). Any None objects will be dropped silently unless
- they are all None in which case a ValueError will be raised
+ they are all None in which case a ValueError will be raised.
axis : {0/'index', 1/'columns'}, default 0
- The axis to concatenate along
+ The axis to concatenate along.
join : {'inner', 'outer'}, default 'outer'
- How to handle indexes on other axis(es)
+ How to handle indexes on other axis (or axes).
join_axes : list of Index objects
Specific indexes to use for the other n - 1 axes instead of performing
- inner/outer set logic
- ignore_index : boolean, default False
+ inner/outer set logic.
+ 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
concatenating objects where the concatenation axis does not have
@@ -54,16 +54,16 @@ def concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,
axes are still respected in the join.
keys : sequence, default None
If multiple levels passed, should contain tuples. Construct
- hierarchical index using the passed keys as the outermost level
+ hierarchical index using the passed keys as the outermost level.
levels : list of sequences, default None
Specific levels (unique values) to use for constructing a
- MultiIndex. Otherwise they will be inferred from the keys
+ MultiIndex. Otherwise they will be inferred from the keys.
names : list, default None
- Names for the levels in the resulting hierarchical index
- verify_integrity : boolean, default False
+ Names for the levels in the resulting hierarchical index.
+ verify_integrity : bool, default False
Check whether the new concatenated axis contains duplicates. This can
- be very expensive relative to the actual data concatenation
- sort : boolean, default None
+ be very expensive relative to the actual data concatenation.
+ sort : bool, default None
Sort non-concatenation axis if it is not already aligned when `join`
is 'outer'. The current default of sorting is deprecated and will
change to not-sorting in a future version of pandas.
@@ -76,12 +76,12 @@ def concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,
.. versionadded:: 0.23.0
- copy : boolean, default True
- If False, do not copy data unnecessarily
+ copy : bool, default True
+ If False, do not copy data unnecessarily.
Returns
-------
- concatenated : object, type of objs
+ object, type of objs
When concatenating all ``Series`` along the index (axis=0), a
``Series`` is returned. When ``objs`` contains at least one
``DataFrame``, a ``DataFrame`` is returned. When concatenating along
@@ -89,10 +89,10 @@ def concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,
See Also
--------
- Series.append
- DataFrame.append
- DataFrame.join
- DataFrame.merge
+ Series.append : Concatenate Series.
+ DataFrame.append : Concatenate DataFrames.
+ DataFrame.join : Join DataFrames using indexes.
+ DataFrame.merge : Merge DataFrames by indexes or columns.
Notes
-----
@@ -128,7 +128,7 @@ def concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,
Add a hierarchical index at the outermost level of
the data with the ``keys`` option.
- >>> pd.concat([s1, s2], keys=['s1', 's2',])
+ >>> pd.concat([s1, s2], keys=['s1', 's2'])
s1 0 a
1 b
s2 0 c
diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py
index 54f11646fc753..8d7616c4b6b61 100644
--- a/pandas/core/reshape/pivot.py
+++ b/pandas/core/reshape/pivot.py
@@ -392,36 +392,36 @@ def crosstab(index, columns, values=None, rownames=None, colnames=None,
aggfunc=None, margins=False, margins_name='All', dropna=True,
normalize=False):
"""
- Compute a simple cross-tabulation of two (or more) factors. By default
+ Compute a simple cross tabulation of two (or more) factors. By default
computes a frequency table of the factors unless an array of values and an
- aggregation function are passed
+ aggregation function are passed.
Parameters
----------
index : array-like, Series, or list of arrays/Series
- Values to group by in the rows
+ Values to group by in the rows.
columns : array-like, Series, or list of arrays/Series
- Values to group by in the columns
+ Values to group by in the columns.
values : array-like, optional
Array of values to aggregate according to the factors.
Requires `aggfunc` be specified.
rownames : sequence, default None
- If passed, must match number of row arrays passed
+ If passed, must match number of row arrays passed.
colnames : sequence, default None
- If passed, must match number of column arrays passed
+ If passed, must match number of column arrays passed.
aggfunc : function, optional
- If specified, requires `values` be specified as well
- margins : boolean, default False
- Add row/column margins (subtotals)
- margins_name : string, default 'All'
- Name of the row / column that will contain the totals
+ If specified, requires `values` be specified as well.
+ margins : bool, default False
+ Add row/column margins (subtotals).
+ margins_name : str, default 'All'
+ Name of the row/column that will contain the totals
when margins is True.
.. versionadded:: 0.21.0
- dropna : boolean, default True
- Do not include columns whose entries are all NaN
- normalize : boolean, {'all', 'index', 'columns'}, or {0,1}, default False
+ dropna : bool, default True
+ Do not include columns whose entries are all NaN.
+ normalize : bool, {'all', 'index', 'columns'}, or {0,1}, default False
Normalize by dividing all values by the sum of values.
- If passed 'all' or `True`, will normalize over all values.
@@ -433,7 +433,13 @@ def crosstab(index, columns, values=None, rownames=None, colnames=None,
Returns
-------
- crosstab : DataFrame
+ DataFrame
+ Cross tabulation of the data.
+
+ See Also
+ --------
+ DataFrame.pivot : Reshape data based on column values.
+ pivot_table : Create a pivot table as a DataFrame.
Notes
-----
@@ -455,32 +461,26 @@ def crosstab(index, columns, values=None, rownames=None, colnames=None,
... "one", "two", "two", "two", "one"], dtype=object)
>>> c = np.array(["dull", "dull", "shiny", "dull", "dull", "shiny",
... "shiny", "dull", "shiny", "shiny", "shiny"],
- ... dtype=object)
-
+ ... dtype=object)
>>> pd.crosstab(a, [b, c], rownames=['a'], colnames=['b', 'c'])
- ... # doctest: +NORMALIZE_WHITESPACE
b one two
c dull shiny dull shiny
a
bar 1 2 1 0
foo 2 2 1 2
+ Here 'c' and 'f' are not represented in the data and will not be
+ shown in the output because dropna is True by default. Set
+ dropna=False to preserve categories with no data.
+
>>> foo = pd.Categorical(['a', 'b'], categories=['a', 'b', 'c'])
>>> bar = pd.Categorical(['d', 'e'], categories=['d', 'e', 'f'])
- >>> crosstab(foo, bar) # 'c' and 'f' are not represented in the data,
- # and will not be shown in the output because
- # dropna is True by default. Set 'dropna=False'
- # to preserve categories with no data
- ... # doctest: +SKIP
+ >>> pd.crosstab(foo, bar)
col_0 d e
row_0
a 1 0
b 0 1
-
- >>> crosstab(foo, bar, dropna=False) # 'c' and 'f' are not represented
- # in the data, but they still will be counted
- # and shown in the output
- ... # doctest: +SKIP
+ >>> pd.crosstab(foo, bar, dropna=False)
col_0 d e f
row_0
a 1 0 0
diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py
index f436b3b92a359..6ba33301753d6 100644
--- a/pandas/core/reshape/reshape.py
+++ b/pandas/core/reshape/reshape.py
@@ -701,19 +701,20 @@ def _convert_level_number(level_num, columns):
def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False,
columns=None, sparse=False, drop_first=False, dtype=None):
"""
- Convert categorical variable into dummy/indicator variables
+ Convert categorical variable into dummy/indicator variables.
Parameters
----------
data : array-like, Series, or DataFrame
- prefix : string, list of strings, or dict of strings, default None
+ Data of which to get dummy indicators.
+ prefix : str, list of str, or dict of str, default None
String to append DataFrame column names.
Pass a list with length equal to the number of columns
when calling get_dummies on a DataFrame. Alternatively, `prefix`
can be a dictionary mapping column names to prefixes.
- prefix_sep : string, default '_'
+ prefix_sep : str, default '_'
If appending prefix, separator/delimiter to use. Or pass a
- list or dictionary as with `prefix.`
+ list or dictionary as with `prefix`.
dummy_na : bool, default False
Add a column to indicate NaNs, if False NaNs are ignored.
columns : list-like, default None
@@ -736,11 +737,12 @@ def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False,
Returns
-------
- dummies : DataFrame
+ DataFrame
+ Dummy-coded data.
See Also
--------
- Series.str.get_dummies
+ Series.str.get_dummies : Convert Series to dummy codes.
Examples
--------
diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py
index 2a654fec36a9f..f99fd9004bb31 100644
--- a/pandas/core/reshape/tile.py
+++ b/pandas/core/reshape/tile.py
@@ -163,7 +163,7 @@ def cut(x, bins, right=True, labels=None, retbins=False, precision=3,
Use `drop` optional when bins is not unique
>>> pd.cut(s, [0, 2, 4, 6, 10, 10], labels=False, retbins=True,
- ... right=False, duplicates='drop')
+ ... right=False, duplicates='drop')
... # doctest: +ELLIPSIS
(a 0.0
b 1.0
diff --git a/pandas/core/strings.py b/pandas/core/strings.py
index 183a91c952140..cc7a4db515c42 100644
--- a/pandas/core/strings.py
+++ b/pandas/core/strings.py
@@ -120,7 +120,7 @@ def str_count(arr, pat, flags=0):
Returns
-------
- counts : Series or Index
+ Series or Index
Same type as the calling object containing the integer counts.
See Also
@@ -283,7 +283,7 @@ def str_contains(arr, pat, case=True, flags=0, na=np.nan, regex=True):
return `True`. However, '.0' as a regex matches any character
followed by a 0.
- >>> s2 = pd.Series(['40','40.0','41','41.0','35'])
+ >>> s2 = pd.Series(['40', '40.0', '41', '41.0', '35'])
>>> s2.str.contains('.0', regex=True)
0 True
1 True
@@ -433,13 +433,13 @@ def str_replace(arr, pat, repl, n=-1, case=None, flags=0, regex=True):
Parameters
----------
- pat : string or compiled regex
+ pat : str or compiled regex
String can be a character sequence or regular expression.
.. versionadded:: 0.20.0
`pat` also accepts a compiled regex.
- repl : string or callable
+ repl : str or callable
Replacement string or a callable. The callable is passed the regex
match object and must return a replacement string to be used.
See :func:`re.sub`.
@@ -448,15 +448,15 @@ def str_replace(arr, pat, repl, n=-1, case=None, flags=0, regex=True):
`repl` also accepts a callable.
n : int, default -1 (all)
- Number of replacements to make from start
- case : boolean, default None
+ Number of replacements to make from start.
+ case : bool, default None
- If True, case sensitive (the default if `pat` is a string)
- Set to False for case insensitive
- Cannot be set if `pat` is a compiled regex
flags : int, default 0 (no flags)
- re module flags, e.g. re.IGNORECASE
- Cannot be set if `pat` is a compiled regex
- regex : boolean, default True
+ regex : bool, default True
- If True, assumes the passed-in pattern is a regular expression.
- If False, treats the pattern as a literal string
- Cannot be set to False if `pat` is a compiled regex or `repl` is
@@ -537,6 +537,7 @@ def str_replace(arr, pat, repl, n=-1, case=None, flags=0, regex=True):
Using a compiled regex with flags
+ >>> import re
>>> regex_pat = re.compile(r'FUZ', flags=re.IGNORECASE)
>>> pd.Series(['foo', 'fuz', np.nan]).str.replace(regex_pat, 'bar')
0 foo
@@ -604,6 +605,7 @@ def str_repeat(arr, repeats):
0 a
1 b
2 c
+ dtype: object
Single int repeats string in Series
@@ -611,6 +613,7 @@ def str_repeat(arr, repeats):
0 aa
1 bb
2 cc
+ dtype: object
Sequence of int repeats corresponding string in Series
@@ -618,6 +621,7 @@ def str_repeat(arr, repeats):
0 a
1 bb
2 ccc
+ dtype: object
"""
if is_scalar(repeats):
def rep(x):
@@ -646,13 +650,14 @@ def str_match(arr, pat, case=True, flags=0, na=np.nan):
Parameters
----------
- pat : string
- Character sequence or regular expression
- case : boolean, default True
- If True, case sensitive
+ pat : str
+ Character sequence or regular expression.
+ case : bool, default True
+ If True, case sensitive.
flags : int, default 0 (no flags)
- re module flags, e.g. re.IGNORECASE
- na : default NaN, fill value for missing values
+ re module flags, e.g. re.IGNORECASE.
+ na : default NaN
+ Fill value for missing values.
Returns
-------
@@ -768,7 +773,7 @@ def str_extract(arr, pat, flags=0, expand=True):
Parameters
----------
- pat : string
+ pat : str
Regular expression pattern with capturing groups.
flags : int, default 0 (no flags)
Flags from the ``re`` module, e.g. ``re.IGNORECASE``, that
@@ -966,21 +971,23 @@ def str_extractall(arr, pat, flags=0):
def str_get_dummies(arr, sep='|'):
"""
- Split each string in the Series by sep and return a frame of
- dummy/indicator variables.
+ Split each string in the Series by sep and return a DataFrame
+ of dummy/indicator variables.
Parameters
----------
- sep : string, default "|"
+ sep : str, default "|"
String to split on.
Returns
-------
- dummies : DataFrame
+ DataFrame
+ Dummy variables corresponding to values of the Series.
See Also
--------
- get_dummies
+ get_dummies : Convert categorical variable into dummy/indicator
+ variables.
Examples
--------
@@ -1089,11 +1096,11 @@ def str_findall(arr, pat, flags=0):
Parameters
----------
- pat : string
+ pat : str
Pattern or regular expression.
flags : int, default 0
- ``re`` module flags, e.g. `re.IGNORECASE` (default is 0, which means
- no flags).
+ Flags from ``re`` module, e.g. `re.IGNORECASE` (default is 0, which
+ means no flags).
Returns
-------
@@ -1182,17 +1189,18 @@ def str_find(arr, sub, start=0, end=None, side='left'):
Parameters
----------
sub : str
- Substring being searched
+ Substring being searched.
start : int
- Left edge index
+ Left edge index.
end : int
- Right edge index
+ Right edge index.
side : {'left', 'right'}, default 'left'
- Specifies a starting side, equivalent to ``find`` or ``rfind``
+ Specifies a starting side, equivalent to ``find`` or ``rfind``.
Returns
-------
- found : Series/Index of integer values
+ Series or Index
+ Indexes where substring is found.
"""
if not isinstance(sub, compat.string_types):
@@ -1430,7 +1438,7 @@ def str_slice_replace(arr, start=None, stop=None, repl=None):
Returns
-------
- replaced : Series or Index
+ Series or Index
Same type as the original object.
See Also
@@ -1513,7 +1521,7 @@ def str_strip(arr, to_strip=None, side='both'):
Returns
-------
- stripped : Series/Index of objects
+ Series or Index
"""
if side == 'both':
f = lambda x: x.strip(to_strip)
@@ -1537,30 +1545,30 @@ def str_wrap(arr, width, **kwargs):
Parameters
----------
width : int
- Maximum line-width
+ Maximum line width.
expand_tabs : bool, optional
- If true, tab characters will be expanded to spaces (default: True)
+ If True, tab characters will be expanded to spaces (default: True).
replace_whitespace : bool, optional
- If true, each whitespace character (as defined by string.whitespace)
+ If True, each whitespace character (as defined by string.whitespace)
remaining after tab expansion will be replaced by a single space
- (default: True)
+ (default: True).
drop_whitespace : bool, optional
- If true, whitespace that, after wrapping, happens to end up at the
- beginning or end of a line is dropped (default: True)
+ If True, whitespace that, after wrapping, happens to end up at the
+ beginning or end of a line is dropped (default: True).
break_long_words : bool, optional
- If true, then words longer than width will be broken in order to ensure
+ If True, then words longer than width will be broken in order to ensure
that no lines are longer than width. If it is false, long words will
- not be broken, and some lines may be longer than width. (default: True)
+ not be broken, and some lines may be longer than width (default: True).
break_on_hyphens : bool, optional
- If true, wrapping will occur preferably on whitespace and right after
+ If True, wrapping will occur preferably on whitespace and right after
hyphens in compound words, as it is customary in English. If false,
only whitespaces will be considered as potentially good places for line
breaks, but you need to set break_long_words to false if you want truly
- insecable words. (default: True)
+ insecable words (default: True).
Returns
-------
- wrapped : Series/Index of objects
+ Series or Index
Notes
-----
@@ -1581,6 +1589,7 @@ def str_wrap(arr, width, **kwargs):
>>> s.str.wrap(12)
0 line to be\nwrapped
1 another line\nto be\nwrapped
+ dtype: object
"""
kwargs['width'] = width
@@ -1613,7 +1622,7 @@ def str_translate(arr, table, deletechars=None):
Returns
-------
- translated : Series/Index of objects
+ Series or Index
"""
if deletechars is None:
f = lambda x: x.translate(table)
@@ -1641,15 +1650,16 @@ def str_get(arr, i):
Returns
-------
- items : Series/Index of objects
+ Series or Index
Examples
--------
>>> s = pd.Series(["String",
- (1, 2, 3),
- ["a", "b", "c"],
- 123, -456,
- {1:"Hello", "2":"World"}])
+ ... (1, 2, 3),
+ ... ["a", "b", "c"],
+ ... 123,
+ ... -456,
+ ... {1: "Hello", "2": "World"}])
>>> s
0 String
1 (1, 2, 3)
@@ -1674,7 +1684,7 @@ def str_get(arr, i):
2 c
3 NaN
4 NaN
- 5 NaN
+ 5 None
dtype: object
"""
def f(x):
@@ -1699,7 +1709,7 @@ def str_decode(arr, encoding, errors="strict"):
Returns
-------
- decoded : Series/Index of objects
+ Series or Index
"""
if encoding in _cpython_optimized_decoders:
# CPython optimized implementation
@@ -2091,7 +2101,7 @@ def cat(self, others=None, sep=None, na_rep=None, join=None):
Returns
-------
- concat : str or Series/Index of objects
+ str, Series or Index
If `others` is None, `str` is returned, otherwise a `Series/Index`
(same type as caller) of objects is returned.
| This PR fixes a variety of docstring errors found in different parts of the code base (mostly incorrect names for data types, missing punctuation, PEP8 in examples, etc.). | https://api.github.com/repos/pandas-dev/pandas/pulls/25295 | 2019-02-13T03:08:35Z | 2019-02-16T17:27:50Z | 2019-02-16T17:27:50Z | 2019-02-16T17:29:49Z |
BUG: fixed merging with empty frame containing an Int64 column (#25183) | diff --git a/doc/source/whatsnew/v0.24.2.rst b/doc/source/whatsnew/v0.24.2.rst
index 8e59c2300e7ca..df215cf021b4b 100644
--- a/doc/source/whatsnew/v0.24.2.rst
+++ b/doc/source/whatsnew/v0.24.2.rst
@@ -93,7 +93,7 @@ Bug Fixes
**Other**
- Bug in :meth:`Series.is_unique` where single occurrences of ``NaN`` were not considered unique (:issue:`25180`)
--
+- Bug in :func:`merge` when merging an empty ``DataFrame`` with an ``Int64`` column or a non-empty ``DataFrame`` with an ``Int64`` column that is all ``NaN`` (:issue:`25183`)
-
.. _whatsnew_0.242.contributors:
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py
index 640587b7f9f31..cb98274962656 100644
--- a/pandas/core/internals/concat.py
+++ b/pandas/core/internals/concat.py
@@ -190,6 +190,8 @@ def get_reindexed_values(self, empty_dtype, upcasted_na):
pass
elif getattr(self.block, 'is_sparse', False):
pass
+ elif getattr(self.block, 'is_extension', False):
+ pass
else:
missing_arr = np.empty(self.shape, dtype=empty_dtype)
missing_arr.fill(fill_value)
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index 25487ccc76e62..7a97368504fd6 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -39,6 +39,54 @@ def get_test_data(ngroups=NGROUPS, n=N):
return arr
+def get_series():
+ return [
+ pd.Series([1], dtype='int64'),
+ pd.Series([1], dtype='Int64'),
+ pd.Series([1.23]),
+ pd.Series(['foo']),
+ pd.Series([True]),
+ pd.Series([pd.Timestamp('2018-01-01')]),
+ pd.Series([pd.Timestamp('2018-01-01', tz='US/Eastern')]),
+ ]
+
+
+def get_series_na():
+ return [
+ pd.Series([np.nan], dtype='Int64'),
+ pd.Series([np.nan], dtype='float'),
+ pd.Series([np.nan], dtype='object'),
+ pd.Series([pd.NaT]),
+ ]
+
+
+@pytest.fixture(params=get_series(), ids=lambda x: x.dtype.name)
+def series_of_dtype(request):
+ """
+ A parametrized fixture returning a variety of Series of different
+ dtypes
+ """
+ return request.param
+
+
+@pytest.fixture(params=get_series(), ids=lambda x: x.dtype.name)
+def series_of_dtype2(request):
+ """
+ A duplicate of the series_of_dtype fixture, so that it can be used
+ twice by a single function
+ """
+ return request.param
+
+
+@pytest.fixture(params=get_series_na(), ids=lambda x: x.dtype.name)
+def series_of_dtype_all_na(request):
+ """
+ A parametrized fixture returning a variety of Series with all NA
+ values
+ """
+ return request.param
+
+
class TestMerge(object):
def setup_method(self, method):
@@ -428,6 +476,36 @@ def check2(exp, kwarg):
check1(exp_in, kwarg)
check2(exp_out, kwarg)
+ def test_merge_empty_frame(self, series_of_dtype, series_of_dtype2):
+ # GH 25183
+ df = pd.DataFrame({'key': series_of_dtype, 'value': series_of_dtype2},
+ columns=['key', 'value'])
+ df_empty = df[:0]
+ expected = pd.DataFrame({
+ 'value_x': pd.Series(dtype=df.dtypes['value']),
+ 'key': pd.Series(dtype=df.dtypes['key']),
+ 'value_y': pd.Series(dtype=df.dtypes['value']),
+ }, columns=['value_x', 'key', 'value_y'])
+ actual = df_empty.merge(df, on='key')
+ assert_frame_equal(actual, expected)
+
+ def test_merge_all_na_column(self, series_of_dtype,
+ series_of_dtype_all_na):
+ # GH 25183
+ df_left = pd.DataFrame(
+ {'key': series_of_dtype, 'value': series_of_dtype_all_na},
+ columns=['key', 'value'])
+ df_right = pd.DataFrame(
+ {'key': series_of_dtype, 'value': series_of_dtype_all_na},
+ columns=['key', 'value'])
+ expected = pd.DataFrame({
+ 'key': series_of_dtype,
+ 'value_x': series_of_dtype_all_na,
+ 'value_y': series_of_dtype_all_na,
+ }, columns=['key', 'value_x', 'value_y'])
+ actual = df_left.merge(df_right, on='key')
+ assert_frame_equal(actual, expected)
+
def test_merge_nosort(self):
# #2098, anything to do?
| - [x] closes #25183
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25289 | 2019-02-12T21:01:45Z | 2019-02-24T03:47:24Z | 2019-02-24T03:47:24Z | 2019-02-24T03:47:53Z |
DOC: Fix minor typo in docstring | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 85aa13526e77c..f8b48e6610ce5 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -5761,9 +5761,9 @@ def stack(self, level=-1, dropna=True):
Notes
-----
The function is named by analogy with a collection of books
- being re-organised from being side by side on a horizontal
+ being reorganized from being side by side on a horizontal
position (the columns of the dataframe) to being stacked
- vertically on top of of each other (in the index of the
+ vertically on top of each other (in the index of the
dataframe).
Examples
| fix for the docstring of `DataFrame.stack()` | https://api.github.com/repos/pandas-dev/pandas/pulls/25285 | 2019-02-12T15:47:27Z | 2019-02-14T01:49:50Z | 2019-02-14T01:49:50Z | 2019-02-14T01:50:05Z |
Removed Panel class from HDF ASVs | diff --git a/asv_bench/benchmarks/io/hdf.py b/asv_bench/benchmarks/io/hdf.py
index f08904ba70a5f..a5dc28eb9508c 100644
--- a/asv_bench/benchmarks/io/hdf.py
+++ b/asv_bench/benchmarks/io/hdf.py
@@ -1,7 +1,5 @@
-import warnings
-
import numpy as np
-from pandas import DataFrame, Panel, date_range, HDFStore, read_hdf
+from pandas import DataFrame, date_range, HDFStore, read_hdf
import pandas.util.testing as tm
from ..pandas_vb_common import BaseIO
@@ -99,31 +97,6 @@ def time_store_info(self):
self.store.info()
-class HDFStorePanel(BaseIO):
-
- def setup(self):
- self.fname = '__test__.h5'
- with warnings.catch_warnings(record=True):
- self.p = Panel(np.random.randn(20, 1000, 25),
- items=['Item%03d' % i for i in range(20)],
- major_axis=date_range('1/1/2000', periods=1000),
- minor_axis=['E%03d' % i for i in range(25)])
- self.store = HDFStore(self.fname)
- self.store.append('p1', self.p)
-
- def teardown(self):
- self.store.close()
- self.remove(self.fname)
-
- def time_read_store_table_panel(self):
- with warnings.catch_warnings(record=True):
- self.store.select('p1')
-
- def time_write_store_table_panel(self):
- with warnings.catch_warnings(record=True):
- self.store.append('p2', self.p)
-
-
class HDF(BaseIO):
params = ['table', 'fixed']
| This is a logical follow up to #25233 which should also help resolve the build failures in #24953 | https://api.github.com/repos/pandas-dev/pandas/pulls/25281 | 2019-02-12T05:47:56Z | 2019-02-13T13:48:28Z | 2019-02-13T13:48:28Z | 2019-02-28T07:23:11Z |
ENH: Support times with timezones in at_time | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 95362521f3b9f..74d25d420e1a1 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -20,7 +20,7 @@ Other Enhancements
^^^^^^^^^^^^^^^^^^
- :meth:`Timestamp.replace` now supports the ``fold`` argument to disambiguate DST transition times (:issue:`25017`)
--
+- :meth:`DataFrame.at_time` and :meth:`Series.at_time` now support :meth:`datetime.time` objects with timezones (:issue:`24043`)
-
.. _whatsnew_0250.api_breaking:
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index df91c71cfe238..5c591f3dd00ac 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -1302,20 +1302,19 @@ def indexer_at_time(self, time, asof=False):
--------
indexer_between_time, DataFrame.at_time
"""
- from dateutil.parser import parse
-
if asof:
raise NotImplementedError("'asof' argument is not supported")
if isinstance(time, compat.string_types):
+ from dateutil.parser import parse
time = parse(time).time()
if time.tzinfo:
- # TODO
- raise NotImplementedError("argument 'time' with timezone info is "
- "not supported")
-
- time_micros = self._get_time_micros()
+ if self.tz is None:
+ raise ValueError("Index must be timezone aware.")
+ time_micros = self.tz_convert(time.tzinfo)._get_time_micros()
+ else:
+ time_micros = self._get_time_micros()
micros = _time_to_micros(time)
return (micros == time_micros).nonzero()[0]
diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py
index bc37317f72802..31e81a9ca77c2 100644
--- a/pandas/tests/frame/test_timeseries.py
+++ b/pandas/tests/frame/test_timeseries.py
@@ -6,6 +6,7 @@
import numpy as np
import pytest
+import pytz
from pandas.compat import product
@@ -647,6 +648,28 @@ def test_at_time(self):
rs = ts.at_time('16:00')
assert len(rs) == 0
+ @pytest.mark.parametrize('hour', ['1:00', '1:00AM', time(1),
+ time(1, tzinfo=pytz.UTC)])
+ def test_at_time_errors(self, hour):
+ # GH 24043
+ dti = pd.date_range('2018', periods=3, freq='H')
+ df = pd.DataFrame(list(range(len(dti))), index=dti)
+ if getattr(hour, 'tzinfo', None) is None:
+ result = df.at_time(hour)
+ expected = df.iloc[1:2]
+ tm.assert_frame_equal(result, expected)
+ else:
+ with pytest.raises(ValueError, match="Index must be timezone"):
+ df.at_time(hour)
+
+ def test_at_time_tz(self):
+ # GH 24043
+ dti = pd.date_range('2018', periods=3, freq='H', tz='US/Pacific')
+ df = pd.DataFrame(list(range(len(dti))), index=dti)
+ result = df.at_time(time(4, tzinfo=pytz.timezone('US/Eastern')))
+ expected = df.iloc[1:2]
+ tm.assert_frame_equal(result, expected)
+
def test_at_time_raises(self):
# GH20725
df = pd.DataFrame([[1, 2, 3], [4, 5, 6]])
| - [x] closes #24043
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25280 | 2019-02-12T03:12:47Z | 2019-02-16T17:56:49Z | 2019-02-16T17:56:49Z | 2019-02-16T22:33:50Z |
"Backport PR #25260 on branch 0.24.x" | diff --git a/doc/source/whatsnew/v0.24.2.rst b/doc/source/whatsnew/v0.24.2.rst
index 5ae777ca68eba..f17c4974cd450 100644
--- a/doc/source/whatsnew/v0.24.2.rst
+++ b/doc/source/whatsnew/v0.24.2.rst
@@ -79,7 +79,7 @@ Bug Fixes
**Reshaping**
-
--
+- Bug in :func:`DataFrame.join` when joining on a timezone aware :class:`DatetimeIndex` (:issue:`23931`)
-
**Visualization**
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index e11847d2b8ce2..adfd69c21d715 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -862,7 +862,7 @@ def _get_merge_keys(self):
in zip(self.right.index.levels,
self.right.index.codes)]
else:
- right_keys = [self.right.index.values]
+ right_keys = [self.right.index._values]
elif _any(self.right_on):
for k in self.right_on:
if is_rkey(k):
diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py
index e21f9d0291afa..c2a214446bb51 100644
--- a/pandas/tests/reshape/merge/test_join.py
+++ b/pandas/tests/reshape/merge/test_join.py
@@ -773,6 +773,28 @@ def test_join_multi_to_multi(self, join_type):
with pytest.raises(ValueError, match=msg):
right.join(left, on=['abc', 'xy'], how=join_type)
+ def test_join_on_tz_aware_datetimeindex(self):
+ # GH 23931
+ df1 = pd.DataFrame(
+ {
+ 'date': pd.date_range(start='2018-01-01', periods=5,
+ tz='America/Chicago'),
+ 'vals': list('abcde')
+ }
+ )
+
+ df2 = pd.DataFrame(
+ {
+ 'date': pd.date_range(start='2018-01-03', periods=5,
+ tz='America/Chicago'),
+ 'vals_2': list('tuvwx')
+ }
+ )
+ result = df1.join(df2.set_index('date'), on='date')
+ expected = df1.copy()
+ expected['vals_2'] = pd.Series([np.nan] * len(expected), dtype=object)
+ assert_frame_equal(result, expected)
+
def _check_join(left, right, result, join_col, how='left',
lsuffix='_x', rsuffix='_y'):
| (cherry picked from commit a9a03a25d82ee285b6da48bfb20b9057d20bb9e7)
xref https://github.com/pandas-dev/pandas/pull/25260#issuecomment-462448610
| https://api.github.com/repos/pandas-dev/pandas/pulls/25279 | 2019-02-12T02:34:00Z | 2019-02-12T13:40:08Z | 2019-02-12T13:40:08Z | 2019-03-11T19:17:22Z |
TST/CLN: remove test_slice_ints_with_floats_raises | diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index c99007cef90d4..8415bab802239 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -1541,8 +1541,9 @@ def test_slice_locs(self, dtype):
assert index2.slice_locs(8, 2) == (2, 6)
assert index2.slice_locs(7, 3) == (2, 5)
- def test_slice_float_locs(self):
- index = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=float))
+ @pytest.mark.parametrize("dtype", [int, float])
+ def test_slice_float_locs(self, dtype):
+ index = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=dtype))
n = len(index)
assert index.slice_locs(5.0, 10.0) == (3, n)
assert index.slice_locs(4.5, 10.5) == (3, 8)
@@ -1551,24 +1552,6 @@ def test_slice_float_locs(self):
assert index2.slice_locs(8.5, 1.5) == (2, 6)
assert index2.slice_locs(10.5, -1) == (0, n)
- @pytest.mark.xfail(reason="Assertions were not correct - see GH#20915")
- def test_slice_ints_with_floats_raises(self):
- # int slicing with floats
- # GH 4892, these are all TypeErrors
- index = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=int))
- n = len(index)
-
- pytest.raises(TypeError,
- lambda: index.slice_locs(5.0, 10.0))
- pytest.raises(TypeError,
- lambda: index.slice_locs(4.5, 10.5))
-
- index2 = index[::-1]
- pytest.raises(TypeError,
- lambda: index2.slice_locs(8.5, 1.5), (2, 6))
- pytest.raises(TypeError,
- lambda: index2.slice_locs(10.5, -1), (0, n))
-
def test_slice_locs_dup(self):
index = Index(['a', 'a', 'b', 'c', 'd', 'd'])
assert index.slice_locs('a', 'd') == (0, 6)
| - [x] closes #20915
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [n/a ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25277 | 2019-02-11T21:34:41Z | 2019-02-13T13:04:32Z | 2019-02-13T13:04:32Z | 2019-02-20T14:08:35Z |
[CLN] Excel Module Cleanups | diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index ed5943e9a1698..8f7bf8e0466f9 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -590,9 +590,8 @@ def __new__(cls, path, engine=None, **kwargs):
if engine == 'auto':
engine = _get_default_writer(ext)
except KeyError:
- error = ValueError("No engine for filetype: '{ext}'"
- .format(ext=ext))
- raise error
+ raise ValueError("No engine for filetype: '{ext}'"
+ .format(ext=ext))
cls = get_writer(engine)
return object.__new__(cls)
diff --git a/pandas/io/excel/_util.py b/pandas/io/excel/_util.py
index 1aeaf70f0832e..49255d83d1cd3 100644
--- a/pandas/io/excel/_util.py
+++ b/pandas/io/excel/_util.py
@@ -5,32 +5,39 @@
from pandas.core.dtypes.common import is_integer, is_list_like
-from pandas.core import config
-
-_writer_extensions = ["xlsx", "xls", "xlsm"]
-
-
_writers = {}
def register_writer(klass):
- """Adds engine to the excel writer registry. You must use this method to
- integrate with ``to_excel``. Also adds config options for any new
- ``supported_extensions`` defined on the writer."""
+ """
+ Add engine to the excel writer registry.io.excel.
+
+ You must use this method to integrate with ``to_excel``.
+
+ Parameters
+ ----------
+ klass : ExcelWriter
+ """
if not callable(klass):
raise ValueError("Can only register callables as engines")
engine_name = klass.engine
_writers[engine_name] = klass
- for ext in klass.supported_extensions:
- if ext.startswith('.'):
- ext = ext[1:]
- if ext not in _writer_extensions:
- config.register_option("io.excel.{ext}.writer".format(ext=ext),
- engine_name, validator=str)
- _writer_extensions.append(ext)
def _get_default_writer(ext):
+ """
+ Return the default writer for the given extension.
+
+ Parameters
+ ----------
+ ext : str
+ The excel file extension for which to get the default engine.
+
+ Returns
+ -------
+ str
+ The default engine for the extension.
+ """
_default_writers = {'xlsx': 'openpyxl', 'xlsm': 'openpyxl', 'xls': 'xlwt'}
try:
import xlsxwriter # noqa
@@ -230,8 +237,6 @@ def _fill_mi_header(row, control_row):
return _maybe_convert_to_string(row), control_row
-# fill blank if index_col not None
-
def _pop_header_name(row, index_col):
"""
diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py
index 09b2d86bde3d3..04c9c58a326a4 100644
--- a/pandas/tests/io/test_excel.py
+++ b/pandas/tests/io/test_excel.py
@@ -2359,7 +2359,7 @@ def test_register_writer(self):
class DummyClass(ExcelWriter):
called_save = False
called_write_cells = False
- supported_extensions = ['test', 'xlsx', 'xls']
+ supported_extensions = ['xlsx', 'xls']
engine = 'dummy'
def save(self):
@@ -2377,12 +2377,9 @@ def check_called(func):
with pd.option_context('io.excel.xlsx.writer', 'dummy'):
register_writer(DummyClass)
- writer = ExcelWriter('something.test')
+ writer = ExcelWriter('something.xlsx')
assert isinstance(writer, DummyClass)
df = tm.makeCustomDataframe(1, 1)
-
- func = lambda: df.to_excel('something.test')
- check_called(func)
check_called(lambda: df.to_excel('something.xlsx'))
check_called(
lambda: df.to_excel(
| - [x] closes #25271
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
| https://api.github.com/repos/pandas-dev/pandas/pulls/25275 | 2019-02-11T21:02:24Z | 2019-02-20T08:04:32Z | 2019-02-20T08:04:32Z | 2019-02-20T08:42:25Z |
REF: use _constructor and ABCFoo to avoid runtime imports | diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index f187d786d9f61..640d43f3b0e03 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -8,7 +8,8 @@
from pandas._libs.interval import Interval
from pandas._libs.tslibs import NaT, Period, Timestamp, timezones
-from pandas.core.dtypes.generic import ABCCategoricalIndex, ABCIndexClass
+from pandas.core.dtypes.generic import (
+ ABCCategoricalIndex, ABCDateOffset, ABCIndexClass)
from pandas import compat
@@ -758,8 +759,7 @@ def __new__(cls, freq=None):
# empty constructor for pickle compat
return object.__new__(cls)
- from pandas.tseries.offsets import DateOffset
- if not isinstance(freq, DateOffset):
+ if not isinstance(freq, ABCDateOffset):
freq = cls._parse_dtype_strict(freq)
try:
@@ -790,12 +790,10 @@ def construct_from_string(cls, string):
Strict construction from a string, raise a TypeError if not
possible
"""
- from pandas.tseries.offsets import DateOffset
-
if (isinstance(string, compat.string_types) and
(string.startswith('period[') or
string.startswith('Period[')) or
- isinstance(string, DateOffset)):
+ isinstance(string, ABCDateOffset)):
# do not parse string like U as period[U]
# avoid tuple to be regarded as freq
try:
diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py
index 3c6d3f212342b..697c58a365233 100644
--- a/pandas/core/dtypes/missing.py
+++ b/pandas/core/dtypes/missing.py
@@ -221,8 +221,8 @@ def _isna_ndarraylike(obj):
# box
if isinstance(obj, ABCSeries):
- from pandas import Series
- result = Series(result, index=obj.index, name=obj.name, copy=False)
+ result = obj._constructor(
+ result, index=obj.index, name=obj.name, copy=False)
return result
@@ -250,8 +250,8 @@ def _isna_ndarraylike_old(obj):
# box
if isinstance(obj, ABCSeries):
- from pandas import Series
- result = Series(result, index=obj.index, name=obj.name, copy=False)
+ result = obj._constructor(
+ result, index=obj.index, name=obj.name, copy=False)
return result
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py
index 3da349c570274..0c76ac6cd75ac 100644
--- a/pandas/core/tools/datetimes.py
+++ b/pandas/core/tools/datetimes.py
@@ -588,9 +588,8 @@ def to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False,
if not cache_array.empty:
result = arg.map(cache_array)
else:
- from pandas import Series
values = convert_listlike(arg._values, True, format)
- result = Series(values, index=arg.index, name=arg.name)
+ result = arg._constructor(values, index=arg.index, name=arg.name)
elif isinstance(arg, (ABCDataFrame, compat.MutableMapping)):
result = _assemble_from_unit_mappings(arg, errors, box, tz)
elif isinstance(arg, ABCIndexClass):
@@ -827,7 +826,6 @@ def to_time(arg, format=None, infer_time_format=False, errors='raise'):
-------
datetime.time
"""
- from pandas.core.series import Series
def _convert_listlike(arg, format):
@@ -892,9 +890,9 @@ def _convert_listlike(arg, format):
return arg
elif isinstance(arg, time):
return arg
- elif isinstance(arg, Series):
+ elif isinstance(arg, ABCSeries):
values = _convert_listlike(arg._values, format)
- return Series(values, index=arg.index, name=arg.name)
+ return arg._constructor(values, index=arg.index, name=arg.name)
elif isinstance(arg, ABCIndexClass):
return _convert_listlike(arg, format)
elif is_list_like(arg):
diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py
index 30cb15f311b9f..7ebaf3056e79e 100644
--- a/pandas/core/tools/timedeltas.py
+++ b/pandas/core/tools/timedeltas.py
@@ -6,12 +6,12 @@
import numpy as np
+from pandas._libs.tslibs import NaT
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 ABCIndexClass, ABCSeries
-import pandas as pd
from pandas.core.arrays.timedeltas import sequence_to_td64ns
@@ -100,10 +100,9 @@ def to_timedelta(arg, unit='ns', box=True, errors='raise'):
if arg is None:
return arg
elif isinstance(arg, ABCSeries):
- from pandas import Series
values = _convert_listlike(arg._values, unit=unit,
box=False, errors=errors)
- return Series(values, index=arg.index, name=arg.name)
+ return arg._constructor(values, index=arg.index, name=arg.name)
elif isinstance(arg, ABCIndexClass):
return _convert_listlike(arg, unit=unit, box=box,
errors=errors, name=arg.name)
@@ -136,7 +135,7 @@ def _coerce_scalar_to_timedelta_type(r, unit='ns', box=True, errors='raise'):
return r
# coerce
- result = pd.NaT
+ result = NaT
return result
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25272 | 2019-02-11T18:13:03Z | 2019-02-11T19:37:54Z | 2019-02-11T19:37:53Z | 2019-03-05T21:02:54Z |
[BUG] exception handling of MultiIndex.__contains__ too narrow | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index 686c5ad0165e7..9d33c651ef283 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -149,10 +149,9 @@ Missing
MultiIndex
^^^^^^^^^^
+- Bug in which incorrect exception raised by :meth:`pd.Timedelta` when testing the membership of :class:`MultiIndex` (:issue:`24570`)
-
-
--
-
I/O
^^^
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index efb77b5d155a1..c19b6f61f2caa 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -840,7 +840,7 @@ def __contains__(self, key):
try:
self.get_loc(key)
return True
- except (LookupError, TypeError):
+ except (LookupError, TypeError, ValueError):
return False
contains = __contains__
diff --git a/pandas/tests/indexing/multiindex/test_multiindex.py b/pandas/tests/indexing/multiindex/test_multiindex.py
index 4f5517f89e852..ccf017489e046 100644
--- a/pandas/tests/indexing/multiindex/test_multiindex.py
+++ b/pandas/tests/indexing/multiindex/test_multiindex.py
@@ -84,3 +84,11 @@ def test_multi_nan_indexing(self):
name='a'),
Index(['C1', 'C2', 'C3', 'C4'], name='b')])
tm.assert_frame_equal(result, expected)
+
+ def test_contains(self):
+ # GH 24570
+ tx = pd.timedelta_range('09:30:00', '16:00:00', freq='30 min')
+ idx = MultiIndex.from_arrays([tx, np.arange(len(tx))])
+ assert tx[0] in idx
+ assert 'element_not_exit' not in idx
+ assert '0 day 09:30:00' in idx
| - closes #24570
- 1 test added
- passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25268 | 2019-02-11T14:31:59Z | 2019-02-19T13:46:05Z | 2019-02-19T13:46:04Z | 2019-02-19T13:46:12Z |
Backport PR #25234 on branch 0.24.x (BUG: Duplicated returns boolean dataframe) | diff --git a/doc/source/whatsnew/v0.24.2.rst b/doc/source/whatsnew/v0.24.2.rst
index b0f287cf0b9f6..5ae777ca68eba 100644
--- a/doc/source/whatsnew/v0.24.2.rst
+++ b/doc/source/whatsnew/v0.24.2.rst
@@ -24,6 +24,8 @@ Fixed Regressions
- Fixed issue in ``DataFrame`` construction with passing a mixed list of mixed types could segfault. (:issue:`25075`)
- Fixed regression in :meth:`DataFrame.apply` causing ``RecursionError`` when ``dict``-like classes were passed as argument. (:issue:`25196`)
+- Fixed regression in :meth:`DataFrame.duplicated()`, where empty dataframe was not returning a boolean dtyped Series. (:issue:`25184`)
+
.. _whatsnew_0242.enhancements:
Enhancements
diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index fac42dbd9c7c8..1f4fb39f76c7c 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -69,6 +69,8 @@ Performance Improvements
Bug Fixes
~~~~~~~~~
+-
+
Categorical
^^^^^^^^^^^
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index da638e24dfce5..f5535096c967d 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4661,7 +4661,7 @@ def duplicated(self, subset=None, keep='first'):
from pandas._libs.hashtable import duplicated_int64, _SIZE_HINT_LIMIT
if self.empty:
- return Series()
+ return Series(dtype=bool)
def f(vals):
labels, shape = algorithms.factorize(
diff --git a/pandas/tests/frame/test_duplicates.py b/pandas/tests/frame/test_duplicates.py
index f61dbbdb989e4..3396670fb5879 100644
--- a/pandas/tests/frame/test_duplicates.py
+++ b/pandas/tests/frame/test_duplicates.py
@@ -182,6 +182,17 @@ def test_drop_duplicates():
assert df.duplicated(keep=keep).sum() == 0
+def test_duplicated_on_empty_frame():
+ # GH 25184
+
+ df = DataFrame(columns=['a', 'b'])
+ dupes = df.duplicated('a')
+
+ result = df[dupes]
+ expected = df.copy()
+ tm.assert_frame_equal(result, expected)
+
+
def test_drop_duplicates_with_duplicate_column_names():
# GH17836
df = DataFrame([
| Backport PR #25234: BUG: Duplicated returns boolean dataframe | https://api.github.com/repos/pandas-dev/pandas/pulls/25267 | 2019-02-11T12:53:23Z | 2019-02-11T13:59:47Z | 2019-02-11T13:59:47Z | 2019-02-11T13:59:47Z |
BUG: Fix regression on DataFrame.replace for regex | diff --git a/doc/source/whatsnew/v0.24.2.rst b/doc/source/whatsnew/v0.24.2.rst
index b0f287cf0b9f6..63a83af79246c 100644
--- a/doc/source/whatsnew/v0.24.2.rst
+++ b/doc/source/whatsnew/v0.24.2.rst
@@ -23,6 +23,7 @@ Fixed Regressions
- Fixed regression in :meth:`DataFrame.all` and :meth:`DataFrame.any` where ``bool_only=True`` was ignored (:issue:`25101`)
- Fixed issue in ``DataFrame`` construction with passing a mixed list of mixed types could segfault. (:issue:`25075`)
- Fixed regression in :meth:`DataFrame.apply` causing ``RecursionError`` when ``dict``-like classes were passed as argument. (:issue:`25196`)
+- Fixed regression in :meth:`DataFrame.replace` where ``regex=True`` was only replacing patterns matching the start of the string (:issue:`25259`)
.. _whatsnew_0242.enhancements:
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 38b719db1709f..407db772d73e8 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -552,9 +552,9 @@ def comp(s, regex=False):
if isna(s):
return isna(values)
if hasattr(s, 'asm8'):
- return _compare_or_regex_match(maybe_convert_objects(values),
- getattr(s, 'asm8'), regex)
- return _compare_or_regex_match(values, s, regex)
+ return _compare_or_regex_search(maybe_convert_objects(values),
+ getattr(s, 'asm8'), regex)
+ return _compare_or_regex_search(values, s, regex)
masks = [comp(s, regex) for i, s in enumerate(src_list)]
@@ -1897,11 +1897,11 @@ def _consolidate(blocks):
return new_blocks
-def _compare_or_regex_match(a, b, regex=False):
+def _compare_or_regex_search(a, b, regex=False):
"""
Compare two array_like inputs of the same shape or two scalar values
- Calls operator.eq or re.match, depending on regex argument. If regex is
+ Calls operator.eq or re.search, depending on regex argument. If regex is
True, perform an element-wise regex matching.
Parameters
@@ -1917,7 +1917,7 @@ def _compare_or_regex_match(a, b, regex=False):
if not regex:
op = lambda x: operator.eq(x, b)
else:
- op = np.vectorize(lambda x: bool(re.match(b, x)) if isinstance(x, str)
+ op = np.vectorize(lambda x: bool(re.search(b, x)) if isinstance(x, str)
else False)
is_a_array = isinstance(a, np.ndarray)
diff --git a/pandas/tests/frame/test_replace.py b/pandas/tests/frame/test_replace.py
index 219f7a1585fc2..127a64da38ba3 100644
--- a/pandas/tests/frame/test_replace.py
+++ b/pandas/tests/frame/test_replace.py
@@ -466,6 +466,13 @@ def test_regex_replace_dict_nested(self):
assert_frame_equal(res3, expec)
assert_frame_equal(res4, expec)
+ def test_regex_replace_dict_nested_non_first_character(self):
+ # GH 25259
+ df = pd.DataFrame({'first': ['abc', 'bca', 'cab']})
+ expected = pd.DataFrame({'first': ['.bc', 'bc.', 'c.b']})
+ result = df.replace({'a': '.'}, regex=True)
+ assert_frame_equal(result, expected)
+
def test_regex_replace_dict_nested_gh4115(self):
df = pd.DataFrame({'Type': ['Q', 'T', 'Q', 'Q', 'T'], 'tmp': 2})
expected = DataFrame({'Type': [0, 1, 0, 0, 1], 'tmp': 2})
| The commit ensures that the replacement for regex is not confined to the
beginning of the string but spans all the characters within. The
behaviour is then consistent with versions prior to 0.24.0.
- [x] closes #25259
- [x] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/25266 | 2019-02-11T10:41:58Z | 2019-02-28T13:55:34Z | 2019-02-28T13:55:33Z | 2019-02-28T18:44:51Z |
BUG: support casting from bool array to EA Integer dtype | diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst
index dacd433f112a5..11507b5d3cb43 100644
--- a/doc/source/whatsnew/v0.25.0.rst
+++ b/doc/source/whatsnew/v0.25.0.rst
@@ -308,8 +308,9 @@ Numeric
- Bug in :meth:`Series.divmod` and :meth:`Series.rdivmod` which would raise an (incorrect) ``ValueError`` rather than return a pair of :class:`Series` objects as result (:issue:`25557`)
- Raises a helpful exception when a non-numeric index is sent to :meth:`interpolate` with methods which require numeric index. (:issue:`21662`)
- Bug in :meth:`~pandas.eval` when comparing floats with scalar operators, for example: ``x < -0.1`` (:issue:`25928`)
+- Fixed bug where casting all-boolean array to integer extension array failed (:issue:`25211`)
+-
-
-
Conversion
^^^^^^^^^^
diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py
index 8e81066de71cb..42aa6a055acca 100644
--- a/pandas/core/arrays/integer.py
+++ b/pandas/core/arrays/integer.py
@@ -188,6 +188,9 @@ def coerce_to_array(values, dtype, mask=None, copy=False):
raise TypeError("{} cannot be converted to an IntegerDtype".format(
values.dtype))
+ elif is_bool_dtype(values) and is_integer_dtype(dtype):
+ values = np.array(values, dtype=int, copy=copy)
+
elif not (is_integer_dtype(values) or is_float_dtype(values)):
raise TypeError("{} cannot be converted to an IntegerDtype".format(
values.dtype))
diff --git a/pandas/core/series.py b/pandas/core/series.py
index e23d0bf6a5b83..f0b674596656a 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2670,7 +2670,6 @@ def combine(self, other, func, fill_value=None):
# do in _values_from_sequence. We still want ops to work
# though, so we catch any regular Exception.
pass
-
return self._constructor(new_values, index=new_index, name=new_name)
def combine_first(self, other):
diff --git a/pandas/tests/arrays/test_integer.py b/pandas/tests/arrays/test_integer.py
index 759dacd7f221e..066eadc9b68bc 100644
--- a/pandas/tests/arrays/test_integer.py
+++ b/pandas/tests/arrays/test_integer.py
@@ -613,6 +613,19 @@ def test_to_integer_array_float():
assert result.dtype == Int64Dtype()
+@pytest.mark.parametrize(
+ 'bool_values, int_values, target_dtype, expected_dtype',
+ [([False, True], [0, 1], Int64Dtype(), Int64Dtype()),
+ ([False, True], [0, 1], 'Int64', Int64Dtype()),
+ ([False, True, np.nan], [0, 1, np.nan], Int64Dtype(), Int64Dtype())])
+def test_to_integer_array_bool(bool_values, int_values, target_dtype,
+ expected_dtype):
+ result = integer_array(bool_values, dtype=target_dtype)
+ assert result.dtype == expected_dtype
+ expected = integer_array(int_values, dtype=target_dtype)
+ tm.assert_extension_array_equal(result, expected)
+
+
@pytest.mark.parametrize(
'values, to_dtype, result_dtype',
[
| Cast boolean array to int before casting to EA Integer dtype.
- [x] closes #25211
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
| https://api.github.com/repos/pandas-dev/pandas/pulls/25265 | 2019-02-11T09:09:36Z | 2019-05-14T14:15:30Z | 2019-05-14T14:15:30Z | 2019-05-14T14:25:41Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.