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 |
|---|---|---|---|---|---|---|---|
DOC: timezone warning for DST beyond 2038-01-18 | diff --git a/doc/source/user_guide/timeseries.rst b/doc/source/user_guide/timeseries.rst
index 6ba58310000cb..a88cb22bd0767 100644
--- a/doc/source/user_guide/timeseries.rst
+++ b/doc/source/user_guide/timeseries.rst
@@ -2265,6 +2265,24 @@ you can use the ``tz_convert`` method.
Instead, the datetime needs to be localized using the ``localize`` method
on the ``pytz`` time zone object.
+.. warning::
+
+ If you are using dates beyond 2038-01-18, due to current deficiencies
+ in the underlying libraries caused by the year 2038 problem, daylight saving time (DST) adjustments
+ to timezone aware dates will not be applied. If and when the underlying libraries are fixed,
+ the DST transitions will be applied. It should be noted though, that time zone data for far future time zones
+ are likely to be inaccurate, as they are simple extrapolations of the current set of (regularly revised) rules.
+
+ For example, for two dates that are in British Summer Time (and so would normally be GMT+1), both the following asserts evaluate as true:
+
+ .. ipython:: python
+
+ d_2037 = '2037-03-31T010101'
+ d_2038 = '2038-03-31T010101'
+ DST = 'Europe/London'
+ assert pd.Timestamp(d_2037, tz=DST) != pd.Timestamp(d_2037, tz='GMT')
+ assert pd.Timestamp(d_2038, tz=DST) == pd.Timestamp(d_2038, tz='GMT')
+
Under the hood, all timestamps are stored in UTC. Values from a time zone aware
:class:`DatetimeIndex` or :class:`Timestamp` will have their fields (day, hour, minute, etc.)
localized to the time zone. However, timestamps with the same UTC value are
| Add warning to time_series user guide that after 2038-01-18 DST will not be respected in tz aware dates
- [x ] closes #33061
- [ ] 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/33863 | 2020-04-29T10:38:36Z | 2020-05-10T14:41:07Z | 2020-05-10T14:41:06Z | 2020-05-10T18:09:58Z |
TYP/CLN: remove #type: ignore from pandas\tests\test_strings.py | diff --git a/pandas/conftest.py b/pandas/conftest.py
index 16b6d40645547..11bb16fc0a3a9 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -297,6 +297,10 @@ def index_or_series(request):
return request.param
+# Generate cartesian product of index_or_series fixture:
+index_or_series2 = index_or_series
+
+
@pytest.fixture
def dict_subclass():
"""
diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py
index 6260d13524da3..35786ce64ac15 100644
--- a/pandas/tests/test_strings.py
+++ b/pandas/tests/test_strings.py
@@ -671,14 +671,10 @@ def test_str_cat_align_mixed_inputs(self, join):
with pytest.raises(ValueError, match=rgx):
s.str.cat([t, z], join=join)
- index_or_series2 = [Series, Index] # type: ignore
- # List item 0 has incompatible type "Type[Series]"; expected "Type[PandasObject]"
- # See GH#29725
-
- @pytest.mark.parametrize("other", index_or_series2)
- def test_str_cat_all_na(self, index_or_series, other):
+ def test_str_cat_all_na(self, index_or_series, index_or_series2):
# GH 24044
box = index_or_series
+ other = index_or_series2
# check that all NaNs in caller / target work
s = Index(["a", "b", "c", "d"])
| https://api.github.com/repos/pandas-dev/pandas/pulls/33862 | 2020-04-29T08:46:22Z | 2020-04-29T22:47:24Z | 2020-04-29T22:47:24Z | 2020-04-30T08:48:54Z | |
DOC: Fix typo in inferred_freq docstring | diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index c325ec0d0bf7c..9d3ec284a2569 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -1066,7 +1066,7 @@ def freqstr(self):
@property # NB: override with cache_readonly in immutable subclasses
def inferred_freq(self):
"""
- Tryies to return a string representing a frequency guess,
+ Tries to return a string representing a frequency guess,
generated by infer_freq. Returns None if it can't autodetect the
frequency.
"""
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/33861 | 2020-04-29T07:52:45Z | 2020-04-29T09:32:08Z | 2020-04-29T09:32:08Z | 2020-04-29T09:32:18Z |
DOC: Fix groupby.agg/transform rst reference and numba references | diff --git a/doc/source/reference/groupby.rst b/doc/source/reference/groupby.rst
index 921eb737aef07..ca444dac9d77d 100644
--- a/doc/source/reference/groupby.rst
+++ b/doc/source/reference/groupby.rst
@@ -36,8 +36,10 @@ Function application
GroupBy.apply
GroupBy.agg
- GroupBy.aggregate
- GroupBy.transform
+ SeriesGroupBy.aggregate
+ DataFrameGroupBy.aggregate
+ SeriesGroupBy.transform
+ DataFrameGroupBy.transform
GroupBy.pipe
Computations / descriptive stats
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 6745203d5beb7..b35798079ba7f 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -63,10 +63,11 @@
import pandas.core.common as com
from pandas.core.construction import create_series_with_explicit_dtype
from pandas.core.frame import DataFrame
-from pandas.core.generic import ABCDataFrame, ABCSeries, NDFrame, _shared_docs
+from pandas.core.generic import ABCDataFrame, ABCSeries, NDFrame
from pandas.core.groupby import base
from pandas.core.groupby.groupby import (
GroupBy,
+ _agg_template,
_apply_docs,
_transform_template,
get_groupby,
@@ -177,16 +178,6 @@ def _selection_name(self):
else:
return self._selection
- _agg_see_also_doc = dedent(
- """
- See Also
- --------
- pandas.Series.groupby.apply
- pandas.Series.groupby.transform
- pandas.Series.aggregate
- """
- )
-
_agg_examples_doc = dedent(
"""
Examples
@@ -224,8 +215,7 @@ def _selection_name(self):
... )
minimum maximum
1 1 2
- 2 3 4
- """
+ 2 3 4"""
)
@Appender(
@@ -237,13 +227,9 @@ def apply(self, func, *args, **kwargs):
return super().apply(func, *args, **kwargs)
@Substitution(
- see_also=_agg_see_also_doc,
- examples=_agg_examples_doc,
- versionadded="",
- klass="Series",
- axis="",
+ examples=_agg_examples_doc, klass="Series",
)
- @Appender(_shared_docs["aggregate"])
+ @Appender(_agg_template)
def aggregate(
self, func=None, *args, engine="cython", engine_kwargs=None, **kwargs
):
@@ -476,7 +462,7 @@ def _aggregate_named(self, func, *args, **kwargs):
return result
- @Substitution(klass="Series", selected="A.")
+ @Substitution(klass="Series")
@Appender(_transform_template)
def transform(self, func, *args, engine="cython", engine_kwargs=None, **kwargs):
func = self._get_cython_func(func) or func
@@ -854,16 +840,6 @@ class DataFrameGroupBy(GroupBy[DataFrame]):
_apply_whitelist = base.dataframe_apply_whitelist
- _agg_see_also_doc = dedent(
- """
- See Also
- --------
- pandas.DataFrame.groupby.apply
- pandas.DataFrame.groupby.transform
- pandas.DataFrame.aggregate
- """
- )
-
_agg_examples_doc = dedent(
"""
Examples
@@ -928,7 +904,6 @@ class DataFrameGroupBy(GroupBy[DataFrame]):
1 1 0.590715
2 3 0.704907
-
- The keywords are the *output* column names
- The values are tuples whose first element is the column to select
and the second element is the aggregation to apply to that column.
@@ -936,18 +911,13 @@ class DataFrameGroupBy(GroupBy[DataFrame]):
``['column', 'aggfunc']`` to make it clearer what the arguments are.
As usual, the aggregation can be a callable or a string alias.
- See :ref:`groupby.aggregate.named` for more.
- """
+ See :ref:`groupby.aggregate.named` for more."""
)
@Substitution(
- see_also=_agg_see_also_doc,
- examples=_agg_examples_doc,
- versionadded="",
- klass="DataFrame",
- axis="",
+ examples=_agg_examples_doc, klass="DataFrame",
)
- @Appender(_shared_docs["aggregate"])
+ @Appender(_agg_template)
def aggregate(
self, func=None, *args, engine="cython", engine_kwargs=None, **kwargs
):
@@ -1467,7 +1437,7 @@ def _transform_general(
concatenated = concatenated.reindex(concat_index, axis=other_axis, copy=False)
return self._set_result_index_ordered(concatenated)
- @Substitution(klass="DataFrame", selected="")
+ @Substitution(klass="DataFrame")
@Appender(_transform_template)
def transform(self, func, *args, engine="cython", engine_kwargs=None, **kwargs):
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 6924c7d320bc4..81c3fd7ad9e89 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -291,7 +291,9 @@ class providing the base-class of operations.
See Also
--------
-aggregate, transform
+%(klass)s.groupby.apply
+%(klass)s.groupby.aggregate
+%(klass)s.transform
Notes
-----
@@ -310,14 +312,17 @@ class providing the base-class of operations.
* f must not mutate groups. Mutation is not supported and may
produce unexpected results.
+When using ``engine='numba'``, there will be no "fall back" behavior internally.
+The group data and group index will be passed as numpy arrays to the JITed
+user defined function, and no alternative execution attempts will be tried.
+
Examples
--------
-# Same shape
>>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
... 'foo', 'bar'],
... 'B' : ['one', 'one', 'two', 'three',
-... 'two', 'two'],
+... 'two', 'two'],
... 'C' : [1, 5, 5, 2, 5, 5],
... 'D' : [2.0, 5., 8., 1., 2., 9.]})
>>> grouped = df.groupby('A')
@@ -330,7 +335,8 @@ class providing the base-class of operations.
4 0.577350 -0.577350
5 0.577350 1.000000
-# Broadcastable
+Broadcast result of the transformation
+
>>> grouped.transform(lambda x: x.max() - x.min())
C D
0 4 6.0
@@ -341,6 +347,69 @@ class providing the base-class of operations.
5 3 8.0
"""
+_agg_template = """
+Aggregate using one or more operations over the specified axis.
+
+Parameters
+----------
+func : function, str, list or dict
+ Function to use for aggregating the data. If a function, must either
+ work when passed a %(klass)s or when passed to %(klass)s.apply.
+
+ Accepted combinations are:
+
+ - function
+ - string function name
+ - list of functions and/or function names, e.g. ``[np.sum, 'mean']``
+ - dict of axis labels -> functions, function names or list of such.
+
+ Can also accept a Numba JIT function with
+ ``engine='numba'`` specified.
+
+ If the ``'numba'`` engine is chosen, the function must be
+ a user defined function with ``values`` and ``index`` as the
+ first and second arguments respectively in the function signature.
+ Each group's index will be passed to the user defined function
+ and optionally available for use.
+
+ .. versionchanged:: 1.1.0
+*args
+ Positional arguments to pass to func
+engine : str, default 'cython'
+ * ``'cython'`` : Runs the function through C-extensions from cython.
+ * ``'numba'`` : Runs the function through JIT compiled code from numba.
+
+ .. versionadded:: 1.1.0
+engine_kwargs : dict, default None
+ * For ``'cython'`` engine, there are no accepted ``engine_kwargs``
+ * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
+ and ``parallel`` dictionary keys. The values must either be ``True`` or
+ ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is
+ ``{'nopython': True, 'nogil': False, 'parallel': False}`` and will be
+ applied to the function
+
+ .. versionadded:: 1.1.0
+**kwargs
+ Keyword arguments to be passed into func.
+
+Returns
+-------
+%(klass)s
+
+See Also
+--------
+%(klass)s.groupby.apply
+%(klass)s.groupby.transform
+%(klass)s.aggregate
+
+Notes
+-----
+When using ``engine='numba'``, there will be no "fall back" behavior internally.
+The group data and group index will be passed as numpy arrays to the JITed
+user defined function, and no alternative execution attempts will be tried.
+%(examples)s
+"""
+
class GroupByPlot(PandasObject):
"""
| - [x] xref https://github.com/pandas-dev/pandas/pull/33388#issuecomment-618808443
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
| https://api.github.com/repos/pandas-dev/pandas/pulls/33860 | 2020-04-29T04:03:04Z | 2020-05-01T05:41:08Z | 2020-05-01T05:41:08Z | 2020-05-01T05:41:13Z |
TST: stop skipping Categorical take tests | diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py
index 059d3453995bd..390c7a2afc641 100644
--- a/pandas/tests/extension/test_categorical.py
+++ b/pandas/tests/extension/test_categorical.py
@@ -97,8 +97,6 @@ class TestReshaping(base.BaseReshapingTests):
class TestGetitem(base.BaseGetitemTests):
- skip_take = pytest.mark.skip(reason="GH-20664.")
-
@pytest.mark.skip(reason="Backwards compatibility")
def test_getitem_scalar(self, data):
# CategoricalDtype.type isn't "correct" since it should
@@ -106,43 +104,6 @@ def test_getitem_scalar(self, data):
# to break things by changing.
super().test_getitem_scalar(data)
- @skip_take
- def test_take(self, data, na_value, na_cmp):
- # TODO remove this once Categorical.take is fixed
- super().test_take(data, na_value, na_cmp)
-
- @skip_take
- def test_take_negative(self, data):
- super().test_take_negative(data)
-
- @skip_take
- def test_take_pandas_style_negative_raises(self, data, na_value):
- super().test_take_pandas_style_negative_raises(data, na_value)
-
- @skip_take
- def test_take_non_na_fill_value(self, data_missing):
- super().test_take_non_na_fill_value(data_missing)
-
- @skip_take
- def test_take_out_of_bounds_raises(self, data, allow_fill):
- return super().test_take_out_of_bounds_raises(data, allow_fill)
-
- @pytest.mark.skip(reason="GH-20747. Unobserved categories.")
- def test_take_series(self, data):
- super().test_take_series(data)
-
- @skip_take
- def test_reindex_non_na_fill_value(self, data_missing):
- super().test_reindex_non_na_fill_value(data_missing)
-
- @pytest.mark.skip(reason="Categorical.take buggy")
- def test_take_empty(self, data, na_value, na_cmp):
- super().test_take_empty(data, na_value, na_cmp)
-
- @pytest.mark.skip(reason="test not written correctly for categorical")
- def test_reindex(self, data, na_value):
- super().test_reindex(data, na_value)
-
class TestSetitem(base.BaseSetitemTests):
pass
| https://api.github.com/repos/pandas-dev/pandas/pulls/33859 | 2020-04-29T03:41:36Z | 2020-04-29T07:18:31Z | 2020-04-29T07:18:31Z | 2020-04-29T14:43:00Z | |
CLN: address FIXME/TODO/XXX comments | diff --git a/ci/setup_env.sh b/ci/setup_env.sh
index ae39b0dda5d09..16bbd7693da37 100755
--- a/ci/setup_env.sh
+++ b/ci/setup_env.sh
@@ -128,7 +128,7 @@ conda list pandas
echo "[Build extensions]"
python setup.py build_ext -q -i -j2
-# XXX: Some of our environments end up with old versions of pip (10.x)
+# TODO: Some of our environments end up with old versions of pip (10.x)
# Adding a new enough version of pip to the requirements explodes the
# solve time. Just using pip to update itself.
# - py35_macos
diff --git a/pandas/_libs/src/parser/tokenizer.h b/pandas/_libs/src/parser/tokenizer.h
index 4fd2065c07100..7dfae737718a5 100644
--- a/pandas/_libs/src/parser/tokenizer.h
+++ b/pandas/_libs/src/parser/tokenizer.h
@@ -52,8 +52,8 @@ See LICENSE for the license
#define PARSER_OUT_OF_MEMORY -1
/*
- * XXX Might want to couple count_rows() with read_rows() to avoid duplication
- * of some file I/O.
+ * TODO: Might want to couple count_rows() with read_rows() to avoid
+ * duplication of some file I/O.
*/
typedef enum {
diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx
index ce4d3a4ef8e02..c56d24d68a175 100644
--- a/pandas/_libs/tslibs/strptime.pyx
+++ b/pandas/_libs/tslibs/strptime.pyx
@@ -544,7 +544,7 @@ class TimeRE(dict):
'w': r"(?P<w>[0-6])",
# W is set below by using 'U'
'y': r"(?P<y>\d\d)",
- # XXX: Does 'Y' need to worry about having less or more than
+ # TODO: Does 'Y' need to worry about having less or more than
# 4 digits?
'Y': r"(?P<Y>\d\d\d\d)",
'z': r"(?P<z>[+-]\d\d:?[0-5]\d(:?[0-5]\d(\.\d{1,6})?)?|Z)",
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index eca1733b61a52..ce22c3f5416fa 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -142,6 +142,7 @@ def _ensure_data(values, dtype=None):
if values.ndim > 1 and is_datetime64_ns_dtype(values):
# Avoid calling the DatetimeIndex constructor as it is 1D only
# Note: this is reached by DataFrame.rank calls GH#27027
+ # TODO(EA2D): special case not needed with 2D EAs
asi8 = values.view("i8")
dtype = values.dtype
return asi8, dtype
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index 620e157ee54ec..72b6e07942d5e 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -335,7 +335,7 @@ def __init__(
# TODO: disentangle the fill_value dtype inference from
# dtype inference
if data is None:
- # XXX: What should the empty dtype be? Object or float?
+ # TODO: What should the empty dtype be? Object or float?
data = np.array([], dtype=dtype)
if not is_array_like(data):
diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py
index 257c4fe3c6d30..2c560a1ed8c62 100644
--- a/pandas/core/dtypes/concat.py
+++ b/pandas/core/dtypes/concat.py
@@ -178,6 +178,7 @@ def concat_categorical(to_concat, axis: int = 0):
]
result = concat_compat(to_concat)
if axis == 1:
+ # TODO(EA2D): not necessary with 2D EAs
result = result.reshape(1, len(result))
return result
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index ddf553dd1dd62..6745203d5beb7 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -1129,6 +1129,7 @@ def _cython_agg_blocks(
# e.g. block.values was an IntegerArray
# (1, N) case can occur if block.values was Categorical
# and result is ndarray[object]
+ # TODO(EA2D): special casing not needed with 2D EAs
assert result.ndim == 1 or result.shape[0] == 1
try:
# Cast back if feasible
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 65788970628dc..f799baf354794 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -476,8 +476,8 @@ def _cython_operation(
if is_datetime64tz_dtype(values.dtype):
# Cast to naive; we'll cast back at the end of the function
- # TODO: possible need to reshape? kludge can be avoided when
- # 2D EA is allowed.
+ # TODO: possible need to reshape?
+ # TODO(EA2D):kludge can be avoided when 2D EA is allowed.
values = values.view("M8[ns]")
is_datetimelike = needs_i8_conversion(values.dtype)
@@ -717,7 +717,7 @@ def _aggregate_series_pure_python(
if isinstance(res, (Series, Index, np.ndarray)):
if len(res) == 1:
# e.g. test_agg_lambda_with_timezone lambda e: e.head(1)
- # FIXME: are we potentially losing import res.index info?
+ # FIXME: are we potentially losing important res.index info?
res = res.item()
else:
raise ValueError("Function does not reduce")
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 366ea54a510ef..c40fad6b434d0 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -1721,7 +1721,7 @@ def take_nd(
return self.make_block_same_class(new_values, new_mgr_locs)
def _can_hold_element(self, element: Any) -> bool:
- # XXX: We may need to think about pushing this onto the array.
+ # TODO: We may need to think about pushing this onto the array.
# We're doing the same as CategoricalBlock here.
return True
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py
index 743dd6db348b4..e9bbd915df768 100644
--- a/pandas/core/internals/concat.py
+++ b/pandas/core/internals/concat.py
@@ -218,6 +218,7 @@ def is_na(self):
elif is_sparse(self.block.values.dtype):
return False
elif self.block.is_extension:
+ # TODO(EA2D): no need for special case with 2D EAs
values_flat = values
else:
values_flat = values.ravel(order="K")
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 2df81ba0aa51a..f289db39347ae 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -1851,7 +1851,7 @@ def _cast_types(self, values, cast_type, column):
)
if not is_object_dtype(values) and not known_cats:
- # XXX this is for consistency with
+ # TODO: this is for consistency with
# c-parser which parses all categories
# as strings
values = astype_nansafe(values, str)
diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py
index 8c937064c0493..e2d53493df95b 100644
--- a/pandas/tests/arithmetic/test_datetime64.py
+++ b/pandas/tests/arithmetic/test_datetime64.py
@@ -140,12 +140,10 @@ def test_dt64arr_nat_comparison(self, tz_naive_fixture, box_with_array):
ts = pd.Timestamp.now(tz)
ser = pd.Series([ts, pd.NaT])
- # FIXME: Can't transpose because that loses the tz dtype on
- # the NaT column
- obj = tm.box_expected(ser, box, transpose=False)
+ obj = tm.box_expected(ser, box)
expected = pd.Series([True, False], dtype=np.bool_)
- expected = tm.box_expected(expected, xbox, transpose=False)
+ expected = tm.box_expected(expected, xbox)
result = obj == ts
tm.assert_equal(result, expected)
@@ -843,10 +841,8 @@ def test_dt64arr_add_sub_td64_nat(self, box_with_array, tz_naive_fixture):
other = np.timedelta64("NaT")
expected = pd.DatetimeIndex(["NaT"] * 9, tz=tz)
- # FIXME: fails with transpose=True due to tz-aware DataFrame
- # transpose bug
- obj = tm.box_expected(dti, box_with_array, transpose=False)
- expected = tm.box_expected(expected, box_with_array, transpose=False)
+ obj = tm.box_expected(dti, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
result = obj + other
tm.assert_equal(result, expected)
diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py
index 55a547b361eb3..0e8bec331ea3f 100644
--- a/pandas/tests/arithmetic/test_period.py
+++ b/pandas/tests/arithmetic/test_period.py
@@ -906,9 +906,8 @@ def test_pi_add_offset_n_gt1_not_divisible(self, box_with_array):
pi = pd.PeriodIndex(["2016-01"], freq="2M")
expected = pd.PeriodIndex(["2016-04"], freq="2M")
- # FIXME: with transposing these tests fail
- pi = tm.box_expected(pi, box_with_array, transpose=False)
- expected = tm.box_expected(expected, box_with_array, transpose=False)
+ pi = tm.box_expected(pi, box_with_array)
+ expected = tm.box_expected(expected, box_with_array)
result = pi + to_offset("3M")
tm.assert_equal(result, expected)
diff --git a/pandas/tests/arrays/boolean/test_logical.py b/pandas/tests/arrays/boolean/test_logical.py
index 6cfe19e2fe3eb..bf4775bbd7b32 100644
--- a/pandas/tests/arrays/boolean/test_logical.py
+++ b/pandas/tests/arrays/boolean/test_logical.py
@@ -38,6 +38,7 @@ def test_empty_ok(self, all_logical_operators):
result = getattr(a, op_name)(False)
tm.assert_extension_array_equal(a, result)
+ # FIXME: dont leave commented-out
# TODO: pd.NA
# result = getattr(a, op_name)(pd.NA)
# tm.assert_extension_array_equal(a, result)
diff --git a/pandas/tests/base/test_conversion.py b/pandas/tests/base/test_conversion.py
index 59f9103072fe9..dd5b24dc2f960 100644
--- a/pandas/tests/base/test_conversion.py
+++ b/pandas/tests/base/test_conversion.py
@@ -48,8 +48,6 @@ class TestToIterable:
],
ids=["tolist", "to_list", "list", "iter"],
)
- @pytest.mark.filterwarnings("ignore:\\n Passing:FutureWarning")
- # TODO(GH-24559): Remove the filterwarnings
def test_iterable(self, index_or_series, method, dtype, rdtype):
# gh-10904
# gh-13258
@@ -104,8 +102,6 @@ def test_iterable_items(self, dtype, rdtype):
@pytest.mark.parametrize(
"dtype, rdtype", dtypes + [("object", int), ("category", int)]
)
- @pytest.mark.filterwarnings("ignore:\\n Passing:FutureWarning")
- # TODO(GH-24559): Remove the filterwarnings
def test_iterable_map(self, index_or_series, dtype, rdtype):
# gh-13236
# coerce iteration to underlying python / pandas types
diff --git a/pandas/tests/extension/base/dtype.py b/pandas/tests/extension/base/dtype.py
index b01867624cb16..ee4e199fbfe45 100644
--- a/pandas/tests/extension/base/dtype.py
+++ b/pandas/tests/extension/base/dtype.py
@@ -75,7 +75,7 @@ def test_check_dtype(self, data):
else:
expected = pd.Series([True, True, False, False], index=list("ABCD"))
- # XXX: This should probably be *fixed* not ignored.
+ # FIXME: This should probably be *fixed* not ignored.
# See libops.scalar_compare
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
diff --git a/pandas/tests/extension/base/getitem.py b/pandas/tests/extension/base/getitem.py
index dc94bffd320b1..251376798efc3 100644
--- a/pandas/tests/extension/base/getitem.py
+++ b/pandas/tests/extension/base/getitem.py
@@ -230,7 +230,8 @@ def test_getitem_integer_with_missing_raises(self, data, idx):
with pytest.raises(ValueError, match=msg):
data[idx]
- # TODO this raises KeyError about labels not found (it tries label-based)
+ # FIXME: dont leave commented-out
+ # TODO: this raises KeyError about labels not found (it tries label-based)
# import pandas._testing as tm
# s = pd.Series(data, index=[tm.rands(4) for _ in range(len(data))])
# with pytest.raises(ValueError, match=msg):
diff --git a/pandas/tests/extension/test_boolean.py b/pandas/tests/extension/test_boolean.py
index e2331b69916fb..20b1eaec7e71c 100644
--- a/pandas/tests/extension/test_boolean.py
+++ b/pandas/tests/extension/test_boolean.py
@@ -346,6 +346,7 @@ class TestUnaryOps(base.BaseUnaryOpsTests):
pass
+# FIXME: dont leave commented-out
# TODO parsing not yet supported
# class TestParsing(base.BaseParsingTests):
# pass
diff --git a/pandas/tests/frame/methods/test_round.py b/pandas/tests/frame/methods/test_round.py
index 6dcdf49e93729..3051f27882fb8 100644
--- a/pandas/tests/frame/methods/test_round.py
+++ b/pandas/tests/frame/methods/test_round.py
@@ -102,11 +102,6 @@ def test_round(self):
# nan in Series round
nan_round_Series = Series({"col1": np.nan, "col2": 1})
- # TODO(wesm): unused?
- expected_nan_round = DataFrame( # noqa
- {"col1": [1.123, 2.123, 3.123], "col2": [1.2, 2.2, 3.2]}
- )
-
msg = "integer argument expected, got float"
with pytest.raises(TypeError, match=msg):
df.round(nan_round_Series)
diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
index 52b82b36d13be..8e8f4738d30dd 100644
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -561,8 +561,7 @@ def test_equals(self, indices):
assert not indices.equals(np.array(indices))
# Cannot pass in non-int64 dtype to RangeIndex
- if not isinstance(indices, (RangeIndex, CategoricalIndex)):
- # TODO: CategoricalIndex can be re-allowed following GH#32167
+ if not isinstance(indices, RangeIndex):
same_values = Index(indices, dtype=object)
assert indices.equals(same_values)
assert same_values.equals(indices)
diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py
index 6ddbe4a5ce0a5..d46fe0181ea1b 100644
--- a/pandas/tests/indexes/datetimes/test_date_range.py
+++ b/pandas/tests/indexes/datetimes/test_date_range.py
@@ -846,7 +846,7 @@ def test_daterange_bug_456(self):
# GH #456
rng1 = bdate_range("12/5/2011", "12/5/2011")
rng2 = bdate_range("12/2/2011", "12/5/2011")
- rng2._data.freq = BDay() # TODO: shouldn't this already be set?
+ assert rng2._data.freq == BDay()
result = rng1.union(rng2)
assert isinstance(result, DatetimeIndex)
@@ -905,7 +905,7 @@ def test_daterange_bug_456(self):
# GH #456
rng1 = bdate_range("12/5/2011", "12/5/2011", freq="C")
rng2 = bdate_range("12/2/2011", "12/5/2011", freq="C")
- rng2._data.freq = CDay() # TODO: shouldn't this already be set?
+ assert rng2._data.freq == CDay()
result = rng1.union(rng2)
assert isinstance(result, DatetimeIndex)
diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py
index 17722e949df1e..fa5fe5ba5c384 100644
--- a/pandas/tests/indexing/test_chaining_and_caching.py
+++ b/pandas/tests/indexing/test_chaining_and_caching.py
@@ -376,9 +376,6 @@ def test_cache_updating(self):
df["f"] = 0
df.f.values[3] = 1
- # TODO(wesm): unused?
- # y = df.iloc[np.arange(2, len(df))]
-
df.f.values[3] = 2
expected = DataFrame(
np.zeros((5, 6), dtype="int64"),
diff --git a/pandas/tests/io/excel/test_style.py b/pandas/tests/io/excel/test_style.py
index 31b033f381f0c..936fc175a493b 100644
--- a/pandas/tests/io/excel/test_style.py
+++ b/pandas/tests/io/excel/test_style.py
@@ -23,7 +23,7 @@
)
def test_styler_to_excel(engine):
def style(df):
- # XXX: RGB colors not supported in xlwt
+ # TODO: RGB colors not supported in xlwt
return DataFrame(
[
["font-weight: bold", "", ""],
@@ -47,7 +47,7 @@ def assert_equal_style(cell1, cell2, engine):
pytest.xfail(
reason=(f"GH25351: failing on some attribute comparisons in {engine}")
)
- # XXX: should find a better way to check equality
+ # TODO: should find a better way to check equality
assert cell1.alignment.__dict__ == cell2.alignment.__dict__
assert cell1.border.__dict__ == cell2.border.__dict__
assert cell1.fill.__dict__ == cell2.fill.__dict__
@@ -98,7 +98,7 @@ def custom_converter(css):
# (2) check styling with default converter
- # XXX: openpyxl (as at 2.4) prefixes colors with 00, xlsxwriter with FF
+ # TODO: openpyxl (as at 2.4) prefixes colors with 00, xlsxwriter with FF
alpha = "00" if engine == "openpyxl" else "FF"
n_cells = 0
@@ -106,7 +106,7 @@ def custom_converter(css):
assert len(col1) == len(col2)
for cell1, cell2 in zip(col1, col2):
ref = f"{cell2.column}{cell2.row:d}"
- # XXX: this isn't as strong a test as ideal; we should
+ # TODO: this isn't as strong a test as ideal; we should
# confirm that differences are exclusive
if ref == "B2":
assert not cell1.font.bold
diff --git a/pandas/tests/io/formats/test_css.py b/pandas/tests/io/formats/test_css.py
index 7008cef7b28fa..9383f86e335fa 100644
--- a/pandas/tests/io/formats/test_css.py
+++ b/pandas/tests/io/formats/test_css.py
@@ -60,8 +60,6 @@ def test_css_parse_invalid(invalid_css, remainder):
with tm.assert_produces_warning(CSSWarning):
assert_same_resolution(invalid_css, remainder)
- # TODO: we should be checking that in other cases no warnings are raised
-
@pytest.mark.parametrize(
"shorthand,expansions",
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index 70f3f99442183..8c424e07601b8 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -1130,7 +1130,7 @@ def setup_method(self, load_iris_data):
self.conn.close()
self.conn = self.__engine
self.pandasSQL = sql.SQLDatabase(self.__engine)
- # XXX:
+ # FIXME: dont leave commented-out
# super().teardown_method(method)
diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py
index c4025640bb49f..7c01664df0607 100644
--- a/pandas/tests/reshape/test_concat.py
+++ b/pandas/tests/reshape/test_concat.py
@@ -228,7 +228,7 @@ def test_concatlike_dtypes_coercion(self):
# same dtype is tested in test_concatlike_same_dtypes
continue
elif typ1 == "category" or typ2 == "category":
- # ToDo: suspicious
+ # TODO: suspicious
continue
# specify expected dtype
diff --git a/pandas/tests/scalar/timedelta/test_arithmetic.py b/pandas/tests/scalar/timedelta/test_arithmetic.py
index eb22b715f9f4d..3825fc4514ea3 100644
--- a/pandas/tests/scalar/timedelta/test_arithmetic.py
+++ b/pandas/tests/scalar/timedelta/test_arithmetic.py
@@ -652,7 +652,6 @@ def test_td_rfloordiv_numeric_series(self):
msg = "Invalid dtype"
with pytest.raises(TypeError, match=msg):
# Deprecated GH#19761, enforced GH#29797
- # TODO: GH-19761. Change to TypeError.
ser // td
# ----------------------------------------------------------------
diff --git a/pandas/tests/series/indexing/test_datetime.py b/pandas/tests/series/indexing/test_datetime.py
index 22ef966299d5b..0b34fab7b80b1 100644
--- a/pandas/tests/series/indexing/test_datetime.py
+++ b/pandas/tests/series/indexing/test_datetime.py
@@ -556,8 +556,6 @@ def test_indexing_unordered():
ts2 = pd.concat([ts[0:4], ts[-4:], ts[4:-4]])
for t in ts.index:
- # TODO: unused?
- s = str(t) # noqa
expected = ts[t]
result = ts2[t]
diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py
index c2b5117d395f9..16b6604c7fc52 100644
--- a/pandas/tests/series/indexing/test_indexing.py
+++ b/pandas/tests/series/indexing/test_indexing.py
@@ -445,7 +445,7 @@ def test_setitem_with_tz(tz):
def test_setitem_with_tz_dst():
- # GH XXX
+ # GH XXX TODO: fill in GH ref
tz = "US/Eastern"
orig = pd.Series(pd.date_range("2016-11-06", freq="H", periods=3, tz=tz))
assert orig.dtype == f"datetime64[ns, {tz}]"
diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py
index 5fe62f41e49ff..286ee91bc7d4f 100644
--- a/pandas/tseries/offsets.py
+++ b/pandas/tseries/offsets.py
@@ -435,7 +435,7 @@ def rollforward(self, dt):
def is_on_offset(self, dt):
if self.normalize and not _is_normalized(dt):
return False
- # XXX, see #1395
+ # TODO, see #1395
if type(self) == DateOffset or isinstance(self, Tick):
return True
| - changed XXX comments to TODO (much more grep-friendly, since we sometimes use XXX for a `name` attribute.
- Removed some now-fixed FIXME/TODO comments
- tests.arithmetic.test_datetime64, tests.arithmetic.test_period, test_conversion, tests.indexes.common, test_date_range, test_css, scalar.timedelta.test_arithmetic
- Added some TODO(EA2D) comments
- Removed some `TODO(wesm): unused?` comments | https://api.github.com/repos/pandas-dev/pandas/pulls/33858 | 2020-04-29T03:37:23Z | 2020-04-29T19:11:50Z | 2020-04-29T19:11:50Z | 2020-04-29T19:14:11Z |
ENH: Add na_value argument to DataFrame.to_numpy | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 9f0aaecacd383..34f6e2359a054 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -224,6 +224,7 @@ Other enhancements
such as ``dict`` and ``list``, mirroring the behavior of :meth:`DataFrame.update` (:issue:`33215`)
- :meth:`~pandas.core.groupby.GroupBy.transform` and :meth:`~pandas.core.groupby.GroupBy.aggregate` has gained ``engine`` and ``engine_kwargs`` arguments that supports executing functions with ``Numba`` (:issue:`32854`, :issue:`33388`)
- :meth:`~pandas.core.resample.Resampler.interpolate` now supports SciPy interpolation method :class:`scipy.interpolate.CubicSpline` as method ``cubicspline`` (:issue:`33670`)
+- :meth:`DataFrame.to_numpy` now supports the ``na_value`` keyword to control the NA sentinel in the output array (:issue:`33820`)
- The ``ExtensionArray`` class has now an :meth:`~pandas.arrays.ExtensionArray.equals`
method, similarly to :meth:`Series.equals` (:issue:`27081`).
- The minimum suppported dta version has increased to 105 in :meth:`~pandas.io.stata.read_stata` and :class:`~pandas.io.stata.StataReader` (:issue:`26667`).
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 445d168ff875d..31015e3095e7d 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1280,7 +1280,9 @@ def from_dict(cls, data, orient="columns", dtype=None, columns=None) -> "DataFra
return cls(data, index=index, columns=columns, dtype=dtype)
- def to_numpy(self, dtype=None, copy: bool = False) -> np.ndarray:
+ def to_numpy(
+ self, dtype=None, copy: bool = False, na_value=lib.no_default
+ ) -> np.ndarray:
"""
Convert the DataFrame to a NumPy array.
@@ -1301,6 +1303,11 @@ def to_numpy(self, dtype=None, copy: bool = False) -> np.ndarray:
another array. Note that ``copy=False`` does not *ensure* that
``to_numpy()`` is no-copy. Rather, ``copy=True`` ensure that
a copy is made, even if not strictly necessary.
+ na_value : Any, optional
+ The value to use for missing values. The default value depends
+ on `dtype` and the dtypes of the DataFrame columns.
+
+ .. versionadded:: 1.1.0
Returns
-------
@@ -1332,7 +1339,10 @@ def to_numpy(self, dtype=None, copy: bool = False) -> np.ndarray:
array([[1, 3.0, Timestamp('2000-01-01 00:00:00')],
[2, 4.5, Timestamp('2000-01-02 00:00:00')]], dtype=object)
"""
- result = np.array(self.values, dtype=dtype, copy=copy)
+ result = self._mgr.as_array(
+ transpose=self._AXIS_REVERSED, dtype=dtype, copy=copy, na_value=na_value
+ )
+
return result
def to_dict(self, orient="dict", into=dict):
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index 3b88edabe9eb0..4f6d84e52ea54 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -781,14 +781,28 @@ def copy_func(ax):
res.axes = new_axes
return res
- def as_array(self, transpose: bool = False) -> np.ndarray:
+ def as_array(
+ self,
+ transpose: bool = False,
+ dtype=None,
+ copy: bool = False,
+ na_value=lib.no_default,
+ ) -> np.ndarray:
"""
Convert the blockmanager data into an numpy array.
Parameters
----------
transpose : bool, default False
- If True, transpose the return array,
+ If True, transpose the return array.
+ dtype : object, default None
+ Data type of the return array.
+ copy : bool, default False
+ If True then guarantee that a copy is returned. A value of
+ False does not guarantee that the underlying data is not
+ copied.
+ na_value : object, default lib.no_default
+ Value to be used as the missing value sentinel.
Returns
-------
@@ -798,24 +812,41 @@ def as_array(self, transpose: bool = False) -> np.ndarray:
arr = np.empty(self.shape, dtype=float)
return arr.transpose() if transpose else arr
- if self._is_single_block and self.blocks[0].is_datetimetz:
- # TODO(Block.get_values): Make DatetimeTZBlock.get_values
- # always be object dtype. Some callers seem to want the
- # DatetimeArray (previously DTI)
- arr = self.blocks[0].get_values(dtype=object)
+ # We want to copy when na_value is provided to avoid
+ # mutating the original object
+ copy = copy or na_value is not lib.no_default
+
+ if self._is_single_block and self.blocks[0].is_extension:
+ # Avoid implicit conversion of extension blocks to object
+ arr = (
+ self.blocks[0]
+ .values.to_numpy(dtype=dtype, na_value=na_value)
+ .reshape(self.blocks[0].shape)
+ )
elif self._is_single_block or not self.is_mixed_type:
arr = np.asarray(self.blocks[0].get_values())
+ if dtype:
+ arr = arr.astype(dtype, copy=False)
else:
- arr = self._interleave()
+ arr = self._interleave(dtype=dtype, na_value=na_value)
+ # The underlying data was copied within _interleave
+ copy = False
+
+ if copy:
+ arr = arr.copy()
+
+ if na_value is not lib.no_default:
+ arr[isna(arr)] = na_value
return arr.transpose() if transpose else arr
- def _interleave(self) -> np.ndarray:
+ def _interleave(self, dtype=None, na_value=lib.no_default) -> np.ndarray:
"""
Return ndarray from blocks with specified item order
Items must be contained in the blocks
"""
- dtype = _interleaved_dtype(self.blocks)
+ if not dtype:
+ dtype = _interleaved_dtype(self.blocks)
# TODO: https://github.com/pandas-dev/pandas/issues/22791
# Give EAs some input on what happens here. Sparse needs this.
@@ -830,7 +861,12 @@ def _interleave(self) -> np.ndarray:
for blk in self.blocks:
rl = blk.mgr_locs
- result[rl.indexer] = blk.get_values(dtype)
+ if blk.is_extension:
+ # Avoid implicit conversion of extension blocks to object
+ arr = blk.values.to_numpy(dtype=dtype, na_value=na_value)
+ else:
+ arr = blk.get_values(dtype)
+ result[rl.indexer] = arr
itemmask[rl.indexer] = 1
if not itemmask.all():
diff --git a/pandas/tests/base/test_conversion.py b/pandas/tests/base/test_conversion.py
index e737a09b2ec6d..b688a048cbe8e 100644
--- a/pandas/tests/base/test_conversion.py
+++ b/pandas/tests/base/test_conversion.py
@@ -407,3 +407,48 @@ def test_to_numpy_kwargs_raises():
s = pd.Series([1, 2, 3], dtype="Int64")
with pytest.raises(TypeError, match=msg):
s.to_numpy(foo=True)
+
+
+@pytest.mark.parametrize(
+ "data",
+ [
+ {"a": [1, 2, 3], "b": [1, 2, None]},
+ {"a": np.array([1, 2, 3]), "b": np.array([1, 2, np.nan])},
+ {"a": pd.array([1, 2, 3]), "b": pd.array([1, 2, None])},
+ ],
+)
+@pytest.mark.parametrize("dtype, na_value", [(float, np.nan), (object, None)])
+def test_to_numpy_dataframe_na_value(data, dtype, na_value):
+ # https://github.com/pandas-dev/pandas/issues/33820
+ df = pd.DataFrame(data)
+ result = df.to_numpy(dtype=dtype, na_value=na_value)
+ expected = np.array([[1, 1], [2, 2], [3, na_value]], dtype=dtype)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "data, expected",
+ [
+ (
+ {"a": pd.array([1, 2, None])},
+ np.array([[1.0], [2.0], [np.nan]], dtype=float),
+ ),
+ (
+ {"a": [1, 2, 3], "b": [1, 2, 3]},
+ np.array([[1, 1], [2, 2], [3, 3]], dtype=float),
+ ),
+ ],
+)
+def test_to_numpy_dataframe_single_block(data, expected):
+ # https://github.com/pandas-dev/pandas/issues/33820
+ df = pd.DataFrame(data)
+ result = df.to_numpy(dtype=float, na_value=np.nan)
+ tm.assert_numpy_array_equal(result, expected)
+
+
+def test_to_numpy_dataframe_single_block_no_mutate():
+ # https://github.com/pandas-dev/pandas/issues/33820
+ result = pd.DataFrame(np.array([1.0, 2.0, np.nan]))
+ expected = pd.DataFrame(np.array([1.0, 2.0, np.nan]))
+ result.to_numpy(na_value=0.0)
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py
index 5cf74d3205a13..2b79fc8cd3406 100644
--- a/pandas/tests/frame/test_api.py
+++ b/pandas/tests/frame/test_api.py
@@ -365,7 +365,7 @@ def test_to_numpy_copy(self):
df = pd.DataFrame(arr)
assert df.values.base is arr
assert df.to_numpy(copy=False).base is arr
- assert df.to_numpy(copy=True).base is None
+ assert df.to_numpy(copy=True).base is not arr
def test_swapaxes(self):
df = DataFrame(np.random.randn(10, 5))
| - [x] closes #33820
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/33857 | 2020-04-29T01:28:37Z | 2020-05-13T15:51:29Z | 2020-05-13T15:51:29Z | 2020-05-13T15:57:03Z |
Requested Follow-Ups | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 597a0c5386cf0..823bfc75e4304 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -544,6 +544,7 @@ Datetimelike
- Bug in :meth:`DatetimeIndex.tz_localize` incorrectly retaining ``freq`` in some cases where the original freq is no longer valid (:issue:`30511`)
- Bug in :meth:`DatetimeIndex.intersection` losing ``freq`` and timezone in some cases (:issue:`33604`)
- Bug in :class:`DatetimeIndex` addition and subtraction with some types of :class:`DateOffset` objects incorrectly retaining an invalid ``freq`` attribute (:issue:`33779`)
+- Bug in :class:`DatetimeIndex` where setting the ``freq`` attribute on an index could silently change the ``freq`` attribute on another index viewing the same data (:issue:`33552`)
Timedelta
^^^^^^^^^
@@ -570,6 +571,7 @@ Numeric
- 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 :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`)
Conversion
^^^^^^^^^^
diff --git a/pandas/core/array_algos/transforms.py b/pandas/core/array_algos/transforms.py
index b8b234d937292..371425f325d76 100644
--- a/pandas/core/array_algos/transforms.py
+++ b/pandas/core/array_algos/transforms.py
@@ -10,9 +10,8 @@
def shift(values: np.ndarray, periods: int, axis: int, fill_value) -> np.ndarray:
new_values = values
- if periods == 0:
- # TODO: should we copy here?
- return new_values
+ if periods == 0 or values.size == 0:
+ return new_values.copy()
# make sure array sent to np.roll is c_contiguous
f_ordered = values.flags.f_contiguous
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index a091476640e07..de401368d55d7 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -1196,7 +1196,7 @@ def shift(self, periods, fill_value=None):
fill_value = self._validate_fill_value(fill_value)
- codes = shift(codes.copy(), periods, axis=0, fill_value=fill_value)
+ codes = shift(codes, periods, axis=0, fill_value=fill_value)
return self._constructor(codes, dtype=self.dtype, fastpath=True)
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 9d3ec284a2569..af7beb0b32be0 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -699,8 +699,6 @@ def _values_for_argsort(self):
@Appender(ExtensionArray.shift.__doc__)
def shift(self, periods=1, fill_value=None, axis=0):
- if not self.size or periods == 0:
- return self.copy()
fill_value = self._validate_shift_value(fill_value)
new_values = shift(self._data, periods, axis, fill_value)
@@ -745,7 +743,9 @@ def _validate_shift_value(self, fill_value):
# TODO(2.0): once this deprecation is enforced, used _validate_fill_value
if is_valid_nat_for_dtype(fill_value, self.dtype):
fill_value = NaT
- elif not isinstance(fill_value, self._recognized_scalars):
+ elif isinstance(fill_value, self._recognized_scalars):
+ fill_value = self._scalar_type(fill_value)
+ else:
# only warn if we're not going to raise
if self._scalar_type is Period and lib.is_integer(fill_value):
# kludge for #31971 since Period(integer) tries to cast to str
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index c40fad6b434d0..afca4ca86bd3f 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -2237,7 +2237,12 @@ def diff(self, n: int, axis: int = 0) -> List["Block"]:
# Cannot currently calculate diff across multiple blocks since this
# function is invoked via apply
raise NotImplementedError
- new_values = (self.values - self.shift(n, axis=axis)[0].values).asi8
+
+ if n == 0:
+ # Fastpath avoids making a copy in `shift`
+ new_values = np.zeros(self.values.shape, dtype=np.int64)
+ else:
+ new_values = (self.values - self.shift(n, axis=axis)[0].values).asi8
# Reshape the new_values like how algos.diff does for timedelta data
new_values = new_values.reshape(1, len(new_values))
diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py
index 7d80ad3d8c6be..804654451a6d9 100644
--- a/pandas/tests/arrays/test_datetimes.py
+++ b/pandas/tests/arrays/test_datetimes.py
@@ -374,6 +374,40 @@ def test_searchsorted_invalid_types(self, other, index):
with pytest.raises(TypeError, match=msg):
arr.searchsorted(other)
+ def test_shift_fill_value(self):
+ dti = pd.date_range("2016-01-01", periods=3)
+
+ dta = dti._data
+ expected = DatetimeArray(np.roll(dta._data, 1))
+
+ fv = dta[-1]
+ for fill_value in [fv, fv.to_pydatetime(), fv.to_datetime64()]:
+ result = dta.shift(1, fill_value=fill_value)
+ tm.assert_datetime_array_equal(result, expected)
+
+ dta = dta.tz_localize("UTC")
+ expected = expected.tz_localize("UTC")
+ fv = dta[-1]
+ for fill_value in [fv, fv.to_pydatetime()]:
+ result = dta.shift(1, fill_value=fill_value)
+ tm.assert_datetime_array_equal(result, expected)
+
+ def test_shift_value_tzawareness_mismatch(self):
+ dti = pd.date_range("2016-01-01", periods=3)
+
+ dta = dti._data
+
+ fv = dta[-1].tz_localize("UTC")
+ for invalid in [fv, fv.to_pydatetime()]:
+ with pytest.raises(TypeError, match="Cannot compare"):
+ dta.shift(1, fill_value=invalid)
+
+ dta = dta.tz_localize("UTC")
+ fv = dta[-1].tz_localize(None)
+ for invalid in [fv, fv.to_pydatetime(), fv.to_datetime64()]:
+ with pytest.raises(TypeError, match="Cannot compare"):
+ dta.shift(1, fill_value=invalid)
+
class TestSequenceToDT64NS:
def test_tz_dtype_mismatch_raises(self):
diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py
index 9c465e264d8a1..6af74b9a022b7 100644
--- a/pandas/tests/extension/base/methods.py
+++ b/pandas/tests/extension/base/methods.py
@@ -237,6 +237,13 @@ def test_container_shift(self, data, frame, periods, indices):
compare(result, expected)
+ def test_shift_0_periods(self, data):
+ # GH#33856 shifting with periods=0 should return a copy, not same obj
+ result = data.shift(0)
+ assert data[0] != data[1] # otherwise below is invalid
+ data[0] = data[1]
+ assert result[0] != result[1] # i.e. not the same object/view
+
@pytest.mark.parametrize("periods", [1, -2])
def test_diff(self, data, periods):
data = data[:5]
diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py
index 694bbee59606f..19ac25eb0ccf7 100644
--- a/pandas/tests/extension/test_sparse.py
+++ b/pandas/tests/extension/test_sparse.py
@@ -309,6 +309,13 @@ def test_searchsorted(self, data_for_sorting, as_series):
with tm.assert_produces_warning(PerformanceWarning):
super().test_searchsorted(data_for_sorting, as_series)
+ def test_shift_0_periods(self, data):
+ # GH#33856 shifting with periods=0 should return a copy, not same obj
+ result = data.shift(0)
+
+ data._sparse_values[0] = data._sparse_values[1]
+ assert result._sparse_values[0] != result._sparse_values[1]
+
class TestCasting(BaseSparseTests, base.BaseCastingTests):
def test_astype_object_series(self, all_data):
| https://api.github.com/repos/pandas-dev/pandas/pulls/33856 | 2020-04-28T23:43:51Z | 2020-04-30T13:08:59Z | 2020-04-30T13:08:59Z | 2020-04-30T14:43:51Z | |
TST: fix xfailed arithmetic tests | diff --git a/pandas/core/ops/dispatch.py b/pandas/core/ops/dispatch.py
index 637f0fa1d52e9..a7dcdd4f9d585 100644
--- a/pandas/core/ops/dispatch.py
+++ b/pandas/core/ops/dispatch.py
@@ -65,8 +65,12 @@ def should_series_dispatch(left, right, op):
ldtype = left.dtypes.iloc[0]
rdtype = right.dtypes.iloc[0]
- if (is_timedelta64_dtype(ldtype) and is_integer_dtype(rdtype)) or (
- is_timedelta64_dtype(rdtype) and is_integer_dtype(ldtype)
+ if (
+ is_timedelta64_dtype(ldtype)
+ and (is_integer_dtype(rdtype) or is_object_dtype(rdtype))
+ ) or (
+ is_timedelta64_dtype(rdtype)
+ and (is_integer_dtype(ldtype) or is_object_dtype(ldtype))
):
# numpy integer dtypes as timedelta64 dtypes in this scenario
return True
diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py
index b2ea6d8b92fdd..e3eec1f781948 100644
--- a/pandas/tests/arithmetic/test_timedelta64.py
+++ b/pandas/tests/arithmetic/test_timedelta64.py
@@ -541,9 +541,10 @@ def test_tda_add_sub_index(self):
expected = tdi - tdi
tm.assert_index_equal(result, expected)
- def test_tda_add_dt64_object_array(self, box_df_fail, tz_naive_fixture):
+ def test_tda_add_dt64_object_array(self, box_with_array, tz_naive_fixture):
# Result should be cast back to DatetimeArray
- box = box_df_fail
+ box = box_with_array
+
dti = pd.date_range("2016-01-01", periods=3, tz=tz_naive_fixture)
dti = dti._with_freq(None)
tdi = dti - dti
@@ -1396,33 +1397,40 @@ def test_td64arr_sub_offset_array(self, box_with_array):
res = tdi - other
tm.assert_equal(res, expected)
- def test_td64arr_with_offset_series(self, names, box_df_fail):
+ def test_td64arr_with_offset_series(self, names, box_with_array):
# GH#18849
- box = box_df_fail
+ box = box_with_array
box2 = Series if box in [pd.Index, tm.to_array] else box
- exname = names[2] if box is not tm.to_array else names[1]
+
+ if box is pd.DataFrame:
+ # Since we are operating with a DataFrame and a non-DataFrame,
+ # the non-DataFrame is cast to Series and its name ignored.
+ exname = names[0]
+ elif box is tm.to_array:
+ exname = names[1]
+ else:
+ exname = names[2]
tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"], name=names[0])
other = Series([pd.offsets.Hour(n=1), pd.offsets.Minute(n=-2)], name=names[1])
expected_add = Series([tdi[n] + other[n] for n in range(len(tdi))], name=exname)
- tdi = tm.box_expected(tdi, box)
+ obj = tm.box_expected(tdi, box)
expected_add = tm.box_expected(expected_add, box2)
with tm.assert_produces_warning(PerformanceWarning):
- res = tdi + other
+ res = obj + other
tm.assert_equal(res, expected_add)
with tm.assert_produces_warning(PerformanceWarning):
- res2 = other + tdi
+ res2 = other + obj
tm.assert_equal(res2, expected_add)
- # TODO: separate/parametrize add/sub test?
expected_sub = Series([tdi[n] - other[n] for n in range(len(tdi))], name=exname)
expected_sub = tm.box_expected(expected_sub, box2)
with tm.assert_produces_warning(PerformanceWarning):
- res3 = tdi - other
+ res3 = obj - other
tm.assert_equal(res3, expected_sub)
@pytest.mark.parametrize("obox", [np.array, pd.Index, pd.Series])
| https://api.github.com/repos/pandas-dev/pandas/pulls/33855 | 2020-04-28T23:27:31Z | 2020-04-29T20:53:31Z | 2020-04-29T20:53:31Z | 2020-04-29T20:56:07Z | |
TST: de-xfail, remove strict=False | diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py
index 8c937064c0493..6e116f56d1494 100644
--- a/pandas/tests/arithmetic/test_datetime64.py
+++ b/pandas/tests/arithmetic/test_datetime64.py
@@ -529,9 +529,9 @@ def test_dti_cmp_nat_behaves_like_float_cmp_nan(self):
"op",
[operator.eq, operator.ne, operator.gt, operator.ge, operator.lt, operator.le],
)
- def test_comparison_tzawareness_compat(self, op, box_df_fail):
+ def test_comparison_tzawareness_compat(self, op, box_with_array):
# GH#18162
- box = box_df_fail
+ box = box_with_array
dr = pd.date_range("2016-01-01", periods=6)
dz = dr.tz_localize("US/Pacific")
@@ -543,34 +543,35 @@ def test_comparison_tzawareness_compat(self, op, box_df_fail):
with pytest.raises(TypeError, match=msg):
op(dr, dz)
- # FIXME: DataFrame case fails to raise for == and !=, wrong
- # message for inequalities
+ if box is pd.DataFrame:
+ tolist = lambda x: x.astype(object).values.tolist()[0]
+ else:
+ tolist = list
+
with pytest.raises(TypeError, match=msg):
- op(dr, list(dz))
+ op(dr, tolist(dz))
with pytest.raises(TypeError, match=msg):
- op(dr, np.array(list(dz), dtype=object))
+ op(dr, np.array(tolist(dz), dtype=object))
with pytest.raises(TypeError, match=msg):
op(dz, dr)
- # FIXME: DataFrame case fails to raise for == and !=, wrong
- # message for inequalities
with pytest.raises(TypeError, match=msg):
- op(dz, list(dr))
+ op(dz, tolist(dr))
with pytest.raises(TypeError, match=msg):
- op(dz, np.array(list(dr), dtype=object))
+ op(dz, np.array(tolist(dr), dtype=object))
# The aware==aware and naive==naive comparisons should *not* raise
assert np.all(dr == dr)
- assert np.all(dr == list(dr))
- assert np.all(list(dr) == dr)
- assert np.all(np.array(list(dr), dtype=object) == dr)
- assert np.all(dr == np.array(list(dr), dtype=object))
+ assert np.all(dr == tolist(dr))
+ assert np.all(tolist(dr) == dr)
+ assert np.all(np.array(tolist(dr), dtype=object) == dr)
+ assert np.all(dr == np.array(tolist(dr), dtype=object))
assert np.all(dz == dz)
- assert np.all(dz == list(dz))
- assert np.all(list(dz) == dz)
- assert np.all(np.array(list(dz), dtype=object) == dz)
- assert np.all(dz == np.array(list(dz), dtype=object))
+ assert np.all(dz == tolist(dz))
+ assert np.all(tolist(dz) == dz)
+ assert np.all(np.array(tolist(dz), dtype=object) == dz)
+ assert np.all(dz == np.array(tolist(dz), dtype=object))
@pytest.mark.parametrize(
"op",
diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py
index b64a52a772419..b2ea6d8b92fdd 100644
--- a/pandas/tests/arithmetic/test_timedelta64.py
+++ b/pandas/tests/arithmetic/test_timedelta64.py
@@ -543,14 +543,15 @@ def test_tda_add_sub_index(self):
def test_tda_add_dt64_object_array(self, box_df_fail, tz_naive_fixture):
# Result should be cast back to DatetimeArray
+ box = box_df_fail
dti = pd.date_range("2016-01-01", periods=3, tz=tz_naive_fixture)
dti = dti._with_freq(None)
tdi = dti - dti
- obj = tm.box_expected(tdi, box_df_fail)
- other = tm.box_expected(dti, box_df_fail)
+ obj = tm.box_expected(tdi, box)
+ other = tm.box_expected(dti, box)
- warn = PerformanceWarning if box_df_fail is not pd.DataFrame else None
+ warn = PerformanceWarning if box is not pd.DataFrame else None
with tm.assert_produces_warning(warn):
result = obj + other.astype(object)
tm.assert_equal(result, other)
@@ -1195,9 +1196,11 @@ def test_td64arr_sub_td64_array(self, box_with_array):
result = tdarr - tdi
tm.assert_equal(result, expected)
- def test_td64arr_add_sub_tdi(self, box, names):
+ def test_td64arr_add_sub_tdi(self, box_with_array, names):
# GH#17250 make sure result dtype is correct
# GH#19043 make sure names are propagated correctly
+ box = box_with_array
+
if box is pd.DataFrame and names[1] != names[0]:
pytest.skip(
"Name propagation for DataFrame does not behave like "
@@ -1205,6 +1208,7 @@ def test_td64arr_add_sub_tdi(self, box, names):
)
tdi = TimedeltaIndex(["0 days", "1 day"], name=names[0])
+ tdi = np.array(tdi) if box is tm.to_array else tdi
ser = Series([Timedelta(hours=3), Timedelta(hours=4)], name=names[1])
expected = Series(
[Timedelta(hours=3), Timedelta(days=1, hours=4)], name=names[2]
@@ -1299,8 +1303,10 @@ def test_td64arr_sub_timedeltalike(self, two_hours, box_with_array):
# ------------------------------------------------------------------
# __add__/__sub__ with DateOffsets and arrays of DateOffsets
- def test_td64arr_add_offset_index(self, names, box):
+ def test_td64arr_add_offset_index(self, names, box_with_array):
# GH#18849, GH#19744
+ box = box_with_array
+
if box is pd.DataFrame and names[1] != names[0]:
pytest.skip(
"Name propagation for DataFrame does not behave like "
@@ -1309,6 +1315,7 @@ def test_td64arr_add_offset_index(self, names, box):
tdi = TimedeltaIndex(["1 days 00:00:00", "3 days 04:00:00"], name=names[0])
other = pd.Index([pd.offsets.Hour(n=1), pd.offsets.Minute(n=-2)], name=names[1])
+ other = np.array(other) if box is tm.to_array else other
expected = TimedeltaIndex(
[tdi[n] + other[n] for n in range(len(tdi))], freq="infer", name=names[2]
@@ -1347,16 +1354,13 @@ def test_td64arr_add_offset_array(self, box_with_array):
res2 = other + tdi
tm.assert_equal(res2, expected)
- @pytest.mark.parametrize(
- "names", [(None, None, None), ("foo", "bar", None), ("foo", "foo", "foo")]
- )
def test_td64arr_sub_offset_index(self, names, box_with_array):
# GH#18824, GH#19744
box = box_with_array
xbox = box if box is not tm.to_array else pd.Index
exname = names[2] if box is not tm.to_array else names[1]
- if box is pd.DataFrame and names[1] == "bar":
+ if box is pd.DataFrame and names[1] != names[0]:
pytest.skip(
"Name propagation for DataFrame does not behave like "
"it does for Index/Series"
@@ -1392,9 +1396,6 @@ def test_td64arr_sub_offset_array(self, box_with_array):
res = tdi - other
tm.assert_equal(res, expected)
- @pytest.mark.parametrize(
- "names", [(None, None, None), ("foo", "bar", None), ("foo", "foo", "foo")]
- )
def test_td64arr_with_offset_series(self, names, box_df_fail):
# GH#18849
box = box_df_fail
@@ -2030,9 +2031,13 @@ def test_td64arr_div_numeric_array(self, box_with_array, vector, any_real_dtype)
with pytest.raises(TypeError, match=pattern):
vector.astype(object) / tdser
- def test_td64arr_mul_int_series(self, box_df_fail, names):
+ def test_td64arr_mul_int_series(self, box_with_array, names, request):
# GH#19042 test for correct name attachment
- box = box_df_fail # broadcasts along wrong axis, but doesn't raise
+ box = box_with_array
+ if box_with_array is pd.DataFrame and names[2] is None:
+ reason = "broadcasts along wrong axis, but doesn't raise"
+ request.node.add_marker(pytest.mark.xfail(reason=reason))
+
exname = names[2] if box is not tm.to_array else names[1]
tdi = TimedeltaIndex(
@@ -2056,7 +2061,10 @@ def test_td64arr_mul_int_series(self, box_df_fail, names):
# The direct operation tdi * ser still needs to be fixed.
result = ser.__rmul__(tdi)
- tm.assert_equal(result, expected)
+ if box is pd.DataFrame:
+ assert result is NotImplemented
+ else:
+ tm.assert_equal(result, expected)
# TODO: Should we be parametrizing over types for `ser` too?
def test_float_series_rdiv_td64arr(self, box_with_array, names):
diff --git a/pandas/tests/extension/base/ops.py b/pandas/tests/extension/base/ops.py
index 4009041218ac2..d3b6472044ea5 100644
--- a/pandas/tests/extension/base/ops.py
+++ b/pandas/tests/extension/base/ops.py
@@ -29,8 +29,14 @@ def check_opname(self, s, op_name, other, exc=Exception):
def _check_op(self, s, op, other, op_name, exc=NotImplementedError):
if exc is None:
result = op(s, other)
- expected = s.combine(other, op)
- self.assert_series_equal(result, expected)
+ if isinstance(s, pd.DataFrame):
+ if len(s.columns) != 1:
+ raise NotImplementedError
+ expected = s.iloc[:, 0].combine(other, op).to_frame()
+ self.assert_frame_equal(result, expected)
+ else:
+ expected = s.combine(other, op)
+ self.assert_series_equal(result, expected)
else:
with pytest.raises(exc):
op(s, other)
diff --git a/pandas/tests/extension/test_boolean.py b/pandas/tests/extension/test_boolean.py
index e2331b69916fb..303764bff50b6 100644
--- a/pandas/tests/extension/test_boolean.py
+++ b/pandas/tests/extension/test_boolean.py
@@ -102,13 +102,15 @@ class TestMissing(base.BaseMissingTests):
class TestArithmeticOps(base.BaseArithmeticOpsTests):
+ implements = {"__sub__", "__rsub__"}
+
def check_opname(self, s, op_name, other, exc=None):
# overwriting to indicate ops don't raise an error
super().check_opname(s, op_name, other, exc=None)
def _check_op(self, s, op, other, op_name, exc=NotImplementedError):
if exc is None:
- if op_name in ("__sub__", "__rsub__"):
+ if op_name in self.implements:
# subtraction for bools raises TypeError (but not yet in 1.13)
if _np_version_under1p14:
pytest.skip("__sub__ does not yet raise in numpy 1.13")
@@ -151,6 +153,14 @@ def test_error(self, data, all_arithmetic_operators):
# other specific errors tested in the boolean array specific tests
pass
+ def test_arith_frame_with_scalar(self, data, all_arithmetic_operators):
+ # frame & scalar
+ op_name = all_arithmetic_operators
+ if op_name in self.implements:
+ super().test_arith_frame_with_scalar(data, all_arithmetic_operators)
+ else:
+ pytest.xfail("_reduce needs implementation")
+
class TestComparisonOps(base.BaseComparisonOpsTests):
def check_opname(self, s, op_name, other, exc=None):
diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py
index 059d3453995bd..91d7cea90e0b3 100644
--- a/pandas/tests/extension/test_categorical.py
+++ b/pandas/tests/extension/test_categorical.py
@@ -242,6 +242,14 @@ def test_consistent_casting(self, dtype, expected):
class TestArithmeticOps(base.BaseArithmeticOpsTests):
+ def test_arith_frame_with_scalar(self, data, all_arithmetic_operators):
+ # frame & scalar
+ op_name = all_arithmetic_operators
+ if op_name != "__rmod__":
+ super().test_arith_frame_with_scalar(data, all_arithmetic_operators)
+ else:
+ pytest.skip("rmod never called when string is first argument")
+
def test_arith_series_with_scalar(self, data, all_arithmetic_operators):
op_name = all_arithmetic_operators
diff --git a/pandas/tests/extension/test_datetime.py b/pandas/tests/extension/test_datetime.py
index 3aa188098620d..e026809f7e611 100644
--- a/pandas/tests/extension/test_datetime.py
+++ b/pandas/tests/extension/test_datetime.py
@@ -111,6 +111,15 @@ def test_array_interface(self, data):
class TestArithmeticOps(BaseDatetimeTests, base.BaseArithmeticOpsTests):
implements = {"__sub__", "__rsub__"}
+ def test_arith_frame_with_scalar(self, data, all_arithmetic_operators):
+ # frame & scalar
+ if all_arithmetic_operators in self.implements:
+ df = pd.DataFrame({"A": data})
+ self.check_opname(df, all_arithmetic_operators, data[0], exc=None)
+ else:
+ # ... but not the rest.
+ super().test_arith_frame_with_scalar(data, all_arithmetic_operators)
+
def test_arith_series_with_scalar(self, data, all_arithmetic_operators):
if all_arithmetic_operators in self.implements:
s = pd.Series(data)
diff --git a/pandas/tests/extension/test_period.py b/pandas/tests/extension/test_period.py
index c439b8b5ed319..11b41eedd5d51 100644
--- a/pandas/tests/extension/test_period.py
+++ b/pandas/tests/extension/test_period.py
@@ -84,6 +84,15 @@ class TestInterface(BasePeriodTests, base.BaseInterfaceTests):
class TestArithmeticOps(BasePeriodTests, base.BaseArithmeticOpsTests):
implements = {"__sub__", "__rsub__"}
+ def test_arith_frame_with_scalar(self, data, all_arithmetic_operators):
+ # frame & scalar
+ if all_arithmetic_operators in self.implements:
+ df = pd.DataFrame({"A": data})
+ self.check_opname(df, all_arithmetic_operators, data[0], exc=None)
+ else:
+ # ... but not the rest.
+ super().test_arith_frame_with_scalar(data, all_arithmetic_operators)
+
def test_arith_series_with_scalar(self, data, all_arithmetic_operators):
# we implement substitution...
if all_arithmetic_operators in self.implements:
diff --git a/pandas/tests/frame/test_cumulative.py b/pandas/tests/frame/test_cumulative.py
index 1b7e70dd28c63..248f3500c41df 100644
--- a/pandas/tests/frame/test_cumulative.py
+++ b/pandas/tests/frame/test_cumulative.py
@@ -7,9 +7,8 @@
"""
import numpy as np
-import pytest
-from pandas import DataFrame, Series, _is_numpy_dev
+from pandas import DataFrame, Series
import pandas._testing as tm
@@ -74,11 +73,6 @@ def test_cumprod(self, datetime_frame):
df.cumprod(0)
df.cumprod(1)
- @pytest.mark.xfail(
- _is_numpy_dev,
- reason="https://github.com/pandas-dev/pandas/issues/31992",
- strict=False,
- )
def test_cummin(self, datetime_frame):
datetime_frame.iloc[5:10, 0] = np.nan
datetime_frame.iloc[10:15, 1] = np.nan
@@ -102,11 +96,6 @@ def test_cummin(self, datetime_frame):
cummin_xs = datetime_frame.cummin(axis=1)
assert np.shape(cummin_xs) == np.shape(datetime_frame)
- @pytest.mark.xfail(
- _is_numpy_dev,
- reason="https://github.com/pandas-dev/pandas/issues/31992",
- strict=False,
- )
def test_cummax(self, datetime_frame):
datetime_frame.iloc[5:10, 0] = np.nan
datetime_frame.iloc[10:15, 1] = np.nan
diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py
index 8e4a7141875bb..781625f1f2ec9 100644
--- a/pandas/tests/groupby/test_categorical.py
+++ b/pandas/tests/groupby/test_categorical.py
@@ -3,7 +3,7 @@
import numpy as np
import pytest
-from pandas.compat import PY37
+from pandas.compat import PY37, is_platform_windows
import pandas as pd
from pandas import (
@@ -13,6 +13,7 @@
Index,
MultiIndex,
Series,
+ _np_version_under1p17,
qcut,
)
import pandas._testing as tm
@@ -210,7 +211,10 @@ def test_level_get_group(observed):
# GH#21636 flaky on py37; may be related to older numpy, see discussion
# https://github.com/MacPython/pandas-wheels/pull/64
-@pytest.mark.xfail(PY37, reason="Flaky, GH-27902", strict=False)
+@pytest.mark.xfail(
+ PY37 and _np_version_under1p17 and not is_platform_windows(),
+ reason="Flaky, GH-27902",
+)
@pytest.mark.parametrize("ordered", [True, False])
def test_apply(ordered):
# GH 10138
diff --git a/pandas/tests/io/parser/test_usecols.py b/pandas/tests/io/parser/test_usecols.py
index 979eb4702cc84..d4e049cc3fcc2 100644
--- a/pandas/tests/io/parser/test_usecols.py
+++ b/pandas/tests/io/parser/test_usecols.py
@@ -558,11 +558,13 @@ def test_raises_on_usecols_names_mismatch(all_parsers, usecols, kwargs, expected
tm.assert_frame_equal(result, expected)
-@pytest.mark.xfail(
- reason="see gh-16469: works on the C engine but not the Python engine", strict=False
-)
@pytest.mark.parametrize("usecols", [["A", "C"], [0, 2]])
-def test_usecols_subset_names_mismatch_orig_columns(all_parsers, usecols):
+def test_usecols_subset_names_mismatch_orig_columns(all_parsers, usecols, request):
+ if all_parsers.engine != "c":
+ reason = "see gh-16469: works on the C engine but not the Python engine"
+ # Number of passed names did not match number of header fields in the file
+ request.node.add_marker(pytest.mark.xfail(reason=reason, raises=ValueError))
+
data = "a,b,c,d\n1,2,3,4\n5,6,7,8"
names = ["A", "B", "C", "D"]
parser = all_parsers
diff --git a/pandas/tests/scalar/timedelta/test_arithmetic.py b/pandas/tests/scalar/timedelta/test_arithmetic.py
index eb22b715f9f4d..1663fa65c7dfe 100644
--- a/pandas/tests/scalar/timedelta/test_arithmetic.py
+++ b/pandas/tests/scalar/timedelta/test_arithmetic.py
@@ -419,7 +419,6 @@ def test_td_div_numeric_scalar(self):
_is_numpy_dev,
raises=RuntimeWarning,
reason="https://github.com/pandas-dev/pandas/issues/31992",
- strict=False,
),
),
float("nan"),
diff --git a/pandas/tests/series/test_cumulative.py b/pandas/tests/series/test_cumulative.py
index 259c5d53c5492..0b4c5f091106a 100644
--- a/pandas/tests/series/test_cumulative.py
+++ b/pandas/tests/series/test_cumulative.py
@@ -11,7 +11,6 @@
import pytest
import pandas as pd
-from pandas import _is_numpy_dev
import pandas._testing as tm
@@ -38,11 +37,6 @@ def test_cumsum(self, datetime_series):
def test_cumprod(self, datetime_series):
_check_accum_op("cumprod", datetime_series)
- @pytest.mark.xfail(
- _is_numpy_dev,
- reason="https://github.com/pandas-dev/pandas/issues/31992",
- strict=False,
- )
def test_cummin(self, datetime_series):
tm.assert_numpy_array_equal(
datetime_series.cummin().values,
@@ -56,11 +50,6 @@ def test_cummin(self, datetime_series):
result.index = result.index._with_freq(None)
tm.assert_series_equal(result, expected)
- @pytest.mark.xfail(
- _is_numpy_dev,
- reason="https://github.com/pandas-dev/pandas/issues/31992",
- strict=False,
- )
def test_cummax(self, datetime_series):
tm.assert_numpy_array_equal(
datetime_series.cummax().values,
diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py
index 57542aa3bc7f6..b671564eb77fe 100644
--- a/pandas/tests/test_downstream.py
+++ b/pandas/tests/test_downstream.py
@@ -69,6 +69,7 @@ def test_oo_optimizable():
@tm.network
# Cython import warning
+@pytest.mark.filterwarnings("ignore:pandas.util.testing is deprecated")
@pytest.mark.filterwarnings("ignore:can't:ImportWarning")
@pytest.mark.filterwarnings(
# patsy needs to update their imports
@@ -140,19 +141,19 @@ def test_pyarrow(df):
tm.assert_frame_equal(result, df)
-@pytest.mark.xfail(reason="pandas-wheels-50", strict=False)
def test_missing_required_dependency():
# GH 23868
# To ensure proper isolation, we pass these flags
# -S : disable site-packages
# -s : disable user site-packages
# -E : disable PYTHON* env vars, especially PYTHONPATH
- # And, that's apparently not enough, so we give up.
# https://github.com/MacPython/pandas-wheels/pull/50
- call = ["python", "-sSE", "-c", "import pandas"]
+
+ pyexe = sys.executable.replace("\\", "/")
+ call = [pyexe, "-sSE", "-c", "import pandas"]
msg = (
- r"Command '\['python', '-sSE', '-c', 'import pandas'\]' "
+ rf"Command '\['{pyexe}', '-sSE', '-c', 'import pandas'\]' "
"returned non-zero exit status 1."
)
diff --git a/pandas/tests/test_expressions.py b/pandas/tests/test_expressions.py
index fadab5d821470..b0a369ea65c94 100644
--- a/pandas/tests/test_expressions.py
+++ b/pandas/tests/test_expressions.py
@@ -363,8 +363,6 @@ def test_bool_ops_column_name_dtype(self, test_input, expected):
@pytest.mark.parametrize("axis", (0, 1))
def test_frame_series_axis(self, axis, arith):
# GH#26736 Dataframe.floordiv(Series, axis=1) fails
- if axis == 1 and arith == "floordiv":
- pytest.xfail("'floordiv' does not succeed with axis=1 #27636")
df = self.frame
if axis == 1:
diff --git a/pandas/tests/tseries/offsets/test_offsets_properties.py b/pandas/tests/tseries/offsets/test_offsets_properties.py
index 716d3ff3faf1c..082aa45f959ff 100644
--- a/pandas/tests/tseries/offsets/test_offsets_properties.py
+++ b/pandas/tests/tseries/offsets/test_offsets_properties.py
@@ -85,8 +85,6 @@
# Offset-specific behaviour tests
-# Based on CI runs: Always passes on OSX, fails on Linux, sometimes on Windows
-@pytest.mark.xfail(strict=False, reason="inconsistent between OSs, Pythons")
@given(gen_random_datetime, gen_yqm_offset)
def test_on_offset_implementations(dt, offset):
assume(not offset.normalize)
| https://api.github.com/repos/pandas-dev/pandas/pulls/33854 | 2020-04-28T20:45:13Z | 2020-04-29T19:38:11Z | 2020-04-29T19:38:11Z | 2020-04-29T19:52:22Z | |
CI: Skip permissions test when running as sudo | diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py
index 5bf9587a6ca22..55256499c6bb2 100644
--- a/pandas/tests/io/parser/test_common.py
+++ b/pandas/tests/io/parser/test_common.py
@@ -974,6 +974,15 @@ def test_no_permission(all_parsers):
msg = r"\[Errno 13\]"
with tm.ensure_clean() as path:
os.chmod(path, 0) # make file unreadable
+
+ # verify that this process cannot open the file (not running as sudo)
+ try:
+ with open(path):
+ pass
+ pytest.skip("Running as sudo.")
+ except PermissionError:
+ pass
+
with pytest.raises(PermissionError, match=msg) as e:
parser.read_csv(path)
assert path == e.value.filename
| Closes https://github.com/pandas-dev/pandas/issues/33210 | https://api.github.com/repos/pandas-dev/pandas/pulls/33847 | 2020-04-28T13:28:18Z | 2020-04-28T22:54:21Z | 2020-04-28T22:54:21Z | 2020-05-04T17:40:39Z |
BUG: Series construction with EA dtype and index but no data fails | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 55a53ba135275..47f67e9c2a4b3 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -752,7 +752,8 @@ Sparse
ExtensionArray
^^^^^^^^^^^^^^
-- Fixed bug where :meth:`Serires.value_counts` would raise on empty input of ``Int64`` dtype (:issue:`33317`)
+- Fixed bug where :meth:`Series.value_counts` would raise on empty input of ``Int64`` dtype (:issue:`33317`)
+- Fixed bug in :class:`Series` construction with EA dtype and index but no data or scalar data fails (:issue:`26469`)
- Fixed bug that caused :meth:`Series.__repr__()` to crash for extension types whose elements are multidimensional arrays (:issue:`33770`).
diff --git a/pandas/core/construction.py b/pandas/core/construction.py
index 351ef1d0429da..e6e26f0eec597 100644
--- a/pandas/core/construction.py
+++ b/pandas/core/construction.py
@@ -450,6 +450,11 @@ def sanitize_array(
subarr = _try_cast(arr, dtype, copy, raise_cast_failure)
elif isinstance(data, abc.Set):
raise TypeError("Set type is unordered")
+ elif lib.is_scalar(data) and index is not None and dtype is not None:
+ data = maybe_cast_to_datetime(data, dtype)
+ if not lib.is_scalar(data):
+ data = data[0]
+ subarr = construct_1d_arraylike_from_scalar(data, len(index), dtype)
else:
subarr = _try_cast(data, dtype, copy, raise_cast_failure)
@@ -516,7 +521,7 @@ def _try_cast(
Parameters
----------
- arr : ndarray, list, tuple, iterator (catchall)
+ arr : ndarray, scalar, list, tuple, iterator (catchall)
Excludes: ExtensionArray, Series, Index.
dtype : np.dtype, ExtensionDtype or None
copy : bool
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index ad307fd99ec9c..b91cfde45f079 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -1384,7 +1384,9 @@ def maybe_cast_to_datetime(value, dtype, errors: str = "raise"):
pass
# coerce datetimelike to object
- elif is_datetime64_dtype(value) and not is_datetime64_dtype(dtype):
+ elif is_datetime64_dtype(
+ getattr(value, "dtype", None)
+ ) and not is_datetime64_dtype(dtype):
if is_object_dtype(dtype):
if value.dtype != DT64NS_DTYPE:
value = value.astype(DT64NS_DTYPE)
diff --git a/pandas/tests/extension/arrow/test_bool.py b/pandas/tests/extension/arrow/test_bool.py
index 94dd09d3eb053..681c6f9a19dc5 100644
--- a/pandas/tests/extension/arrow/test_bool.py
+++ b/pandas/tests/extension/arrow/test_bool.py
@@ -1,6 +1,8 @@
import numpy as np
import pytest
+from pandas.compat import PY37
+
import pandas as pd
import pandas._testing as tm
from pandas.tests.extension import base
@@ -55,6 +57,18 @@ def test_from_dtype(self, data):
def test_from_sequence_from_cls(self, data):
super().test_from_sequence_from_cls(data)
+ @pytest.mark.skipif(not PY37, reason="timeout on Linux py36_locale")
+ @pytest.mark.xfail(reason="pa.NULL is not recognised as scalar, GH-33899")
+ def test_series_constructor_no_data_with_index(self, dtype, na_value):
+ # pyarrow.lib.ArrowInvalid: only handle 1-dimensional arrays
+ super().test_series_constructor_no_data_with_index(dtype, na_value)
+
+ @pytest.mark.skipif(not PY37, reason="timeout on Linux py36_locale")
+ @pytest.mark.xfail(reason="pa.NULL is not recognised as scalar, GH-33899")
+ def test_series_constructor_scalar_na_with_index(self, dtype, na_value):
+ # pyarrow.lib.ArrowInvalid: only handle 1-dimensional arrays
+ super().test_series_constructor_scalar_na_with_index(dtype, na_value)
+
class TestReduce(base.BaseNoReduceTests):
def test_reduce_series_boolean(self):
diff --git a/pandas/tests/extension/base/constructors.py b/pandas/tests/extension/base/constructors.py
index 1ddc7af0f6268..52e29cffc79c4 100644
--- a/pandas/tests/extension/base/constructors.py
+++ b/pandas/tests/extension/base/constructors.py
@@ -33,6 +33,31 @@ def test_series_constructor(self, data):
assert result2.dtype == data.dtype
assert isinstance(result2._mgr.blocks[0], ExtensionBlock)
+ def test_series_constructor_no_data_with_index(self, dtype, na_value):
+ result = pd.Series(index=[1, 2, 3], dtype=dtype)
+ expected = pd.Series([na_value] * 3, index=[1, 2, 3], dtype=dtype)
+ self.assert_series_equal(result, expected)
+
+ # GH 33559 - empty index
+ result = pd.Series(index=[], dtype=dtype)
+ expected = pd.Series([], index=pd.Index([], dtype="object"), dtype=dtype)
+ self.assert_series_equal(result, expected)
+
+ def test_series_constructor_scalar_na_with_index(self, dtype, na_value):
+ result = pd.Series(na_value, index=[1, 2, 3], dtype=dtype)
+ expected = pd.Series([na_value] * 3, index=[1, 2, 3], dtype=dtype)
+ self.assert_series_equal(result, expected)
+
+ def test_series_constructor_scalar_with_index(self, data, dtype):
+ scalar = data[0]
+ result = pd.Series(scalar, index=[1, 2, 3], dtype=dtype)
+ expected = pd.Series([scalar] * 3, index=[1, 2, 3], dtype=dtype)
+ self.assert_series_equal(result, expected)
+
+ result = pd.Series(scalar, index=["foo"], dtype=dtype)
+ expected = pd.Series([scalar], index=["foo"], dtype=dtype)
+ self.assert_series_equal(result, expected)
+
@pytest.mark.parametrize("from_series", [True, False])
def test_dataframe_constructor_from_dict(self, data, from_series):
if from_series:
diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py
index 745488770e09c..d79769208ab56 100644
--- a/pandas/tests/extension/json/test_json.py
+++ b/pandas/tests/extension/json/test_json.py
@@ -150,6 +150,21 @@ def test_from_dtype(self, data):
# construct from our dtype & string dtype
pass
+ @pytest.mark.xfail(reason="RecursionError, GH-33900")
+ def test_series_constructor_no_data_with_index(self, dtype, na_value):
+ # RecursionError: maximum recursion depth exceeded in comparison
+ super().test_series_constructor_no_data_with_index(dtype, na_value)
+
+ @pytest.mark.xfail(reason="RecursionError, GH-33900")
+ def test_series_constructor_scalar_na_with_index(self, dtype, na_value):
+ # RecursionError: maximum recursion depth exceeded in comparison
+ super().test_series_constructor_scalar_na_with_index(dtype, na_value)
+
+ @pytest.mark.xfail(reason="collection as scalar, GH-33901")
+ def test_series_constructor_scalar_with_index(self, data, dtype):
+ # TypeError: All values must be of type <class 'collections.abc.Mapping'>
+ super().test_series_constructor_scalar_with_index(data, dtype)
+
class TestReshaping(BaseJSON, base.BaseReshapingTests):
@pytest.mark.skip(reason="Different definitions of NA")
diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py
index 1c887cc4371b6..bb3595f4aef68 100644
--- a/pandas/tests/extension/test_numpy.py
+++ b/pandas/tests/extension/test_numpy.py
@@ -151,6 +151,11 @@ def test_array_from_scalars(self, data):
# ValueError: PandasArray must be 1-dimensional.
super().test_array_from_scalars(data)
+ @skip_nested
+ def test_series_constructor_scalar_with_index(self, data, dtype):
+ # ValueError: Length of passed values is 1, index implies 3.
+ super().test_series_constructor_scalar_with_index(data, dtype)
+
class TestDtype(BaseNumPyTests, base.BaseDtypeTests):
@pytest.mark.skip(reason="Incorrect expected.")
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index 22076eb05db88..85f47d0f6f5a4 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -1444,3 +1444,9 @@ def test_constructor_datetime64(self):
series = Series(dates)
assert np.issubdtype(series.dtype, np.dtype("M8[ns]"))
+
+ def test_constructor_datetimelike_scalar_to_string_dtype(self):
+ # https://github.com/pandas-dev/pandas/pull/33846
+ result = Series("M", index=[1, 2, 3], dtype="string")
+ expected = pd.Series(["M", "M", "M"], index=[1, 2, 3], dtype="string")
+ tm.assert_series_equal(result, expected)
| - [ ] closes #26469
- [ ] closes #33559
- [ ] 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/33846 | 2020-04-28T13:25:19Z | 2020-05-02T17:49:04Z | 2020-05-02T17:49:04Z | 2020-05-02T18:01:13Z |
Roll quantile support multiple quantiles as per #12093: rough sketch for discussion | diff --git a/TEMP_NOTES.md b/TEMP_NOTES.md
new file mode 100644
index 0000000000000..ef1ee3f1614f1
--- /dev/null
+++ b/TEMP_NOTES.md
@@ -0,0 +1,37 @@
+In [20]: s = pd.Series(np.random.randn(100000))
+
+In [21]: n = 10
+
+In [22]: q = np.linspace(1./n, 1 - 1./n, n - 1)
+
+In [23]: r = s.rolling(window=100)
+
+In [24]: %time a = pd.DataFrame({qq: r.quantile(qq) for qq in q})
+CPU times: user 333 ms, sys: 13.9 ms, total: 347 ms
+Wall time: 347 ms
+
+In [25]: %time b = r.quantile(q)
+CPU times: user 97.9 ms, sys: 7.96 ms, total: 106 ms
+Wall time: 106 ms
+
+In [26]: r = s.rolling(window=1000)
+
+In [27]: %time a = pd.DataFrame({qq: r.quantile(qq) for qq in q})
+CPU times: user 477 ms, sys: 9.32 ms, total: 486 ms
+Wall time: 486 ms
+
+In [28]: %time b = r.quantile(q)
+CPU times: user 148 ms, sys: 0 ns, total: 148 ms
+Wall time: 156 ms
+
+In [29]: n = 100
+
+In [30]: q = np.linspace(1./n, 1 - 1./n, n - 1)
+
+In [31]: %time a = pd.DataFrame({qq: r.quantile(qq) for qq in q})
+CPU times: user 5.33 s, sys: 41.7 ms, total: 5.38 s
+Wall time: 5.38 s
+
+In [32]: %time b = r.quantile(q)
+CPU times: user 1.25 s, sys: 25.6 ms, total: 1.28 s
+Wall time: 1.28 s
diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx
index ec4a412b5adc7..da49d1d6197a9 100644
--- a/pandas/_libs/window/aggregations.pyx
+++ b/pandas/_libs/window/aggregations.pyx
@@ -1218,22 +1218,22 @@ interpolation_types = {
def roll_quantile(ndarray[float64_t, cast=True] values, ndarray[int64_t] start,
ndarray[int64_t] end, int64_t minp, int64_t win,
- float64_t quantile, str interpolation):
+ ndarray[float64_t, cast=True] quantiles, str interpolation):
"""
O(N log(window)) implementation using skip list
"""
cdef:
float64_t val, prev, midpoint, idx_with_fraction
skiplist_t *skiplist
- int64_t nobs = 0, i, j, s, e, N = len(values)
+ int64_t nobs = 0, i, j, s, e, N = len(values), Nq = len(quantiles)
Py_ssize_t idx
- ndarray[float64_t] output
- float64_t vlow, vhigh
+ ndarray[float64_t, ndim=2] output
+ float64_t vlow, vhigh, quantile, tmp
InterpolationType interpolation_type
int ret = 0
- if quantile <= 0.0 or quantile >= 1.0:
- raise ValueError(f"quantile value {quantile} not in [0, 1]")
+ if np.min(quantiles) <= 0.0 or np.max(quantiles) >= 1.0:
+ raise ValueError(f"quantile value {quantiles} not in [0, 1]")
try:
interpolation_type = interpolation_types[interpolation]
@@ -1242,7 +1242,7 @@ def roll_quantile(ndarray[float64_t, cast=True] values, ndarray[int64_t] start,
# we use the Fixed/Variable Indexer here as the
# actual skiplist ops outweigh any window computation costs
- output = np.empty(N, dtype=float)
+ output = np.empty((N, Nq), dtype=float)
if win == 0 or (end - start).max() == 0:
output[:] = NaN
@@ -1282,49 +1282,55 @@ def roll_quantile(ndarray[float64_t, cast=True] values, ndarray[int64_t] start,
skiplist_remove(skiplist, val)
nobs -= 1
- if nobs >= minp:
- if nobs == 1:
- # Single value in skip list
- output[i] = skiplist_get(skiplist, 0, &ret)
- else:
- idx_with_fraction = quantile * (nobs - 1)
- idx = <int>idx_with_fraction
-
- if idx_with_fraction == idx:
- # no need to interpolate
- output[i] = skiplist_get(skiplist, idx, &ret)
- continue
-
- if interpolation_type == LINEAR:
- vlow = skiplist_get(skiplist, idx, &ret)
- vhigh = skiplist_get(skiplist, idx + 1, &ret)
- output[i] = ((vlow + (vhigh - vlow) *
- (idx_with_fraction - idx)))
- elif interpolation_type == LOWER:
- output[i] = skiplist_get(skiplist, idx, &ret)
- elif interpolation_type == HIGHER:
- output[i] = skiplist_get(skiplist, idx + 1, &ret)
- elif interpolation_type == NEAREST:
- # the same behaviour as round()
- if idx_with_fraction - idx == 0.5:
- if idx % 2 == 0:
- output[i] = skiplist_get(skiplist, idx, &ret)
+ for j in range(0, Nq):
+ if nobs >= minp:
+ if nobs == 1:
+ # Single value in skip list
+ tmp = skiplist_get(skiplist, 0, &ret)
+ output[i, j] = tmp
+ else:
+ quantile = quantiles[j]
+ idx_with_fraction = quantile * (nobs - 1)
+ idx = <int>idx_with_fraction
+
+ if idx_with_fraction == idx:
+ # no need to interpolate
+ output[i, j] = skiplist_get(skiplist, idx, &ret)
+ continue
+
+ if interpolation_type == LINEAR:
+ vlow = skiplist_get(skiplist, idx, &ret)
+ vhigh = skiplist_get(skiplist, idx + 1, &ret)
+ output[i, j] = ((vlow + (vhigh - vlow) *
+ (idx_with_fraction - idx)))
+ elif interpolation_type == LOWER:
+ output[i, j] = skiplist_get(skiplist, idx, &ret)
+ elif interpolation_type == HIGHER:
+ output[i, j] = skiplist_get(skiplist, idx + 1, &ret)
+ elif interpolation_type == NEAREST:
+ # the same behaviour as round()
+ if idx_with_fraction - idx == 0.5:
+ if idx % 2 == 0:
+ output[i, j] = skiplist_get(skiplist, idx, &ret)
+ else:
+ output[i, j] = skiplist_get(
+ skiplist, idx + 1, &ret)
+ elif idx_with_fraction - idx < 0.5:
+ output[i, j] = skiplist_get(skiplist, idx, &ret)
else:
- output[i] = skiplist_get(
- skiplist, idx + 1, &ret)
- elif idx_with_fraction - idx < 0.5:
- output[i] = skiplist_get(skiplist, idx, &ret)
- else:
- output[i] = skiplist_get(skiplist, idx + 1, &ret)
- elif interpolation_type == MIDPOINT:
- vlow = skiplist_get(skiplist, idx, &ret)
- vhigh = skiplist_get(skiplist, idx + 1, &ret)
- output[i] = <float64_t>(vlow + vhigh) / 2
- else:
- output[i] = NaN
+ output[i, j] = skiplist_get(skiplist, idx + 1, &ret)
+ elif interpolation_type == MIDPOINT:
+ vlow = skiplist_get(skiplist, idx, &ret)
+ vhigh = skiplist_get(skiplist, idx + 1, &ret)
+ output[i, j] = <float64_t>(vlow + vhigh) / 2
+ else:
+ output[i, j] = NaN
skiplist_destroy(skiplist)
+ if Nq == 1:
+ return output[:, 0]
+
return output
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index 8cb53ebd92214..dac1e2b29e8af 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -5,6 +5,7 @@
from datetime import timedelta
from functools import partial
import inspect
+import itertools
from textwrap import dedent
from typing import Callable, Dict, List, Optional, Set, Tuple, Type, Union
@@ -363,7 +364,7 @@ def _prep_values(self, values: Optional[np.ndarray] = None) -> np.ndarray:
return values
- def _wrap_result(self, result, block=None, obj=None):
+ def _wrap_result(self, result, block=None, obj=None, columns=None):
"""
Wrap a single result.
"""
@@ -377,11 +378,30 @@ def _wrap_result(self, result, block=None, obj=None):
from pandas import Series
return Series(result, index, name=obj.name)
+ elif result.ndim == 2 and columns is not None:
+ from pandas import DataFrame
+
+ df = DataFrame(result, index, columns=columns)
+ if isinstance(obj, DataFrame):
+ pass
+ else:
+ df.columns.name = obj.name
+ return df
+ elif (
+ result.ndim == 3 and columns is not None
+ ): # index x quantiles x columns for example
+ from pandas import DataFrame, MultiIndex
+
+ result = result.reshape(100, 2 * 3, order="F")
+ cols = MultiIndex.from_tuples(itertools.product(block.columns, columns))
+ return DataFrame(result, index=index, columns=cols)
return type(obj)(result, index=index, columns=block.columns)
return result
- def _wrap_results(self, results, blocks, obj, exclude=None) -> FrameOrSeries:
+ def _wrap_results(
+ self, results, blocks, obj, exclude=None, columns=None
+ ) -> FrameOrSeries:
"""
Wrap the results.
@@ -397,11 +417,17 @@ def _wrap_results(self, results, blocks, obj, exclude=None) -> FrameOrSeries:
final = []
for result, block in zip(results, blocks):
- result = self._wrap_result(result, block=block, obj=obj)
+ result = self._wrap_result(result, block=block, obj=obj, columns=columns)
if result.ndim == 1:
return result
+ elif result.ndim == 2 and columns is not None:
+ # I have no idea what this ndim switch case above is but
+ # this case *currently* corresponds to quantile
+ return result
final.append(result)
+ print(type(self._selected_obj))
+
# if we have an 'on' column
# we want to put it back into the results
# in the same location
@@ -595,8 +621,16 @@ def calc(x):
result = self._center_window(result, window)
results.append(result)
-
- return self._wrap_results(results, block_list, obj, exclude)
+ columns = None
+ # func is a functools.partial. Let's abuse this for now.
+ # this getattr madness is because of awful mypy
+ func_name = getattr(func, "func", func).__name__
+ if func_name == "roll_quantile":
+ keywords = getattr(func, "keywords", None)
+ if keywords is not None:
+ if not is_scalar(keywords["quantiles"]):
+ columns = keywords["quantiles"]
+ return self._wrap_results(results, block_list, obj, exclude, columns=columns)
def aggregate(self, func, *args, **kwargs):
result, how = self._aggregate(func, *args, **kwargs)
@@ -1683,15 +1717,17 @@ def kurt(self, **kwargs):
)
def quantile(self, quantile, interpolation="linear", **kwargs):
- if quantile == 1.0:
+ if is_scalar(quantile) and quantile == 1.0:
window_func = self._get_cython_func_type("roll_max")
- elif quantile == 0.0:
+ elif is_scalar(quantile) and quantile == 0.0:
window_func = self._get_cython_func_type("roll_min")
else:
+ if is_scalar(quantile):
+ quantile = np.atleast_1d(quantile)
window_func = partial(
self._get_roll_func("roll_quantile"),
win=self._get_window(),
- quantile=quantile,
+ quantiles=quantile,
interpolation=interpolation,
)
@@ -1748,9 +1784,12 @@ def _get_cov(X, Y):
# to avoid potential overflow, cast the data to float64
X = X.astype("float64")
Y = Y.astype("float64")
- mean = lambda x: x.rolling(
- window, self.min_periods, center=self.center
- ).mean(**kwargs)
+
+ def mean(x):
+ return x.rolling(window, self.min_periods, center=self.center).mean(
+ **kwargs
+ )
+
count = (
(X + Y)
.rolling(window=window, min_periods=0, center=self.center)
| - [ ] closes #12093
Putting this in a PR for discussion. It definitely needs more work on kicking the arguments through properly in the python interface but someone who has strong opinions about that can hopefully step in and then will refactor and test etc.
The "content" is really just the cython change.
| https://api.github.com/repos/pandas-dev/pandas/pulls/33843 | 2020-04-28T09:34:20Z | 2020-11-26T01:25:19Z | null | 2020-11-26T01:25:19Z |
DOC: Fix groupby.agg/transform API reference and add numba arguments to documentation | diff --git a/doc/source/reference/groupby.rst b/doc/source/reference/groupby.rst
index 921eb737aef07..201e33c2fd0ee 100644
--- a/doc/source/reference/groupby.rst
+++ b/doc/source/reference/groupby.rst
@@ -35,9 +35,12 @@ Function application
:toctree: api/
GroupBy.apply
- GroupBy.agg
- GroupBy.aggregate
- GroupBy.transform
+ SeriesGroupBy.agg
+ DataFrameGroupBy.agg
+ SeriesGroupBy.aggregate
+ DataFrameGroupBy.aggregate
+ SeriesGroupBy.transform
+ DataFrameGroupBy.transform
GroupBy.pipe
Computations / descriptive stats
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 4b4801f4e8c58..f360c66804889 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -7105,6 +7105,9 @@ def _gotitem(
see_also=_agg_summary_and_see_also_doc,
examples=_agg_examples_doc,
versionadded="\n.. versionadded:: 0.20.0\n",
+ numba_func_notes="",
+ numba_args="",
+ numba_notes="",
**_shared_doc_kwargs,
)
@Appender(_shared_docs["aggregate"])
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index b550857252466..4b03823b88cbc 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -5071,12 +5071,16 @@ def pipe(self, func, *args, **kwargs):
Function to use for aggregating the data. If a function, must either
work when passed a %(klass)s or when passed to %(klass)s.apply.
+ %(numba_func_notes)s
+
Accepted combinations are:
- function
- string function name
- list of functions and/or function names, e.g. ``[np.sum, 'mean']``
- dict of axis labels -> functions, function names or list of such.
+
+ %(numba_args)s
%(axis)s
*args
Positional arguments to pass to `func`.
@@ -5100,6 +5104,7 @@ def pipe(self, func, *args, **kwargs):
`agg` is an alias for `aggregate`. Use the alias.
A passed user-defined-function will be passed a Series for evaluation.
+ %(numba_notes)s
%(examples)s"""
)
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index ddf553dd1dd62..0cd73cc56470f 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -80,6 +80,9 @@
check_kwargs_and_nopython,
get_jit_arguments,
jit_user_function,
+ numba_groupby_args,
+ numba_groupby_func_notes,
+ numba_groupby_notes,
split_for_numba,
validate_udf,
)
@@ -181,9 +184,9 @@ def _selection_name(self):
"""
See Also
--------
- pandas.Series.groupby.apply
- pandas.Series.groupby.transform
- pandas.Series.aggregate
+ Series.groupby.apply
+ Series.groupby.transform
+ Series.aggregate
"""
)
@@ -242,6 +245,9 @@ def apply(self, func, *args, **kwargs):
versionadded="",
klass="Series",
axis="",
+ numba_func_notes=numba_groupby_func_notes,
+ numba_args=numba_groupby_args,
+ numba_notes=numba_groupby_notes,
)
@Appender(_shared_docs["aggregate"])
def aggregate(
@@ -476,7 +482,7 @@ def _aggregate_named(self, func, *args, **kwargs):
return result
- @Substitution(klass="Series", selected="A.")
+ @Substitution(klass="Series")
@Appender(_transform_template)
def transform(self, func, *args, engine="cython", engine_kwargs=None, **kwargs):
func = self._get_cython_func(func) or func
@@ -858,9 +864,9 @@ class DataFrameGroupBy(GroupBy[DataFrame]):
"""
See Also
--------
- pandas.DataFrame.groupby.apply
- pandas.DataFrame.groupby.transform
- pandas.DataFrame.aggregate
+ DataFrame.groupby.apply
+ DataFrame.groupby.transform
+ DataFrame.aggregate
"""
)
@@ -946,6 +952,9 @@ class DataFrameGroupBy(GroupBy[DataFrame]):
versionadded="",
klass="DataFrame",
axis="",
+ numba_func_notes=numba_groupby_func_notes,
+ numba_args=numba_groupby_args,
+ numba_notes=numba_groupby_notes,
)
@Appender(_shared_docs["aggregate"])
def aggregate(
@@ -1466,7 +1475,7 @@ def _transform_general(
concatenated = concatenated.reindex(concat_index, axis=other_axis, copy=False)
return self._set_result_index_ordered(concatenated)
- @Substitution(klass="DataFrame", selected="")
+ @Substitution(klass="DataFrame")
@Appender(_transform_template)
def transform(self, func, *args, engine="cython", engine_kwargs=None, **kwargs):
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 6924c7d320bc4..50fac4753eda7 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -310,14 +310,17 @@ class providing the base-class of operations.
* f must not mutate groups. Mutation is not supported and may
produce unexpected results.
+When using ``engine='numba'``, there will be no "fall back" behavior internally.
+The group data and group index will be passed as numpy arrays to the JITed
+user defined function, and no alternative execution attempts will be tried.
+
Examples
--------
-# Same shape
>>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
... 'foo', 'bar'],
... 'B' : ['one', 'one', 'two', 'three',
-... 'two', 'two'],
+... 'two', 'two'],
... 'C' : [1, 5, 5, 2, 5, 5],
... 'D' : [2.0, 5., 8., 1., 2., 9.]})
>>> grouped = df.groupby('A')
@@ -330,7 +333,8 @@ class providing the base-class of operations.
4 0.577350 -0.577350
5 0.577350 1.000000
-# Broadcastable
+Broadcast result of the transformation
+
>>> grouped.transform(lambda x: x.max() - x.min())
C D
0 4 6.0
diff --git a/pandas/core/resample.py b/pandas/core/resample.py
index 06751d9c35fab..3feee63bfa05c 100644
--- a/pandas/core/resample.py
+++ b/pandas/core/resample.py
@@ -273,6 +273,9 @@ def pipe(self, func, *args, **kwargs):
versionadded="",
klass="DataFrame",
axis="",
+ numba_func_notes="",
+ numba_args="",
+ numba_notes="",
)
@Appender(_shared_docs["aggregate"])
def aggregate(self, func, *args, **kwargs):
diff --git a/pandas/core/series.py b/pandas/core/series.py
index eb409b432f89c..36a17a70c7b24 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -3809,6 +3809,9 @@ def _gotitem(self, key, ndim, subset=None) -> "Series":
see_also=_agg_see_also_doc,
examples=_agg_examples_doc,
versionadded="\n.. versionadded:: 0.20.0\n",
+ numba_func_notes="",
+ numba_args="",
+ numba_notes="",
**_shared_doc_kwargs,
)
@Appender(generic._shared_docs["aggregate"])
diff --git a/pandas/core/util/numba_.py b/pandas/core/util/numba_.py
index c2e4b38ad5b4d..4b56e6bcf6386 100644
--- a/pandas/core/util/numba_.py
+++ b/pandas/core/util/numba_.py
@@ -13,6 +13,39 @@
NUMBA_FUNC_CACHE: Dict[Tuple[Callable, str], Callable] = dict()
+numba_groupby_func_notes = """
+ If the ``'numba'`` engine is chosen, the function must be
+ a user defined function with ``values`` and ``index`` as the
+ first and second arguments respectively in the function signature.
+ Each group's index will be passed to the user defined function
+ and optionally available for use.
+
+ .. versionchanged:: 1.1.0"""
+numba_groupby_args = """
+
+ engine : str, default 'cython'
+
+ * ``'cython'`` : Runs the function through C-extensions from cython.
+ * ``'numba'`` : Runs the function through JIT compiled code from numba.
+
+ .. versionadded:: 1.1.0
+
+ engine_kwargs : dict, default None
+
+ * For ``'cython'`` engine, there are no accepted ``engine_kwargs``
+ * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil``
+ and ``parallel`` dictionary keys. The values must either be ``True`` or
+ ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is
+ ``{'nopython': True, 'nogil': False, 'parallel': False}`` and will be
+ applied to the function
+
+ .. versionadded:: 1.1.0"""
+numba_groupby_notes = """
+ When using ``engine='numba'``, there will be no "fall back" behavior internally.
+ The group data and group index will be passed as numpy arrays to the JITed
+ user defined function, and no alternative execution attempts will be tried."""
+
+
def check_kwargs_and_nopython(
kwargs: Optional[Dict] = None, nopython: Optional[bool] = None
) -> None:
diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py
index 2759280dc1d1c..5530a56d437be 100644
--- a/pandas/core/window/ewm.py
+++ b/pandas/core/window/ewm.py
@@ -188,6 +188,9 @@ def _constructor(self):
versionadded="",
klass="Series/Dataframe",
axis="",
+ numba_func_notes="",
+ numba_args="",
+ numba_notes="",
)
@Appender(_shared_docs["aggregate"])
def aggregate(self, func, *args, **kwargs):
diff --git a/pandas/core/window/expanding.py b/pandas/core/window/expanding.py
index 146c139806bca..5980b496d28b6 100644
--- a/pandas/core/window/expanding.py
+++ b/pandas/core/window/expanding.py
@@ -120,6 +120,9 @@ def _get_window(self, other=None, **kwargs):
versionadded="",
klass="Series/Dataframe",
axis="",
+ numba_func_notes="",
+ numba_args="",
+ numba_notes="",
)
@Appender(_shared_docs["aggregate"])
def aggregate(self, func, *args, **kwargs):
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index 6c775953e18db..e4bd98fa8ba6c 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -1070,6 +1070,9 @@ def _get_window(
versionadded="",
klass="Series/DataFrame",
axis="",
+ numba_func_notes="",
+ numba_args="",
+ numba_notes="",
)
@Appender(_shared_docs["aggregate"])
def aggregate(self, func, *args, **kwargs):
@@ -1937,6 +1940,9 @@ def _validate_freq(self):
versionadded="",
klass="Series/Dataframe",
axis="",
+ numba_func_notes="",
+ numba_args="",
+ numba_notes="",
)
@Appender(_shared_docs["aggregate"])
def aggregate(self, func, *args, **kwargs):
| - xref https://github.com/pandas-dev/pandas/pull/33388#issuecomment-618808443
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
<img width="927" alt="Screen Shot 2020-04-27 at 11 19 16 PM" src="https://user-images.githubusercontent.com/10647082/80453833-e20eeb80-88dd-11ea-9acc-ef322cb59df5.png">
<img width="934" alt="Screen Shot 2020-04-27 at 11 19 33 PM" src="https://user-images.githubusercontent.com/10647082/80453838-e4714580-88dd-11ea-85b2-735d327ee686.png">
<img width="922" alt="Screen Shot 2020-04-27 at 11 19 53 PM" src="https://user-images.githubusercontent.com/10647082/80453844-e6d39f80-88dd-11ea-8c49-a9d35fd80e0c.png">
<img width="927" alt="Screen Shot 2020-04-27 at 11 20 16 PM" src="https://user-images.githubusercontent.com/10647082/80453851-e935f980-88dd-11ea-8c62-b92043ed26e4.png">
| https://api.github.com/repos/pandas-dev/pandas/pulls/33840 | 2020-04-28T06:22:51Z | 2020-04-29T03:42:04Z | null | 2020-04-29T03:42:13Z |
CLN: freq inference in DTI/TDI set ops | diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index decb17cdf6672..fe48f05820a4a 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -2,7 +2,7 @@
Base and utility classes for tseries type pandas objects.
"""
from datetime import datetime
-from typing import Any, List, Optional, Union, cast
+from typing import Any, List, Optional, TypeVar, Union, cast
import numpy as np
@@ -45,6 +45,8 @@
_index_doc_kwargs = dict(ibase._index_doc_kwargs)
+_T = TypeVar("_T", bound="DatetimeIndexOpsMixin")
+
def _join_i8_wrapper(joinf, with_indexers: bool = True):
"""
@@ -655,13 +657,7 @@ def intersection(self, other, sort=False):
result = result._with_freq("infer")
return result
- elif (
- other.freq is None
- or self.freq is None
- or other.freq != self.freq
- or not other.freq.is_anchored()
- or (not self.is_monotonic or not other.is_monotonic)
- ):
+ elif not self._can_fast_intersect(other):
result = Index.intersection(self, other, sort=sort)
result = result._with_freq("infer")
return result
@@ -684,7 +680,28 @@ def intersection(self, other, sort=False):
left_chunk = left._values[lslice]
return self._shallow_copy(left_chunk)
- def _can_fast_union(self, other) -> bool:
+ def _can_fast_intersect(self: _T, other: _T) -> bool:
+ if self.freq is None:
+ return False
+
+ if other.freq != self.freq:
+ return False
+
+ if not self.is_monotonic_increasing:
+ # Because freq is not None, we must then be monotonic decreasing
+ return False
+
+ if not self.freq.is_anchored():
+ # If freq is not anchored, then despite having matching freqs,
+ # we might not "line up"
+ return False
+
+ return True
+
+ def _can_fast_union(self: _T, other: _T) -> bool:
+ # Assumes that type(self) == type(other), as per the annotation
+ # The ability to fast_union also implies that `freq` should be
+ # retained on union.
if not isinstance(other, type(self)):
return False
@@ -693,7 +710,9 @@ def _can_fast_union(self, other) -> bool:
if freq is None or freq != other.freq:
return False
- if not self.is_monotonic or not other.is_monotonic:
+ if not self.is_monotonic_increasing:
+ # Because freq is not None, we must then be monotonic decreasing
+ # TODO: do union on the reversed indexes?
return False
if len(self) == 0 or len(other) == 0:
@@ -709,12 +728,7 @@ def _can_fast_union(self, other) -> bool:
left_end = left[-1]
# Only need to "adjoin", not overlap
- try:
- return (right_start == left_end + freq) or right_start in left
- except ValueError:
- # if we are comparing a freq that does not propagate timezones
- # this will raise
- return False
+ return (right_start == left_end + freq) or right_start in left
def _fast_union(self, other, sort=None):
if len(other) == 0:
@@ -734,7 +748,7 @@ def _fast_union(self, other, sort=None):
loc = right.searchsorted(left_start, side="left")
right_chunk = right._values[:loc]
dates = concat_compat((left._values, right_chunk))
- # TODO: can we infer that it has self.freq?
+ # With sort being False, we can't infer that result.freq == self.freq
result = self._shallow_copy(dates)._with_freq("infer")
return result
else:
@@ -748,8 +762,10 @@ def _fast_union(self, other, sort=None):
loc = right.searchsorted(left_end, side="right")
right_chunk = right._values[loc:]
dates = concat_compat([left._values, right_chunk])
- # TODO: can we infer that it has self.freq?
- result = self._shallow_copy(dates)._with_freq("infer")
+ # The can_fast_union check ensures that the result.freq
+ # should match self.freq
+ dates = type(self._data)(dates, freq=self.freq)
+ result = type(self)._simple_new(dates, name=self.name)
return result
else:
return left
@@ -766,6 +782,8 @@ def _union(self, other, sort):
if this._can_fast_union(other):
result = this._fast_union(other, sort=sort)
if result.freq is None:
+ # In the case where sort is None, _can_fast_union
+ # implies that result.freq should match self.freq
result = result._with_freq("infer")
return result
else:
| These ops are a PITA for getting the freq check into assert_index_equal. I'm leaning towards ripping out the freq="infer" behavior in all the cases where we can't fast-infer it. | https://api.github.com/repos/pandas-dev/pandas/pulls/33839 | 2020-04-28T03:46:04Z | 2020-04-29T20:10:26Z | 2020-04-29T20:10:26Z | 2020-04-29T20:52:51Z |
teaching someone this | diff --git a/web/pandas_web.py b/web/pandas_web.py
index e62deaa8cdc7f..58efd950bfe25 100755
--- a/web/pandas_web.py
+++ b/web/pandas_web.py
@@ -9,6 +9,7 @@
The file should contain:
```
+fuck pandas
main:
template_path: <path_to_the_jinja2_templates_directory>
base_template: <template_file_all_other_files_will_extend>
| sorry guys, i was teaching my friend... Dont ban me please. | https://api.github.com/repos/pandas-dev/pandas/pulls/33837 | 2020-04-28T01:23:36Z | 2020-04-28T01:24:24Z | null | 2020-04-28T01:24:41Z |
BUG: preserve freq in DTI/TDI factorize | diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index eca1733b61a52..7ac9cef0d2412 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -184,8 +184,16 @@ def _reconstruct_data(values, dtype, original):
-------
Index for extension types, otherwise ndarray casted to dtype
"""
+ if isinstance(values, ABCExtensionArray) and values.dtype == dtype:
+ # Catch DatetimeArray/TimedeltaArray
+ return values
+
if is_extension_array_dtype(dtype):
- values = dtype.construct_array_type()._from_sequence(values)
+ cls = dtype.construct_array_type()
+ if isinstance(values, cls) and values.dtype == dtype:
+ return values
+
+ values = cls._from_sequence(values)
elif is_bool_dtype(dtype):
values = values.astype(dtype, copy=False)
@@ -613,9 +621,11 @@ def factorize(
values = _ensure_arraylike(values)
original = values
+ if not isinstance(values, ABCMultiIndex):
+ values = extract_array(values, extract_numpy=True)
- if is_extension_array_dtype(values.dtype):
- values = extract_array(values)
+ if isinstance(values, ABCExtensionArray):
+ # Includes DatetimeArray, TimedeltaArray
codes, uniques = values.factorize(na_sentinel=na_sentinel)
dtype = original.dtype
else:
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index c325ec0d0bf7c..22ffd00ca1393 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -437,6 +437,13 @@ def _with_freq(self, freq):
arr._freq = freq
return arr
+ def factorize(self, na_sentinel=-1):
+ if self.freq is not None:
+ # We must be unique, so can short-circuit (and retain freq)
+ codes = np.arange(len(self), dtype=np.intp)
+ return codes, self.copy()
+ return ExtensionArray.factorize(self, na_sentinel=na_sentinel)
+
DatetimeLikeArrayT = TypeVar("DatetimeLikeArrayT", bound="DatetimeLikeArrayMixin")
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index e3fbb906ed6b1..222e9d8edd454 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -112,7 +112,7 @@ def f(self):
return property(f)
-class DatetimeArray(dtl.DatetimeLikeArrayMixin, dtl.TimelikeOps, dtl.DatelikeOps):
+class DatetimeArray(dtl.TimelikeOps, dtl.DatetimeLikeArrayMixin, dtl.DatelikeOps):
"""
Pandas ExtensionArray for tz-naive or tz-aware datetime data.
diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py
index a460d07e1f6f2..cc5ad95036a1c 100644
--- a/pandas/core/arrays/timedeltas.py
+++ b/pandas/core/arrays/timedeltas.py
@@ -57,7 +57,7 @@ def f(self):
return property(f)
-class TimedeltaArray(dtl.DatetimeLikeArrayMixin, dtl.TimelikeOps):
+class TimedeltaArray(dtl.TimelikeOps, dtl.DatetimeLikeArrayMixin):
"""
Pandas ExtensionArray for timedelta data.
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index decb17cdf6672..c6f79de61053e 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -602,6 +602,15 @@ def _shallow_copy(self, values=None, name: Label = lib.no_default):
result._cache = cache
return result
+ def factorize(self, sort=False, na_sentinel=-1):
+ if self.freq is not None and sort is False:
+ # we are unique, so can short-circuit, also can preserve freq
+ codes = np.arange(len(self), dtype=np.intp)
+ return codes, self.copy()
+ # TODO: In the sort=True case we could check for montonic_decreasing
+ # and operate on self[::-1]
+ return super().factorize(sort=sort, na_sentinel=na_sentinel)
+
# --------------------------------------------------------------------
# Set Operation Methods
diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py
index e0e5beaf48e20..aa3a963efb735 100644
--- a/pandas/tests/indexes/datetimes/test_datetime.py
+++ b/pandas/tests/indexes/datetimes/test_datetime.py
@@ -328,10 +328,12 @@ def test_factorize(self):
arr, idx = idx1.factorize()
tm.assert_numpy_array_equal(arr, exp_arr)
tm.assert_index_equal(idx, exp_idx)
+ assert idx.freq == exp_idx.freq
arr, idx = idx1.factorize(sort=True)
tm.assert_numpy_array_equal(arr, exp_arr)
tm.assert_index_equal(idx, exp_idx)
+ assert idx.freq == exp_idx.freq
# tz must be preserved
idx1 = idx1.tz_localize("Asia/Tokyo")
@@ -340,6 +342,7 @@ def test_factorize(self):
arr, idx = idx1.factorize()
tm.assert_numpy_array_equal(arr, exp_arr)
tm.assert_index_equal(idx, exp_idx)
+ assert idx.freq == exp_idx.freq
idx2 = pd.DatetimeIndex(
["2014-03", "2014-03", "2014-02", "2014-01", "2014-03", "2014-01"]
@@ -350,21 +353,31 @@ def test_factorize(self):
arr, idx = idx2.factorize(sort=True)
tm.assert_numpy_array_equal(arr, exp_arr)
tm.assert_index_equal(idx, exp_idx)
+ assert idx.freq == exp_idx.freq
exp_arr = np.array([0, 0, 1, 2, 0, 2], dtype=np.intp)
exp_idx = DatetimeIndex(["2014-03", "2014-02", "2014-01"])
arr, idx = idx2.factorize()
tm.assert_numpy_array_equal(arr, exp_arr)
tm.assert_index_equal(idx, exp_idx)
+ assert idx.freq == exp_idx.freq
- # freq must be preserved
+ def test_factorize_preserves_freq(self):
+ # GH#33836 freq should be preserved
idx3 = date_range("2000-01", periods=4, freq="M", tz="Asia/Tokyo")
exp_arr = np.array([0, 1, 2, 3], dtype=np.intp)
+
arr, idx = idx3.factorize()
tm.assert_numpy_array_equal(arr, exp_arr)
tm.assert_index_equal(idx, idx3)
+ assert idx.freq == idx3.freq
+
+ arr, idx = pd.factorize(idx3)
+ tm.assert_numpy_array_equal(arr, exp_arr)
+ tm.assert_index_equal(idx, idx3)
+ assert idx.freq == idx3.freq
- def test_factorize_tz(self, tz_naive_fixture):
+ def test_factorize_tz(self, tz_naive_fixture, index_or_series):
tz = tz_naive_fixture
# GH#13750
base = pd.date_range("2016-11-05", freq="H", periods=100, tz=tz)
@@ -372,27 +385,33 @@ def test_factorize_tz(self, tz_naive_fixture):
exp_arr = np.arange(100, dtype=np.intp).repeat(5)
- for obj in [idx, pd.Series(idx)]:
- arr, res = obj.factorize()
- tm.assert_numpy_array_equal(arr, exp_arr)
- expected = base._with_freq(None)
- tm.assert_index_equal(res, expected)
+ obj = index_or_series(idx)
+
+ arr, res = obj.factorize()
+ tm.assert_numpy_array_equal(arr, exp_arr)
+ expected = base._with_freq(None)
+ tm.assert_index_equal(res, expected)
+ assert res.freq == expected.freq
- def test_factorize_dst(self):
+ def test_factorize_dst(self, index_or_series):
# GH 13750
idx = pd.date_range("2016-11-06", freq="H", periods=12, tz="US/Eastern")
+ obj = index_or_series(idx)
- for obj in [idx, pd.Series(idx)]:
- arr, res = obj.factorize()
- tm.assert_numpy_array_equal(arr, np.arange(12, dtype=np.intp))
- tm.assert_index_equal(res, idx)
+ arr, res = obj.factorize()
+ tm.assert_numpy_array_equal(arr, np.arange(12, dtype=np.intp))
+ tm.assert_index_equal(res, idx)
+ if index_or_series is Index:
+ assert res.freq == idx.freq
idx = pd.date_range("2016-06-13", freq="H", periods=12, tz="US/Eastern")
+ obj = index_or_series(idx)
- for obj in [idx, pd.Series(idx)]:
- arr, res = obj.factorize()
- tm.assert_numpy_array_equal(arr, np.arange(12, dtype=np.intp))
- tm.assert_index_equal(res, idx)
+ arr, res = obj.factorize()
+ tm.assert_numpy_array_equal(arr, np.arange(12, dtype=np.intp))
+ tm.assert_index_equal(res, idx)
+ if index_or_series is Index:
+ assert res.freq == idx.freq
@pytest.mark.parametrize(
"arr, expected",
diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py
index 5efa1a75700e0..fa82ccb68989b 100644
--- a/pandas/tests/indexes/timedeltas/test_timedelta.py
+++ b/pandas/tests/indexes/timedeltas/test_timedelta.py
@@ -76,17 +76,26 @@ def test_factorize(self):
arr, idx = idx1.factorize()
tm.assert_numpy_array_equal(arr, exp_arr)
tm.assert_index_equal(idx, exp_idx)
+ assert idx.freq == exp_idx.freq
arr, idx = idx1.factorize(sort=True)
tm.assert_numpy_array_equal(arr, exp_arr)
tm.assert_index_equal(idx, exp_idx)
+ assert idx.freq == exp_idx.freq
- # freq must be preserved
+ def test_factorize_preserves_freq(self):
+ # GH#33836 freq should be preserved
idx3 = timedelta_range("1 day", periods=4, freq="s")
exp_arr = np.array([0, 1, 2, 3], dtype=np.intp)
arr, idx = idx3.factorize()
tm.assert_numpy_array_equal(arr, exp_arr)
tm.assert_index_equal(idx, idx3)
+ assert idx.freq == idx3.freq
+
+ arr, idx = pd.factorize(idx3)
+ tm.assert_numpy_array_equal(arr, exp_arr)
+ tm.assert_index_equal(idx, idx3)
+ assert idx.freq == idx3.freq
def test_sort_values(self):
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
xref #33830 | https://api.github.com/repos/pandas-dev/pandas/pulls/33836 | 2020-04-28T00:58:46Z | 2020-06-11T17:27:06Z | null | 2020-06-11T17:27:14Z |
REF/CLN: Parametrize _isna | diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py
index 92e1b17c41694..87ff9a78909dd 100644
--- a/pandas/core/dtypes/missing.py
+++ b/pandas/core/dtypes/missing.py
@@ -1,6 +1,8 @@
"""
missing types & inference
"""
+from functools import partial
+
import numpy as np
from pandas._config import get_option
@@ -124,61 +126,44 @@ def isna(obj):
isnull = isna
-def _isna_new(obj):
-
- if is_scalar(obj):
- return libmissing.checknull(obj)
- # hack (for now) because MI registers as ndarray
- elif isinstance(obj, ABCMultiIndex):
- raise NotImplementedError("isna is not defined for MultiIndex")
- elif isinstance(obj, type):
- return False
- elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):
- return _isna_ndarraylike(obj, old=False)
- elif isinstance(obj, ABCDataFrame):
- return obj.isna()
- elif isinstance(obj, list):
- return _isna_ndarraylike(np.asarray(obj, dtype=object), old=False)
- elif hasattr(obj, "__array__"):
- return _isna_ndarraylike(np.asarray(obj), old=False)
- else:
- return False
-
-
-def _isna_old(obj):
+def _isna(obj, inf_as_na: bool = False):
"""
- Detect missing values, treating None, NaN, INF, -INF as null.
+ Detect missing values, treating None, NaN or NA as null. Infinite
+ values will also be treated as null if inf_as_na is True.
Parameters
----------
- arr: ndarray or object value
+ obj: ndarray or object value
+ Input array or scalar value.
+ inf_as_na: bool
+ Whether to treat infinity as null.
Returns
-------
boolean ndarray or boolean
"""
if is_scalar(obj):
- return libmissing.checknull_old(obj)
+ if inf_as_na:
+ return libmissing.checknull_old(obj)
+ else:
+ return libmissing.checknull(obj)
# hack (for now) because MI registers as ndarray
elif isinstance(obj, ABCMultiIndex):
raise NotImplementedError("isna is not defined for MultiIndex")
elif isinstance(obj, type):
return False
elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass, ABCExtensionArray)):
- return _isna_ndarraylike(obj, old=True)
+ return _isna_ndarraylike(obj, inf_as_na=inf_as_na)
elif isinstance(obj, ABCDataFrame):
return obj.isna()
elif isinstance(obj, list):
- return _isna_ndarraylike(np.asarray(obj, dtype=object), old=True)
+ return _isna_ndarraylike(np.asarray(obj, dtype=object), inf_as_na=inf_as_na)
elif hasattr(obj, "__array__"):
- return _isna_ndarraylike(np.asarray(obj), old=True)
+ return _isna_ndarraylike(np.asarray(obj), inf_as_na=inf_as_na)
else:
return False
-_isna = _isna_new
-
-
def _use_inf_as_na(key):
"""
Option change callback for na/inf behaviour.
@@ -200,14 +185,11 @@ def _use_inf_as_na(key):
* https://stackoverflow.com/questions/4859217/
programmatically-creating-variables-in-python/4859312#4859312
"""
- flag = get_option(key)
- if flag:
- globals()["_isna"] = _isna_old
- else:
- globals()["_isna"] = _isna_new
+ inf_as_na = get_option(key)
+ globals()["_isna"] = partial(_isna, inf_as_na=inf_as_na)
-def _isna_ndarraylike(obj, old: bool = False):
+def _isna_ndarraylike(obj, inf_as_na: bool = False):
"""
Return an array indicating which values of the input array are NaN / NA.
@@ -215,7 +197,7 @@ def _isna_ndarraylike(obj, old: bool = False):
----------
obj: array-like
The input array whose elements are to be checked.
- old: bool
+ inf_as_na: bool
Whether or not to treat infinite values as NA.
Returns
@@ -227,17 +209,17 @@ def _isna_ndarraylike(obj, old: bool = False):
dtype = values.dtype
if is_extension_array_dtype(dtype):
- if old:
+ if inf_as_na:
result = values.isna() | (values == -np.inf) | (values == np.inf)
else:
result = values.isna()
elif is_string_dtype(dtype):
- result = _isna_string_dtype(values, dtype, old=old)
+ result = _isna_string_dtype(values, dtype, inf_as_na=inf_as_na)
elif needs_i8_conversion(dtype):
# this is the NaT pattern
result = values.view("i8") == iNaT
else:
- if old:
+ if inf_as_na:
result = ~np.isfinite(values)
else:
result = np.isnan(values)
@@ -249,7 +231,9 @@ def _isna_ndarraylike(obj, old: bool = False):
return result
-def _isna_string_dtype(values: np.ndarray, dtype: np.dtype, old: bool) -> np.ndarray:
+def _isna_string_dtype(
+ values: np.ndarray, dtype: np.dtype, inf_as_na: bool
+) -> np.ndarray:
# Working around NumPy ticket 1542
shape = values.shape
@@ -257,7 +241,7 @@ def _isna_string_dtype(values: np.ndarray, dtype: np.dtype, old: bool) -> np.nda
result = np.zeros(values.shape, dtype=bool)
else:
result = np.empty(shape, dtype=bool)
- if old:
+ if inf_as_na:
vec = libmissing.isnaobj_old(values.ravel())
else:
vec = libmissing.isnaobj(values.ravel())
| Replaces two nearly identical isna functions with one by parametrizing over the difference | https://api.github.com/repos/pandas-dev/pandas/pulls/33835 | 2020-04-27T23:59:50Z | 2020-04-29T12:09:20Z | 2020-04-29T12:09:20Z | 2020-04-29T12:38:28Z |
BUG: TimedeltaIndex[:] losing freq | diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index 8295ca13c33b1..decb17cdf6672 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -1,7 +1,7 @@
"""
Base and utility classes for tseries type pandas objects.
"""
-from datetime import datetime, timedelta
+from datetime import datetime
from typing import Any, List, Optional, Union, cast
import numpy as np
@@ -16,18 +16,14 @@
from pandas.core.dtypes.common import (
ensure_int64,
is_bool_dtype,
- is_datetime64_any_dtype,
is_dtype_equal,
is_integer,
is_list_like,
- is_object_dtype,
is_period_dtype,
is_scalar,
- is_timedelta64_dtype,
)
from pandas.core.dtypes.concat import concat_compat
from pandas.core.dtypes.generic import ABCIndex, ABCIndexClass, ABCSeries
-from pandas.core.dtypes.missing import isna
from pandas.core import algorithms
from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray
@@ -46,7 +42,6 @@
from pandas.core.tools.timedeltas import to_timedelta
from pandas.tseries.frequencies import DateOffset
-from pandas.tseries.offsets import Tick
_index_doc_kwargs = dict(ibase._index_doc_kwargs)
@@ -77,33 +72,13 @@ def wrapper(left, right):
return wrapper
-def _make_wrapped_arith_op_with_freq(opname: str):
- """
- Dispatch the operation to the underlying ExtensionArray, and infer
- the appropriate frequency for the result.
- """
- meth = make_wrapped_arith_op(opname)
-
- def wrapped(self, other):
- result = meth(self, other)
- if result is NotImplemented:
- return NotImplemented
-
- new_freq = self._get_addsub_freq(other, result)
- result._freq = new_freq
- return result
-
- wrapped.__name__ = opname
- return wrapped
-
-
@inherit_names(
["inferred_freq", "_isnan", "_resolution", "resolution"],
DatetimeLikeArrayMixin,
cache=True,
)
@inherit_names(
- ["mean", "asi8", "_box_func"], DatetimeLikeArrayMixin,
+ ["mean", "asi8", "freq", "freqstr", "_box_func"], DatetimeLikeArrayMixin,
)
class DatetimeIndexOpsMixin(ExtensionIndex):
"""
@@ -437,44 +412,8 @@ def _partial_date_slice(
# --------------------------------------------------------------------
# Arithmetic Methods
- def _get_addsub_freq(self, other, result) -> Optional[DateOffset]:
- """
- Find the freq we expect the result of an addition/subtraction operation
- to have.
- """
- if is_period_dtype(self.dtype):
- if is_period_dtype(result.dtype):
- # Only used for ops that stay PeriodDtype
- return self.freq
- return None
- elif self.freq is None:
- return None
- elif lib.is_scalar(other) and isna(other):
- return None
-
- elif isinstance(other, (Tick, timedelta, np.timedelta64)):
- new_freq = None
- if isinstance(self.freq, Tick):
- new_freq = self.freq
- return new_freq
-
- elif isinstance(other, DateOffset):
- # otherwise just DatetimeArray
- return None # TODO: Should we infer if it matches self.freq * n?
- elif isinstance(other, (datetime, np.datetime64)):
- return self.freq
-
- elif is_timedelta64_dtype(other):
- return None # TODO: shouldnt we be able to do self.freq + other.freq?
- elif is_object_dtype(other):
- return None # TODO: is this quite right? sometimes we unpack singletons
- elif is_datetime64_any_dtype(other):
- return None # TODO: shouldnt we be able to do self.freq + other.freq?
- else:
- raise NotImplementedError
-
- __add__ = _make_wrapped_arith_op_with_freq("__add__")
- __sub__ = _make_wrapped_arith_op_with_freq("__sub__")
+ __add__ = make_wrapped_arith_op("__add__")
+ __sub__ = make_wrapped_arith_op("__sub__")
__radd__ = make_wrapped_arith_op("__radd__")
__rsub__ = make_wrapped_arith_op("__rsub__")
__pow__ = make_wrapped_arith_op("__pow__")
@@ -643,25 +582,6 @@ class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index):
_is_monotonic_increasing = Index.is_monotonic_increasing
_is_monotonic_decreasing = Index.is_monotonic_decreasing
_is_unique = Index.is_unique
- _freq = lib.no_default
-
- @property
- def freq(self):
- """
- In limited circumstances, our freq may differ from that of our _data.
- """
- if self._freq is not lib.no_default:
- return self._freq
- return self._data.freq
-
- @property
- def freqstr(self):
- """
- Return the frequency object as a string if its set, otherwise None.
- """
- if self.freq is None:
- return None
- return self.freq.freqstr
def _with_freq(self, freq):
arr = self._data._with_freq(freq)
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py
index 76c78fa34cf8b..135361c8c0962 100644
--- a/pandas/core/indexes/period.py
+++ b/pandas/core/indexes/period.py
@@ -70,7 +70,7 @@ def _new_PeriodIndex(cls, **d):
PeriodArray,
wrap=True,
)
-@inherit_names(["is_leap_year", "freq", "freqstr", "_format_native_types"], PeriodArray)
+@inherit_names(["is_leap_year", "_format_native_types"], PeriodArray)
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index):
"""
Immutable ndarray holding ordinal values indicating regular periods in time.
diff --git a/pandas/tests/indexes/datetimelike.py b/pandas/tests/indexes/datetimelike.py
index dfefdc0f211b1..ac3320c6f9fa0 100644
--- a/pandas/tests/indexes/datetimelike.py
+++ b/pandas/tests/indexes/datetimelike.py
@@ -96,3 +96,10 @@ def test_map_dictlike(self, mapper):
expected = pd.Index([np.nan] * len(index))
result = index.map(mapper([], []))
tm.assert_index_equal(result, expected)
+
+ def test_getitem_preserves_freq(self):
+ index = self.create_index()
+ assert index.freq is not None
+
+ result = index[:]
+ assert result.freq == index.freq
| Reverts the freq-override I implemented a few days ago. That was made unnecessary by the more-recent change to _with_freq that ensures that self.freq and self._data.freq stay in sync. | https://api.github.com/repos/pandas-dev/pandas/pulls/33834 | 2020-04-27T22:08:46Z | 2020-04-27T23:43:49Z | 2020-04-27T23:43:49Z | 2020-04-27T23:46:56Z |
DOC/CLN: Fix whatsnew typo | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 20dff048cc6d5..6b641746b95ff 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -730,7 +730,7 @@ Sparse
ExtensionArray
^^^^^^^^^^^^^^
-- Fixed bug where :meth:`Serires.value_counts` would raise on empty input of ``Int64`` dtype (:issue:`33317`)
+- Fixed bug where :meth:`Series.value_counts` would raise on empty input of ``Int64`` dtype (:issue:`33317`)
-
| Should something like this cause a CI failure? | https://api.github.com/repos/pandas-dev/pandas/pulls/33833 | 2020-04-27T21:49:32Z | 2020-04-27T23:48:43Z | 2020-04-27T23:48:43Z | 2020-04-27T23:51:43Z |
DEPR: Timestamp.freq | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 597a0c5386cf0..a2a2a87bbdc56 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -486,6 +486,7 @@ Deprecations
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`)
+- The :class:`Timestamp` attribute ``freq`` is deprecated and will be removed in a future version; passing ``freq`` to the constructor will raise ``TypeError`` (:issue:`15146`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx
index 53bcf5be2586a..088b51e60f9ae 100644
--- a/pandas/_libs/tslib.pyx
+++ b/pandas/_libs/tslib.pyx
@@ -1,3 +1,5 @@
+import warnings
+
import cython
from cpython.datetime cimport (
@@ -163,6 +165,13 @@ def ints_to_pydatetime(
elif box == "timestamp":
func_create = create_timestamp_from_ts
+ if freq is not None:
+ warnings.warn(
+ "Passing `freq` to Timestamp is deprecated and will raise "
+ "TypeError in a future version.",
+ FutureWarning,
+ )
+
if isinstance(freq, str):
freq = to_offset(freq)
elif box == "time":
diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx
index 7858072407a35..076ad11e45df8 100644
--- a/pandas/_libs/tslibs/timestamps.pyx
+++ b/pandas/_libs/tslibs/timestamps.pyx
@@ -484,6 +484,13 @@ class Timestamp(_Timestamp):
if ts.value == NPY_NAT:
return NaT
+ if freq is not None:
+ warnings.warn(
+ "Passing `freq` to Timestamp is deprecated and will raise "
+ "TypeError in a future version.",
+ FutureWarning,
+ )
+
if freq is None:
# GH 22311: Try to extract the frequency of a given Timestamp input
freq = getattr(ts_input, 'freq', None)
diff --git a/pandas/conftest.py b/pandas/conftest.py
index 16b6d40645547..6427b738ef843 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -39,6 +39,10 @@
from pandas.core import ops
from pandas.core.indexes.api import Index, MultiIndex
+silence_freq_deprecation = pytest.mark.filterwarnings(
+ "ignore:Passing `freq` to Timestamp is deprecated"
+)
+
# ----------------------------------------------------------------
# Configuration / Settings
@@ -78,6 +82,13 @@ def pytest_runtest_setup(item):
pytest.skip("skipping high memory test since --run-high-memory was not set")
+def pytest_collection_modifyitems(config, items):
+ for item in items:
+ # By adding this marker here, we do not need to silence it throughout
+ # the tests
+ item.add_marker(silence_freq_deprecation)
+
+
# Hypothesis
hypothesis.settings.register_profile(
"ci",
diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py
index 8c937064c0493..7bd5553e2a4f5 100644
--- a/pandas/tests/arithmetic/test_datetime64.py
+++ b/pandas/tests/arithmetic/test_datetime64.py
@@ -967,7 +967,10 @@ def test_dt64arr_sub_dt64object_array(self, box_with_array, tz_naive_fixture):
warn = PerformanceWarning if box_with_array is not pd.DataFrame else None
with tm.assert_produces_warning(warn):
- result = obj - obj.astype(object)
+ with warnings.catch_warnings():
+ # Passing freq to Timestamp constructor
+ warnings.simplefilter("ignore", FutureWarning)
+ result = obj - obj.astype(object)
tm.assert_equal(result, expected)
def test_dt64arr_naive_sub_dt64ndarray(self, box_with_array):
@@ -1457,11 +1460,15 @@ def test_dt64arr_add_sub_offset_array(
# GH#10699 array of offsets
tz = tz_naive_fixture
- dti = pd.date_range("2017-01-01", periods=2, tz=tz)
- dtarr = tm.box_expected(dti, box_with_array)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", FutureWarning)
+ dti = pd.date_range("2017-01-01", periods=2, tz=tz)
+ dtarr = tm.box_expected(dti, box_with_array)
other = np.array([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)])
- expected = DatetimeIndex([op(dti[n], other[n]) for n in range(len(dti))])
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", FutureWarning)
+ expected = DatetimeIndex([op(dti[n], other[n]) for n in range(len(dti))])
expected = tm.box_expected(expected, box_with_array)
if box_other:
@@ -1471,7 +1478,9 @@ def test_dt64arr_add_sub_offset_array(
if box_with_array is pd.DataFrame and not (tz is None and not box_other):
warn = None
with tm.assert_produces_warning(warn):
- res = op(dtarr, other)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", FutureWarning)
+ res = op(dtarr, other)
tm.assert_equal(res, expected)
@@ -2391,10 +2400,15 @@ def test_dti_addsub_offset_arraylike(
xbox = get_upcast_box(box, other)
with tm.assert_produces_warning(PerformanceWarning):
- res = op(dti, other)
+ with warnings.catch_warnings():
+ # Passing freq to Timestamp constructor
+ warnings.simplefilter("ignore", FutureWarning)
+ res = op(dti, other)
expected = DatetimeIndex(
- [op(dti[n], other[n]) for n in range(len(dti))], name=names[2], freq="infer"
+ [op(dti[n], other[n]) for n in range(len(dti))],
+ name=names[2],
+ freq="infer",
)
expected = tm.box_expected(expected, xbox)
tm.assert_equal(res, expected)
@@ -2418,14 +2432,20 @@ def test_dti_addsub_object_arraylike(
warn = None
with tm.assert_produces_warning(warn):
- result = dtarr + other
+ with warnings.catch_warnings():
+ # Passing freq to Timestamp constructor
+ warnings.simplefilter("ignore", FutureWarning)
+ result = dtarr + other
tm.assert_equal(result, expected)
expected = pd.DatetimeIndex(["2016-12-31", "2016-12-29"], tz=tz_naive_fixture)
expected = tm.box_expected(expected, xbox)
with tm.assert_produces_warning(warn):
- result = dtarr - other
+ with warnings.catch_warnings():
+ # Passing freq to Timestamp constructor
+ warnings.simplefilter("ignore", FutureWarning)
+ result = dtarr - other
tm.assert_equal(result, expected)
diff --git a/pandas/tests/indexes/datetimes/test_misc.py b/pandas/tests/indexes/datetimes/test_misc.py
index 42a72125ba411..c193b87a4be73 100644
--- a/pandas/tests/indexes/datetimes/test_misc.py
+++ b/pandas/tests/indexes/datetimes/test_misc.py
@@ -242,40 +242,42 @@ def test_datetimeindex_accessors(self):
assert dti.is_month_start[0] == 1
- tests = [
- (Timestamp("2013-06-01", freq="M").is_month_start, 1),
- (Timestamp("2013-06-01", freq="BM").is_month_start, 0),
- (Timestamp("2013-06-03", freq="M").is_month_start, 0),
- (Timestamp("2013-06-03", freq="BM").is_month_start, 1),
- (Timestamp("2013-02-28", freq="Q-FEB").is_month_end, 1),
- (Timestamp("2013-02-28", freq="Q-FEB").is_quarter_end, 1),
- (Timestamp("2013-02-28", freq="Q-FEB").is_year_end, 1),
- (Timestamp("2013-03-01", freq="Q-FEB").is_month_start, 1),
- (Timestamp("2013-03-01", freq="Q-FEB").is_quarter_start, 1),
- (Timestamp("2013-03-01", freq="Q-FEB").is_year_start, 1),
- (Timestamp("2013-03-31", freq="QS-FEB").is_month_end, 1),
- (Timestamp("2013-03-31", freq="QS-FEB").is_quarter_end, 0),
- (Timestamp("2013-03-31", freq="QS-FEB").is_year_end, 0),
- (Timestamp("2013-02-01", freq="QS-FEB").is_month_start, 1),
- (Timestamp("2013-02-01", freq="QS-FEB").is_quarter_start, 1),
- (Timestamp("2013-02-01", freq="QS-FEB").is_year_start, 1),
- (Timestamp("2013-06-30", freq="BQ").is_month_end, 0),
- (Timestamp("2013-06-30", freq="BQ").is_quarter_end, 0),
- (Timestamp("2013-06-30", freq="BQ").is_year_end, 0),
- (Timestamp("2013-06-28", freq="BQ").is_month_end, 1),
- (Timestamp("2013-06-28", freq="BQ").is_quarter_end, 1),
- (Timestamp("2013-06-28", freq="BQ").is_year_end, 0),
- (Timestamp("2013-06-30", freq="BQS-APR").is_month_end, 0),
- (Timestamp("2013-06-30", freq="BQS-APR").is_quarter_end, 0),
- (Timestamp("2013-06-30", freq="BQS-APR").is_year_end, 0),
- (Timestamp("2013-06-28", freq="BQS-APR").is_month_end, 1),
- (Timestamp("2013-06-28", freq="BQS-APR").is_quarter_end, 1),
- (Timestamp("2013-03-29", freq="BQS-APR").is_year_end, 1),
- (Timestamp("2013-11-01", freq="AS-NOV").is_year_start, 1),
- (Timestamp("2013-10-31", freq="AS-NOV").is_year_end, 1),
- (Timestamp("2012-02-01").days_in_month, 29),
- (Timestamp("2013-02-01").days_in_month, 28),
- ]
+ with tm.assert_produces_warning(FutureWarning):
+ # passing freq to Timestamp
+ tests = [
+ (Timestamp("2013-06-01", freq="M").is_month_start, 1),
+ (Timestamp("2013-06-01", freq="BM").is_month_start, 0),
+ (Timestamp("2013-06-03", freq="M").is_month_start, 0),
+ (Timestamp("2013-06-03", freq="BM").is_month_start, 1),
+ (Timestamp("2013-02-28", freq="Q-FEB").is_month_end, 1),
+ (Timestamp("2013-02-28", freq="Q-FEB").is_quarter_end, 1),
+ (Timestamp("2013-02-28", freq="Q-FEB").is_year_end, 1),
+ (Timestamp("2013-03-01", freq="Q-FEB").is_month_start, 1),
+ (Timestamp("2013-03-01", freq="Q-FEB").is_quarter_start, 1),
+ (Timestamp("2013-03-01", freq="Q-FEB").is_year_start, 1),
+ (Timestamp("2013-03-31", freq="QS-FEB").is_month_end, 1),
+ (Timestamp("2013-03-31", freq="QS-FEB").is_quarter_end, 0),
+ (Timestamp("2013-03-31", freq="QS-FEB").is_year_end, 0),
+ (Timestamp("2013-02-01", freq="QS-FEB").is_month_start, 1),
+ (Timestamp("2013-02-01", freq="QS-FEB").is_quarter_start, 1),
+ (Timestamp("2013-02-01", freq="QS-FEB").is_year_start, 1),
+ (Timestamp("2013-06-30", freq="BQ").is_month_end, 0),
+ (Timestamp("2013-06-30", freq="BQ").is_quarter_end, 0),
+ (Timestamp("2013-06-30", freq="BQ").is_year_end, 0),
+ (Timestamp("2013-06-28", freq="BQ").is_month_end, 1),
+ (Timestamp("2013-06-28", freq="BQ").is_quarter_end, 1),
+ (Timestamp("2013-06-28", freq="BQ").is_year_end, 0),
+ (Timestamp("2013-06-30", freq="BQS-APR").is_month_end, 0),
+ (Timestamp("2013-06-30", freq="BQS-APR").is_quarter_end, 0),
+ (Timestamp("2013-06-30", freq="BQS-APR").is_year_end, 0),
+ (Timestamp("2013-06-28", freq="BQS-APR").is_month_end, 1),
+ (Timestamp("2013-06-28", freq="BQS-APR").is_quarter_end, 1),
+ (Timestamp("2013-03-29", freq="BQS-APR").is_year_end, 1),
+ (Timestamp("2013-11-01", freq="AS-NOV").is_year_start, 1),
+ (Timestamp("2013-10-31", freq="AS-NOV").is_year_end, 1),
+ (Timestamp("2012-02-01").days_in_month, 29),
+ (Timestamp("2013-02-01").days_in_month, 28),
+ ]
for ts, value in tests:
assert ts == value
diff --git a/pandas/tests/indexes/datetimes/test_shift.py b/pandas/tests/indexes/datetimes/test_shift.py
index 8724bfeb05c4d..3848311f374c4 100644
--- a/pandas/tests/indexes/datetimes/test_shift.py
+++ b/pandas/tests/indexes/datetimes/test_shift.py
@@ -1,4 +1,5 @@
from datetime import datetime
+import warnings
import pytest
import pytz
@@ -149,5 +150,9 @@ def test_shift_bmonth(self):
rng = date_range(START, END, freq=pd.offsets.BMonthEnd())
with tm.assert_produces_warning(pd.errors.PerformanceWarning):
- shifted = rng.shift(1, freq=pd.offsets.CDay())
- assert shifted[0] == rng[0] + pd.offsets.CDay()
+ with warnings.catch_warnings():
+ # Passing freq to Timestamp constructor
+ warnings.simplefilter("ignore", FutureWarning)
+
+ shifted = rng.shift(1, freq=pd.offsets.CDay())
+ assert shifted[0] == rng[0] + pd.offsets.CDay()
diff --git a/pandas/tests/indexes/datetimes/test_to_period.py b/pandas/tests/indexes/datetimes/test_to_period.py
index d82fc1ef6743b..e90713dfad908 100644
--- a/pandas/tests/indexes/datetimes/test_to_period.py
+++ b/pandas/tests/indexes/datetimes/test_to_period.py
@@ -147,8 +147,11 @@ def test_to_period_tz(self, tz):
with tm.assert_produces_warning(UserWarning):
# GH#21333 warning that timezone info will be lost
- result = ts.to_period()[0]
- expected = ts[0].to_period()
+ with warnings.catch_warnings():
+ # Passing freq to Timestamp constructor
+ warnings.simplefilter("ignore", FutureWarning)
+ result = ts.to_period()[0]
+ expected = ts[0].to_period()
assert result == expected
@@ -165,9 +168,13 @@ def test_to_period_tz_utc_offset_consistency(self, tz):
# GH#22905
ts = date_range("1/1/2000", "2/1/2000", tz="Etc/GMT-1")
with tm.assert_produces_warning(UserWarning):
- result = ts.to_period()[0]
- expected = ts[0].to_period()
- assert result == expected
+ with warnings.catch_warnings():
+ # Passing freq to Timestamp constructor
+ warnings.simplefilter("ignore", FutureWarning)
+ result = ts.to_period()[0]
+ expected = ts[0].to_period()
+
+ assert result == expected
def test_to_period_nofreq(self):
idx = DatetimeIndex(["2000-01-01", "2000-01-02", "2000-01-04"])
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index 7b42e9646918e..36576b9c0c6bd 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -4,6 +4,7 @@
import math
import operator
import re
+import warnings
import numpy as np
import pytest
@@ -1924,12 +1925,20 @@ def test_outer_join_sort(self):
right_index = tm.makeDateIndex(10)
with tm.assert_produces_warning(RuntimeWarning):
- result = left_index.join(right_index, how="outer")
+ with warnings.catch_warnings():
+ # Passing freq to Timestamp constructor
+ warnings.simplefilter("ignore", FutureWarning)
+
+ result = left_index.join(right_index, how="outer")
# right_index in this case because DatetimeIndex has join precedence
# over Int64Index
with tm.assert_produces_warning(RuntimeWarning):
- expected = right_index.astype(object).union(left_index.astype(object))
+ with warnings.catch_warnings():
+ # Passing freq to Timestamp constructor
+ warnings.simplefilter("ignore", FutureWarning)
+
+ expected = right_index.astype(object).union(left_index.astype(object))
tm.assert_index_equal(result, expected)
diff --git a/pandas/tests/scalar/timestamp/test_constructors.py b/pandas/tests/scalar/timestamp/test_constructors.py
index 770753f42a4c8..a391af54010ec 100644
--- a/pandas/tests/scalar/timestamp/test_constructors.py
+++ b/pandas/tests/scalar/timestamp/test_constructors.py
@@ -10,6 +10,7 @@
from pandas.errors import OutOfBoundsDatetime
from pandas import Period, Timedelta, Timestamp, compat
+import pandas._testing as tm
from pandas.tseries import offsets
@@ -187,7 +188,8 @@ def test_constructor_invalid_tz(self):
# GH#5168
# case where user tries to pass tz as an arg, not kwarg, gets
# interpreted as a `freq`
- Timestamp("2012-01-01", "US/Pacific")
+ with tm.assert_produces_warning(FutureWarning):
+ Timestamp("2012-01-01", "US/Pacific")
def test_constructor_strptime(self):
# GH25016
@@ -271,7 +273,8 @@ def test_constructor_keyword(self):
def test_constructor_fromordinal(self):
base = datetime(2000, 1, 1)
- ts = Timestamp.fromordinal(base.toordinal(), freq="D")
+ with tm.assert_produces_warning(FutureWarning):
+ ts = Timestamp.fromordinal(base.toordinal(), freq="D")
assert base == ts
assert ts.freq == "D"
assert base.toordinal() == ts.toordinal()
@@ -495,7 +498,8 @@ def test_construct_with_different_string_format(self, arg):
def test_construct_timestamp_preserve_original_frequency(self):
# GH 22311
- result = Timestamp(Timestamp("2010-08-08", freq="D")).freq
+ with tm.assert_produces_warning(FutureWarning):
+ result = Timestamp(Timestamp("2010-08-08", freq="D")).freq
expected = offsets.Day()
assert result == expected
@@ -503,7 +507,12 @@ def test_constructor_invalid_frequency(self):
# GH 22311
msg = "Invalid frequency:"
with pytest.raises(ValueError, match=msg):
- Timestamp("2012-01-01", freq=[])
+ with tm.assert_produces_warning(FutureWarning):
+ Timestamp("2012-01-01", freq=[])
+
+ def test_freq_deprecated(self):
+ with tm.assert_produces_warning(FutureWarning):
+ Timestamp("2012-01-01", freq="D")
@pytest.mark.parametrize("box", [datetime, Timestamp])
def test_raise_tz_and_tzinfo_in_datetime_input(self, box):
diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py
index 15b6481c08a61..716d74cdc5419 100644
--- a/pandas/tests/series/test_timeseries.py
+++ b/pandas/tests/series/test_timeseries.py
@@ -1,3 +1,5 @@
+import warnings
+
import numpy as np
import pytest
@@ -115,7 +117,12 @@ def test_asarray_object_dt64(self, tz):
with tm.assert_produces_warning(None):
# Future behavior (for tzaware case) with no warning
- result = np.asarray(ser, dtype=object)
+ with warnings.catch_warnings():
+ # Passing freq to Timestamp constructor
+ warnings.simplefilter("ignore", FutureWarning)
+ # FIXME: this makes the assert_produces_warning(None) toothless
+
+ result = np.asarray(ser, dtype=object)
expected = np.array(
[pd.Timestamp("2000-01-01", tz=tz), pd.Timestamp("2000-01-02", tz=tz)]
diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py
index 5fe62f41e49ff..dc73016f3aaf7 100644
--- a/pandas/tseries/offsets.py
+++ b/pandas/tseries/offsets.py
@@ -608,7 +608,11 @@ def apply(self, other):
# shift by n days plus 2 to get past the weekend
days = n + 2
- result = other + timedelta(days=7 * weeks + days)
+ with warnings.catch_warnings():
+ # Passing freq to Timestamp constructor
+ warnings.simplefilter("ignore", FutureWarning)
+ result = other + timedelta(days=7 * weeks + days)
+
if self.offset:
result = result + self.offset
return result
| - [x] closes #15146
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
The motivation here is that I've concluded that DatetimeArray.freq _must_ be removed, so for internal consistency Timestamp.freq should be removed too.
The main user-facing behavior this will affect is Timestamp.is_month_start, is_month_end, is_quarter_start, is_quarter_end, is_year_start, is_year_end, for which I guess we'll offer users an alternative(?) | https://api.github.com/repos/pandas-dev/pandas/pulls/33832 | 2020-04-27T21:48:45Z | 2020-05-22T20:33:02Z | null | 2020-05-22T20:33:06Z |
DOC/CLN: remove outdated warnings in enhancingperf.rst | diff --git a/doc/source/user_guide/enhancingperf.rst b/doc/source/user_guide/enhancingperf.rst
index 1d84d05fda079..2056fe2f754f8 100644
--- a/doc/source/user_guide/enhancingperf.rst
+++ b/doc/source/user_guide/enhancingperf.rst
@@ -396,7 +396,7 @@ Consider the following toy example of doubling each observation:
1000 loops, best of 3: 233 us per loop
# Custom function with numba
- In [7]: %timeit (df['col1_doubled'] = double_every_value_withnumba(df['a'].to_numpy())
+ In [7]: %timeit df['col1_doubled'] = double_every_value_withnumba(df['a'].to_numpy())
1000 loops, best of 3: 145 us per loop
Caveats
@@ -599,13 +599,6 @@ identifier.
The ``inplace`` keyword determines whether this assignment will performed
on the original ``DataFrame`` or return a copy with the new column.
-.. warning::
-
- For backwards compatibility, ``inplace`` defaults to ``True`` if not
- specified. This will change in a future version of pandas - if your
- code depends on an inplace assignment you should update to explicitly
- set ``inplace=True``.
-
.. ipython:: python
df = pd.DataFrame(dict(a=range(5), b=range(5, 10)))
@@ -614,7 +607,7 @@ on the original ``DataFrame`` or return a copy with the new column.
df.eval('a = 1', inplace=True)
df
-When ``inplace`` is set to ``False``, a copy of the ``DataFrame`` with the
+When ``inplace`` is set to ``False``, the default, a copy of the ``DataFrame`` with the
new or modified columns is returned and the original frame is unchanged.
.. ipython:: python
@@ -653,11 +646,6 @@ whether the query modifies the original frame.
df.query('a > 2', inplace=True)
df
-.. warning::
-
- Unlike with ``eval``, the default value for ``inplace`` for ``query``
- is ``False``. This is consistent with prior versions of pandas.
-
Local variables
~~~~~~~~~~~~~~~
| xref #16732 and SyntaxError | https://api.github.com/repos/pandas-dev/pandas/pulls/33831 | 2020-04-27T21:41:58Z | 2020-04-27T23:48:10Z | 2020-04-27T23:48:10Z | 2020-04-28T08:58:20Z |
TST: ensure groupby get by index value #33439 | diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py
index e860ea1a3d052..d4b061594c364 100644
--- a/pandas/tests/groupby/aggregate/test_aggregate.py
+++ b/pandas/tests/groupby/aggregate/test_aggregate.py
@@ -940,3 +940,11 @@ def test_agg_multiple_lambda(self):
weight_min=pd.NamedAgg(column="weight", aggfunc=lambda x: np.min(x)),
)
tm.assert_frame_equal(result2, expected)
+
+
+def test_groupby_get_by_index():
+ # GH 33439
+ df = pd.DataFrame({"A": ["S", "W", "W"], "B": [1.0, 1.0, 2.0]})
+ res = df.groupby("A").agg({"B": lambda x: x.get(x.index[-1])})
+ expected = pd.DataFrame(dict(A=["S", "W"], B=[1.0, 2.0])).set_index("A")
+ pd.testing.assert_frame_equal(res, expected)
| - [x] closes #33439
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/33829 | 2020-04-27T19:47:14Z | 2020-05-01T00:26:36Z | 2020-05-01T00:26:36Z | 2020-05-01T00:26:49Z |
BUG: DataFrame[object] + Series[dt64], test parametrization | diff --git a/pandas/core/ops/dispatch.py b/pandas/core/ops/dispatch.py
index 2463a1f58a447..637f0fa1d52e9 100644
--- a/pandas/core/ops/dispatch.py
+++ b/pandas/core/ops/dispatch.py
@@ -71,8 +71,10 @@ def should_series_dispatch(left, right, op):
# numpy integer dtypes as timedelta64 dtypes in this scenario
return True
- if is_datetime64_dtype(ldtype) and is_object_dtype(rdtype):
- # in particular case where right is an array of DateOffsets
+ if (is_datetime64_dtype(ldtype) and is_object_dtype(rdtype)) or (
+ is_datetime64_dtype(rdtype) and is_object_dtype(ldtype)
+ ):
+ # in particular case where one is an array of DateOffsets
return True
return False
diff --git a/pandas/tests/arithmetic/conftest.py b/pandas/tests/arithmetic/conftest.py
index 577093c0f2967..c20a9567e9ff8 100644
--- a/pandas/tests/arithmetic/conftest.py
+++ b/pandas/tests/arithmetic/conftest.py
@@ -17,6 +17,18 @@ def id_func(x):
# ------------------------------------------------------------------
+@pytest.fixture(
+ params=[
+ ("foo", None, None),
+ ("Egon", "Venkman", None),
+ ("NCC1701D", "NCC1701D", "NCC1701D"),
+ ]
+)
+def names(request):
+ """
+ A 3-tuple of names, the first two for operands, the last for a result.
+ """
+ return request.param
@pytest.fixture(params=[1, np.array(1, dtype=np.int64)])
diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py
index 83d81ccf84b45..8c937064c0493 100644
--- a/pandas/tests/arithmetic/test_datetime64.py
+++ b/pandas/tests/arithmetic/test_datetime64.py
@@ -1438,64 +1438,41 @@ def test_dt64arr_add_sub_DateOffset(self, box_with_array):
tm.assert_equal(result, exp)
tm.assert_equal(result2, exp)
- # TODO: __sub__, __rsub__
- def test_dt64arr_add_mixed_offset_array(self, box_with_array):
- # GH#10699
- # array of offsets
- s = DatetimeIndex([Timestamp("2000-1-1"), Timestamp("2000-2-1")])
- s = tm.box_expected(s, box_with_array)
-
- warn = None if box_with_array is pd.DataFrame else PerformanceWarning
- with tm.assert_produces_warning(warn):
- other = pd.Index([pd.offsets.DateOffset(years=1), pd.offsets.MonthEnd()])
- other = tm.box_expected(other, box_with_array)
- result = s + other
- exp = DatetimeIndex([Timestamp("2001-1-1"), Timestamp("2000-2-29")])
- exp = tm.box_expected(exp, box_with_array)
- tm.assert_equal(result, exp)
-
- # same offset
- other = pd.Index(
+ @pytest.mark.parametrize(
+ "other",
+ [
+ np.array([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)]),
+ np.array([pd.offsets.DateOffset(years=1), pd.offsets.MonthEnd()]),
+ np.array( # matching offsets
[pd.offsets.DateOffset(years=1), pd.offsets.DateOffset(years=1)]
- )
- other = tm.box_expected(other, box_with_array)
- result = s + other
- exp = DatetimeIndex([Timestamp("2001-1-1"), Timestamp("2001-2-1")])
- exp = tm.box_expected(exp, box_with_array)
- tm.assert_equal(result, exp)
-
- # TODO: overlap with test_dt64arr_add_mixed_offset_array?
- def test_dt64arr_add_sub_offset_ndarray(self, tz_naive_fixture, box_with_array):
+ ),
+ ],
+ )
+ @pytest.mark.parametrize("op", [operator.add, roperator.radd, operator.sub])
+ @pytest.mark.parametrize("box_other", [True, False])
+ def test_dt64arr_add_sub_offset_array(
+ self, tz_naive_fixture, box_with_array, box_other, op, other
+ ):
# GH#18849
+ # GH#10699 array of offsets
tz = tz_naive_fixture
dti = pd.date_range("2017-01-01", periods=2, tz=tz)
dtarr = tm.box_expected(dti, box_with_array)
other = np.array([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)])
+ expected = DatetimeIndex([op(dti[n], other[n]) for n in range(len(dti))])
+ expected = tm.box_expected(expected, box_with_array)
+
+ if box_other:
+ other = tm.box_expected(other, box_with_array)
warn = PerformanceWarning
- if box_with_array is pd.DataFrame and tz is not None:
+ if box_with_array is pd.DataFrame and not (tz is None and not box_other):
warn = None
-
- with tm.assert_produces_warning(warn):
- res = dtarr + other
- expected = DatetimeIndex(
- [dti[n] + other[n] for n in range(len(dti))], name=dti.name, freq="infer"
- )
- expected = tm.box_expected(expected, box_with_array)
- tm.assert_equal(res, expected)
-
with tm.assert_produces_warning(warn):
- res2 = other + dtarr
- tm.assert_equal(res2, expected)
+ res = op(dtarr, other)
- with tm.assert_produces_warning(warn):
- res = dtarr - other
- expected = DatetimeIndex(
- [dti[n] - other[n] for n in range(len(dti))], name=dti.name, freq="infer"
- )
- expected = tm.box_expected(expected, box_with_array)
tm.assert_equal(res, expected)
@pytest.mark.parametrize(
@@ -1905,9 +1882,9 @@ def test_dt64_mul_div_numeric_invalid(self, one, dt64_series):
# TODO: parametrize over box
@pytest.mark.parametrize("op", ["__add__", "__radd__", "__sub__", "__rsub__"])
- @pytest.mark.parametrize("tz", [None, "Asia/Tokyo"])
- def test_dt64_series_add_intlike(self, tz, op):
+ def test_dt64_series_add_intlike(self, tz_naive_fixture, op):
# GH#19123
+ tz = tz_naive_fixture
dti = pd.DatetimeIndex(["2016-01-02", "2016-02-03", "NaT"], tz=tz)
ser = Series(dti)
@@ -2376,12 +2353,9 @@ def test_ufunc_coercions(self):
tm.assert_index_equal(result, exp)
assert result.freq == exp.freq
- @pytest.mark.parametrize(
- "names", [("foo", None, None), ("baz", "bar", None), ("bar", "bar", "bar")]
- )
- @pytest.mark.parametrize("tz", [None, "America/Chicago"])
- def test_dti_add_series(self, tz, names):
+ def test_dti_add_series(self, tz_naive_fixture, names):
# GH#13905
+ tz = tz_naive_fixture
index = DatetimeIndex(
["2016-06-28 05:30", "2016-06-28 05:31"], tz=tz, name=names[0]
)
@@ -2403,9 +2377,6 @@ def test_dti_add_series(self, tz, names):
tm.assert_index_equal(result4, expected)
@pytest.mark.parametrize("op", [operator.add, roperator.radd, operator.sub])
- @pytest.mark.parametrize(
- "names", [(None, None, None), ("foo", "bar", None), ("foo", "foo", "foo")]
- )
def test_dti_addsub_offset_arraylike(
self, tz_naive_fixture, names, op, index_or_series
):
diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py
index 0afa09d351895..b64a52a772419 100644
--- a/pandas/tests/arithmetic/test_timedelta64.py
+++ b/pandas/tests/arithmetic/test_timedelta64.py
@@ -1195,18 +1195,10 @@ def test_td64arr_sub_td64_array(self, box_with_array):
result = tdarr - tdi
tm.assert_equal(result, expected)
- @pytest.mark.parametrize(
- "names",
- [
- (None, None, None),
- ("Egon", "Venkman", None),
- ("NCC1701D", "NCC1701D", "NCC1701D"),
- ],
- )
def test_td64arr_add_sub_tdi(self, box, names):
# GH#17250 make sure result dtype is correct
# GH#19043 make sure names are propagated correctly
- if box is pd.DataFrame and names[1] == "Venkman":
+ if box is pd.DataFrame and names[1] != names[0]:
pytest.skip(
"Name propagation for DataFrame does not behave like "
"it does for Index/Series"
@@ -1307,12 +1299,9 @@ def test_td64arr_sub_timedeltalike(self, two_hours, box_with_array):
# ------------------------------------------------------------------
# __add__/__sub__ with DateOffsets and arrays of DateOffsets
- @pytest.mark.parametrize(
- "names", [(None, None, None), ("foo", "bar", None), ("foo", "foo", "foo")]
- )
def test_td64arr_add_offset_index(self, names, box):
# GH#18849, GH#19744
- if box is pd.DataFrame and names[1] == "bar":
+ if box is pd.DataFrame and names[1] != names[0]:
pytest.skip(
"Name propagation for DataFrame does not behave like "
"it does for Index/Series"
@@ -2041,14 +2030,6 @@ def test_td64arr_div_numeric_array(self, box_with_array, vector, any_real_dtype)
with pytest.raises(TypeError, match=pattern):
vector.astype(object) / tdser
- @pytest.mark.parametrize(
- "names",
- [
- (None, None, None),
- ("Egon", "Venkman", None),
- ("NCC1701D", "NCC1701D", "NCC1701D"),
- ],
- )
def test_td64arr_mul_int_series(self, box_df_fail, names):
# GH#19042 test for correct name attachment
box = box_df_fail # broadcasts along wrong axis, but doesn't raise
@@ -2078,14 +2059,6 @@ def test_td64arr_mul_int_series(self, box_df_fail, names):
tm.assert_equal(result, expected)
# TODO: Should we be parametrizing over types for `ser` too?
- @pytest.mark.parametrize(
- "names",
- [
- (None, None, None),
- ("Egon", "Venkman", None),
- ("NCC1701D", "NCC1701D", "NCC1701D"),
- ],
- )
def test_float_series_rdiv_td64arr(self, box_with_array, names):
# GH#19042 test for correct name attachment
# TODO: the direct operation TimedeltaIndex / Series still
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
In the course of parametrizing tests, found a failing case. The edit in ops.dispatch fixes it. | https://api.github.com/repos/pandas-dev/pandas/pulls/33824 | 2020-04-27T17:09:45Z | 2020-04-27T20:24:43Z | 2020-04-27T20:24:43Z | 2020-04-27T21:33:04Z |
REF: collect set_index tests | diff --git a/pandas/tests/frame/methods/test_set_index.py b/pandas/tests/frame/methods/test_set_index.py
new file mode 100644
index 0000000000000..5f62697cc3e43
--- /dev/null
+++ b/pandas/tests/frame/methods/test_set_index.py
@@ -0,0 +1,532 @@
+from datetime import datetime, timedelta
+
+import numpy as np
+import pytest
+
+from pandas import DataFrame, DatetimeIndex, Index, MultiIndex, Series, date_range
+import pandas._testing as tm
+
+
+class TestSetIndex:
+ def test_set_index_empty_column(self):
+ # GH#1971
+ df = DataFrame(
+ [
+ {"a": 1, "p": 0},
+ {"a": 2, "m": 10},
+ {"a": 3, "m": 11, "p": 20},
+ {"a": 4, "m": 12, "p": 21},
+ ],
+ columns=["a", "m", "p", "x"],
+ )
+
+ result = df.set_index(["a", "x"])
+
+ expected = df[["m", "p"]]
+ expected.index = MultiIndex.from_arrays([df["a"], df["x"]], names=["a", "x"])
+ tm.assert_frame_equal(result, expected)
+
+ def test_set_index_multiindexcolumns(self):
+ columns = MultiIndex.from_tuples([("foo", 1), ("foo", 2), ("bar", 1)])
+ df = DataFrame(np.random.randn(3, 3), columns=columns)
+
+ result = df.set_index(df.columns[0])
+
+ expected = df.iloc[:, 1:]
+ expected.index = df.iloc[:, 0].values
+ expected.index.names = [df.columns[0]]
+ tm.assert_frame_equal(result, expected)
+
+ def test_set_index_timezone(self):
+ # GH#12358
+ # tz-aware Series should retain the tz
+ idx = DatetimeIndex(["2014-01-01 10:10:10"], tz="UTC").tz_convert("Europe/Rome")
+ df = DataFrame({"A": idx})
+ assert df.set_index(idx).index[0].hour == 11
+ assert DatetimeIndex(Series(df.A))[0].hour == 11
+ assert df.set_index(df.A).index[0].hour == 11
+
+ def test_set_index_cast_datetimeindex(self):
+ df = DataFrame(
+ {
+ "A": [datetime(2000, 1, 1) + timedelta(i) for i in range(1000)],
+ "B": np.random.randn(1000),
+ }
+ )
+
+ idf = df.set_index("A")
+ assert isinstance(idf.index, DatetimeIndex)
+
+ def test_set_index_dst(self):
+ di = date_range("2006-10-29 00:00:00", periods=3, freq="H", tz="US/Pacific")
+
+ df = DataFrame(data={"a": [0, 1, 2], "b": [3, 4, 5]}, index=di).reset_index()
+ # single level
+ res = df.set_index("index")
+ exp = DataFrame(
+ data={"a": [0, 1, 2], "b": [3, 4, 5]}, index=Index(di, name="index")
+ )
+ tm.assert_frame_equal(res, exp)
+
+ # GH#12920
+ res = df.set_index(["index", "a"])
+ exp_index = MultiIndex.from_arrays([di, [0, 1, 2]], names=["index", "a"])
+ exp = DataFrame({"b": [3, 4, 5]}, index=exp_index)
+ tm.assert_frame_equal(res, exp)
+
+ def test_set_index(self, float_string_frame):
+ df = float_string_frame
+ idx = Index(np.arange(len(df))[::-1])
+
+ df = df.set_index(idx)
+ tm.assert_index_equal(df.index, idx)
+ with pytest.raises(ValueError, match="Length mismatch"):
+ df.set_index(idx[::2])
+
+ def test_set_index_names(self):
+ df = tm.makeDataFrame()
+ df.index.name = "name"
+
+ assert df.set_index(df.index).index.names == ["name"]
+
+ mi = MultiIndex.from_arrays(df[["A", "B"]].T.values, names=["A", "B"])
+ mi2 = MultiIndex.from_arrays(
+ df[["A", "B", "A", "B"]].T.values, names=["A", "B", "C", "D"]
+ )
+
+ df = df.set_index(["A", "B"])
+
+ assert df.set_index(df.index).index.names == ["A", "B"]
+
+ # Check that set_index isn't converting a MultiIndex into an Index
+ assert isinstance(df.set_index(df.index).index, MultiIndex)
+
+ # Check actual equality
+ tm.assert_index_equal(df.set_index(df.index).index, mi)
+
+ idx2 = df.index.rename(["C", "D"])
+
+ # Check that [MultiIndex, MultiIndex] yields a MultiIndex rather
+ # than a pair of tuples
+ assert isinstance(df.set_index([df.index, idx2]).index, MultiIndex)
+
+ # Check equality
+ tm.assert_index_equal(df.set_index([df.index, idx2]).index, mi2)
+
+ def test_set_index_cast(self):
+ # issue casting an index then set_index
+ df = DataFrame(
+ {"A": [1.1, 2.2, 3.3], "B": [5.0, 6.1, 7.2]}, index=[2010, 2011, 2012]
+ )
+ df2 = df.set_index(df.index.astype(np.int32))
+ tm.assert_frame_equal(df, df2)
+
+ # A has duplicate values, C does not
+ @pytest.mark.parametrize("keys", ["A", "C", ["A", "B"], ("tuple", "as", "label")])
+ @pytest.mark.parametrize("inplace", [True, False])
+ @pytest.mark.parametrize("drop", [True, False])
+ def test_set_index_drop_inplace(self, frame_of_index_cols, drop, inplace, keys):
+ df = frame_of_index_cols
+
+ if isinstance(keys, list):
+ idx = MultiIndex.from_arrays([df[x] for x in keys], names=keys)
+ else:
+ idx = Index(df[keys], name=keys)
+ expected = df.drop(keys, axis=1) if drop else df
+ expected.index = idx
+
+ if inplace:
+ result = df.copy()
+ result.set_index(keys, drop=drop, inplace=True)
+ else:
+ result = df.set_index(keys, drop=drop)
+
+ tm.assert_frame_equal(result, expected)
+
+ # A has duplicate values, C does not
+ @pytest.mark.parametrize("keys", ["A", "C", ["A", "B"], ("tuple", "as", "label")])
+ @pytest.mark.parametrize("drop", [True, False])
+ def test_set_index_append(self, frame_of_index_cols, drop, keys):
+ df = frame_of_index_cols
+
+ keys = keys if isinstance(keys, list) else [keys]
+ idx = MultiIndex.from_arrays(
+ [df.index] + [df[x] for x in keys], names=[None] + keys
+ )
+ expected = df.drop(keys, axis=1) if drop else df.copy()
+ expected.index = idx
+
+ result = df.set_index(keys, drop=drop, append=True)
+
+ tm.assert_frame_equal(result, expected)
+
+ # A has duplicate values, C does not
+ @pytest.mark.parametrize("keys", ["A", "C", ["A", "B"], ("tuple", "as", "label")])
+ @pytest.mark.parametrize("drop", [True, False])
+ def test_set_index_append_to_multiindex(self, frame_of_index_cols, drop, keys):
+ # append to existing multiindex
+ df = frame_of_index_cols.set_index(["D"], drop=drop, append=True)
+
+ keys = keys if isinstance(keys, list) else [keys]
+ expected = frame_of_index_cols.set_index(["D"] + keys, drop=drop, append=True)
+
+ result = df.set_index(keys, drop=drop, append=True)
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_set_index_after_mutation(self):
+ # GH#1590
+ df = DataFrame({"val": [0, 1, 2], "key": ["a", "b", "c"]})
+ expected = DataFrame({"val": [1, 2]}, Index(["b", "c"], name="key"))
+
+ df2 = df.loc[df.index.map(lambda indx: indx >= 1)]
+ result = df2.set_index("key")
+ tm.assert_frame_equal(result, expected)
+
+ # MultiIndex constructor does not work directly on Series -> lambda
+ # Add list-of-list constructor because list is ambiguous -> lambda
+ # also test index name if append=True (name is duplicate here for B)
+ @pytest.mark.parametrize(
+ "box",
+ [
+ Series,
+ Index,
+ np.array,
+ list,
+ lambda x: [list(x)],
+ lambda x: MultiIndex.from_arrays([x]),
+ ],
+ )
+ @pytest.mark.parametrize(
+ "append, index_name", [(True, None), (True, "B"), (True, "test"), (False, None)]
+ )
+ @pytest.mark.parametrize("drop", [True, False])
+ def test_set_index_pass_single_array(
+ self, frame_of_index_cols, drop, append, index_name, box
+ ):
+ df = frame_of_index_cols
+ df.index.name = index_name
+
+ key = box(df["B"])
+ if box == list:
+ # list of strings gets interpreted as list of keys
+ msg = "['one', 'two', 'three', 'one', 'two']"
+ with pytest.raises(KeyError, match=msg):
+ df.set_index(key, drop=drop, append=append)
+ else:
+ # np.array/list-of-list "forget" the name of B
+ name_mi = getattr(key, "names", None)
+ name = [getattr(key, "name", None)] if name_mi is None else name_mi
+
+ result = df.set_index(key, drop=drop, append=append)
+
+ # only valid column keys are dropped
+ # since B is always passed as array above, nothing is dropped
+ expected = df.set_index(["B"], drop=False, append=append)
+ expected.index.names = [index_name] + name if append else name
+
+ tm.assert_frame_equal(result, expected)
+
+ # MultiIndex constructor does not work directly on Series -> lambda
+ # also test index name if append=True (name is duplicate here for A & B)
+ @pytest.mark.parametrize(
+ "box", [Series, Index, np.array, list, lambda x: MultiIndex.from_arrays([x])]
+ )
+ @pytest.mark.parametrize(
+ "append, index_name",
+ [(True, None), (True, "A"), (True, "B"), (True, "test"), (False, None)],
+ )
+ @pytest.mark.parametrize("drop", [True, False])
+ def test_set_index_pass_arrays(
+ self, frame_of_index_cols, drop, append, index_name, box
+ ):
+ df = frame_of_index_cols
+ df.index.name = index_name
+
+ keys = ["A", box(df["B"])]
+ # np.array/list "forget" the name of B
+ names = ["A", None if box in [np.array, list, tuple, iter] else "B"]
+
+ result = df.set_index(keys, drop=drop, append=append)
+
+ # only valid column keys are dropped
+ # since B is always passed as array above, only A is dropped, if at all
+ expected = df.set_index(["A", "B"], drop=False, append=append)
+ expected = expected.drop("A", axis=1) if drop else expected
+ expected.index.names = [index_name] + names if append else names
+
+ tm.assert_frame_equal(result, expected)
+
+ # MultiIndex constructor does not work directly on Series -> lambda
+ # We also emulate a "constructor" for the label -> lambda
+ # also test index name if append=True (name is duplicate here for A)
+ @pytest.mark.parametrize(
+ "box2",
+ [
+ Series,
+ Index,
+ np.array,
+ list,
+ iter,
+ lambda x: MultiIndex.from_arrays([x]),
+ lambda x: x.name,
+ ],
+ )
+ @pytest.mark.parametrize(
+ "box1",
+ [
+ Series,
+ Index,
+ np.array,
+ list,
+ iter,
+ lambda x: MultiIndex.from_arrays([x]),
+ lambda x: x.name,
+ ],
+ )
+ @pytest.mark.parametrize(
+ "append, index_name", [(True, None), (True, "A"), (True, "test"), (False, None)]
+ )
+ @pytest.mark.parametrize("drop", [True, False])
+ def test_set_index_pass_arrays_duplicate(
+ self, frame_of_index_cols, drop, append, index_name, box1, box2
+ ):
+ df = frame_of_index_cols
+ df.index.name = index_name
+
+ keys = [box1(df["A"]), box2(df["A"])]
+ result = df.set_index(keys, drop=drop, append=append)
+
+ # if either box is iter, it has been consumed; re-read
+ keys = [box1(df["A"]), box2(df["A"])]
+
+ # need to adapt first drop for case that both keys are 'A' --
+ # cannot drop the same column twice;
+ # plain == would give ambiguous Boolean error for containers
+ first_drop = (
+ False
+ if (
+ isinstance(keys[0], str)
+ and keys[0] == "A"
+ and isinstance(keys[1], str)
+ and keys[1] == "A"
+ )
+ else drop
+ )
+ # to test against already-tested behaviour, we add sequentially,
+ # hence second append always True; must wrap keys in list, otherwise
+ # box = list would be interpreted as keys
+ expected = df.set_index([keys[0]], drop=first_drop, append=append)
+ expected = expected.set_index([keys[1]], drop=drop, append=True)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("append", [True, False])
+ @pytest.mark.parametrize("drop", [True, False])
+ def test_set_index_pass_multiindex(self, frame_of_index_cols, drop, append):
+ df = frame_of_index_cols
+ keys = MultiIndex.from_arrays([df["A"], df["B"]], names=["A", "B"])
+
+ result = df.set_index(keys, drop=drop, append=append)
+
+ # setting with a MultiIndex will never drop columns
+ expected = df.set_index(["A", "B"], drop=False, append=append)
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_construction_with_categorical_index(self):
+ ci = tm.makeCategoricalIndex(10)
+ ci.name = "B"
+
+ # with Categorical
+ df = DataFrame({"A": np.random.randn(10), "B": ci.values})
+ idf = df.set_index("B")
+ tm.assert_index_equal(idf.index, ci)
+
+ # from a CategoricalIndex
+ df = DataFrame({"A": np.random.randn(10), "B": ci})
+ idf = df.set_index("B")
+ tm.assert_index_equal(idf.index, ci)
+
+ # round-trip
+ idf = idf.reset_index().set_index("B")
+ tm.assert_index_equal(idf.index, ci)
+
+
+class TestSetIndexInvalid:
+ def test_set_index_verify_integrity(self, frame_of_index_cols):
+ df = frame_of_index_cols
+
+ with pytest.raises(ValueError, match="Index has duplicate keys"):
+ df.set_index("A", verify_integrity=True)
+ # with MultiIndex
+ with pytest.raises(ValueError, match="Index has duplicate keys"):
+ df.set_index([df["A"], df["A"]], verify_integrity=True)
+
+ @pytest.mark.parametrize("append", [True, False])
+ @pytest.mark.parametrize("drop", [True, False])
+ def test_set_index_raise_keys(self, frame_of_index_cols, drop, append):
+ df = frame_of_index_cols
+
+ with pytest.raises(KeyError, match="['foo', 'bar', 'baz']"):
+ # column names are A-E, as well as one tuple
+ df.set_index(["foo", "bar", "baz"], drop=drop, append=append)
+
+ # non-existent key in list with arrays
+ with pytest.raises(KeyError, match="X"):
+ df.set_index([df["A"], df["B"], "X"], drop=drop, append=append)
+
+ msg = "[('foo', 'foo', 'foo', 'bar', 'bar')]"
+ # tuples always raise KeyError
+ with pytest.raises(KeyError, match=msg):
+ df.set_index(tuple(df["A"]), drop=drop, append=append)
+
+ # also within a list
+ with pytest.raises(KeyError, match=msg):
+ df.set_index(["A", df["A"], tuple(df["A"])], drop=drop, append=append)
+
+ @pytest.mark.parametrize("append", [True, False])
+ @pytest.mark.parametrize("drop", [True, False])
+ @pytest.mark.parametrize("box", [set], ids=["set"])
+ def test_set_index_raise_on_type(self, frame_of_index_cols, box, drop, append):
+ df = frame_of_index_cols
+
+ msg = 'The parameter "keys" may be a column key, .*'
+ # forbidden type, e.g. set
+ with pytest.raises(TypeError, match=msg):
+ df.set_index(box(df["A"]), drop=drop, append=append)
+
+ # forbidden type in list, e.g. set
+ with pytest.raises(TypeError, match=msg):
+ df.set_index(["A", df["A"], box(df["A"])], drop=drop, append=append)
+
+ # MultiIndex constructor does not work directly on Series -> lambda
+ @pytest.mark.parametrize(
+ "box",
+ [Series, Index, np.array, iter, lambda x: MultiIndex.from_arrays([x])],
+ ids=["Series", "Index", "np.array", "iter", "MultiIndex"],
+ )
+ @pytest.mark.parametrize("length", [4, 6], ids=["too_short", "too_long"])
+ @pytest.mark.parametrize("append", [True, False])
+ @pytest.mark.parametrize("drop", [True, False])
+ def test_set_index_raise_on_len(
+ self, frame_of_index_cols, box, length, drop, append
+ ):
+ # GH 24984
+ df = frame_of_index_cols # has length 5
+
+ values = np.random.randint(0, 10, (length,))
+
+ msg = "Length mismatch: Expected 5 rows, received array of length.*"
+
+ # wrong length directly
+ with pytest.raises(ValueError, match=msg):
+ df.set_index(box(values), drop=drop, append=append)
+
+ # wrong length in list
+ with pytest.raises(ValueError, match=msg):
+ df.set_index(["A", df.A, box(values)], drop=drop, append=append)
+
+
+class TestSetIndexCustomLabelType:
+ def test_set_index_custom_label_type(self):
+ # GH#24969
+
+ class Thing:
+ def __init__(self, name, color):
+ self.name = name
+ self.color = color
+
+ def __str__(self) -> str:
+ return f"<Thing {repr(self.name)}>"
+
+ # necessary for pretty KeyError
+ __repr__ = __str__
+
+ thing1 = Thing("One", "red")
+ thing2 = Thing("Two", "blue")
+ df = DataFrame({thing1: [0, 1], thing2: [2, 3]})
+ expected = DataFrame({thing1: [0, 1]}, index=Index([2, 3], name=thing2))
+
+ # use custom label directly
+ result = df.set_index(thing2)
+ tm.assert_frame_equal(result, expected)
+
+ # custom label wrapped in list
+ result = df.set_index([thing2])
+ tm.assert_frame_equal(result, expected)
+
+ # missing key
+ thing3 = Thing("Three", "pink")
+ msg = "<Thing 'Three'>"
+ with pytest.raises(KeyError, match=msg):
+ # missing label directly
+ df.set_index(thing3)
+
+ with pytest.raises(KeyError, match=msg):
+ # missing label in list
+ df.set_index([thing3])
+
+ def test_set_index_custom_label_hashable_iterable(self):
+ # GH#24969
+
+ # actual example discussed in GH 24984 was e.g. for shapely.geometry
+ # objects (e.g. a collection of Points) that can be both hashable and
+ # iterable; using frozenset as a stand-in for testing here
+
+ class Thing(frozenset):
+ # need to stabilize repr for KeyError (due to random order in sets)
+ def __repr__(self) -> str:
+ tmp = sorted(self)
+ joined_reprs = ", ".join(map(repr, tmp))
+ # double curly brace prints one brace in format string
+ return f"frozenset({{{joined_reprs}}})"
+
+ thing1 = Thing(["One", "red"])
+ thing2 = Thing(["Two", "blue"])
+ df = DataFrame({thing1: [0, 1], thing2: [2, 3]})
+ expected = DataFrame({thing1: [0, 1]}, index=Index([2, 3], name=thing2))
+
+ # use custom label directly
+ result = df.set_index(thing2)
+ tm.assert_frame_equal(result, expected)
+
+ # custom label wrapped in list
+ result = df.set_index([thing2])
+ tm.assert_frame_equal(result, expected)
+
+ # missing key
+ thing3 = Thing(["Three", "pink"])
+ msg = r"frozenset\(\{'Three', 'pink'\}\)"
+ with pytest.raises(KeyError, match=msg):
+ # missing label directly
+ df.set_index(thing3)
+
+ with pytest.raises(KeyError, match=msg):
+ # missing label in list
+ df.set_index([thing3])
+
+ def test_set_index_custom_label_type_raises(self):
+ # GH#24969
+
+ # purposefully inherit from something unhashable
+ class Thing(set):
+ def __init__(self, name, color):
+ self.name = name
+ self.color = color
+
+ def __str__(self) -> str:
+ return f"<Thing {repr(self.name)}>"
+
+ thing1 = Thing("One", "red")
+ thing2 = Thing("Two", "blue")
+ df = DataFrame([[0, 2], [1, 3]], columns=[thing1, thing2])
+
+ msg = 'The parameter "keys" may be a column key, .*'
+
+ with pytest.raises(TypeError, match=msg):
+ # use custom label directly
+ df.set_index(thing2)
+
+ with pytest.raises(TypeError, match=msg):
+ # custom label wrapped in list
+ df.set_index([thing2])
diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py
index b28e8a5b347aa..cd23cd6aa9c63 100644
--- a/pandas/tests/frame/test_alter_axes.py
+++ b/pandas/tests/frame/test_alter_axes.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta
+from datetime import datetime
import inspect
import numpy as np
@@ -16,7 +16,6 @@
DatetimeIndex,
Index,
IntervalIndex,
- MultiIndex,
Series,
Timestamp,
cut,
@@ -36,440 +35,6 @@ def test_set_index_directly(self, float_string_frame):
with pytest.raises(ValueError, match="Length mismatch"):
df.index = idx[::2]
- def test_set_index(self, float_string_frame):
- df = float_string_frame
- idx = Index(np.arange(len(df))[::-1])
-
- df = df.set_index(idx)
- tm.assert_index_equal(df.index, idx)
- with pytest.raises(ValueError, match="Length mismatch"):
- df.set_index(idx[::2])
-
- def test_set_index_cast(self):
- # issue casting an index then set_index
- df = DataFrame(
- {"A": [1.1, 2.2, 3.3], "B": [5.0, 6.1, 7.2]}, index=[2010, 2011, 2012]
- )
- df2 = df.set_index(df.index.astype(np.int32))
- tm.assert_frame_equal(df, df2)
-
- # A has duplicate values, C does not
- @pytest.mark.parametrize("keys", ["A", "C", ["A", "B"], ("tuple", "as", "label")])
- @pytest.mark.parametrize("inplace", [True, False])
- @pytest.mark.parametrize("drop", [True, False])
- def test_set_index_drop_inplace(self, frame_of_index_cols, drop, inplace, keys):
- df = frame_of_index_cols
-
- if isinstance(keys, list):
- idx = MultiIndex.from_arrays([df[x] for x in keys], names=keys)
- else:
- idx = Index(df[keys], name=keys)
- expected = df.drop(keys, axis=1) if drop else df
- expected.index = idx
-
- if inplace:
- result = df.copy()
- result.set_index(keys, drop=drop, inplace=True)
- else:
- result = df.set_index(keys, drop=drop)
-
- tm.assert_frame_equal(result, expected)
-
- # A has duplicate values, C does not
- @pytest.mark.parametrize("keys", ["A", "C", ["A", "B"], ("tuple", "as", "label")])
- @pytest.mark.parametrize("drop", [True, False])
- def test_set_index_append(self, frame_of_index_cols, drop, keys):
- df = frame_of_index_cols
-
- keys = keys if isinstance(keys, list) else [keys]
- idx = MultiIndex.from_arrays(
- [df.index] + [df[x] for x in keys], names=[None] + keys
- )
- expected = df.drop(keys, axis=1) if drop else df.copy()
- expected.index = idx
-
- result = df.set_index(keys, drop=drop, append=True)
-
- tm.assert_frame_equal(result, expected)
-
- # A has duplicate values, C does not
- @pytest.mark.parametrize("keys", ["A", "C", ["A", "B"], ("tuple", "as", "label")])
- @pytest.mark.parametrize("drop", [True, False])
- def test_set_index_append_to_multiindex(self, frame_of_index_cols, drop, keys):
- # append to existing multiindex
- df = frame_of_index_cols.set_index(["D"], drop=drop, append=True)
-
- keys = keys if isinstance(keys, list) else [keys]
- expected = frame_of_index_cols.set_index(["D"] + keys, drop=drop, append=True)
-
- result = df.set_index(keys, drop=drop, append=True)
-
- tm.assert_frame_equal(result, expected)
-
- def test_set_index_after_mutation(self):
- # GH1590
- df = DataFrame({"val": [0, 1, 2], "key": ["a", "b", "c"]})
- expected = DataFrame({"val": [1, 2]}, Index(["b", "c"], name="key"))
-
- df2 = df.loc[df.index.map(lambda indx: indx >= 1)]
- result = df2.set_index("key")
- tm.assert_frame_equal(result, expected)
-
- # MultiIndex constructor does not work directly on Series -> lambda
- # Add list-of-list constructor because list is ambiguous -> lambda
- # also test index name if append=True (name is duplicate here for B)
- @pytest.mark.parametrize(
- "box",
- [
- Series,
- Index,
- np.array,
- list,
- lambda x: [list(x)],
- lambda x: MultiIndex.from_arrays([x]),
- ],
- )
- @pytest.mark.parametrize(
- "append, index_name", [(True, None), (True, "B"), (True, "test"), (False, None)]
- )
- @pytest.mark.parametrize("drop", [True, False])
- def test_set_index_pass_single_array(
- self, frame_of_index_cols, drop, append, index_name, box
- ):
- df = frame_of_index_cols
- df.index.name = index_name
-
- key = box(df["B"])
- if box == list:
- # list of strings gets interpreted as list of keys
- msg = "['one', 'two', 'three', 'one', 'two']"
- with pytest.raises(KeyError, match=msg):
- df.set_index(key, drop=drop, append=append)
- else:
- # np.array/list-of-list "forget" the name of B
- name_mi = getattr(key, "names", None)
- name = [getattr(key, "name", None)] if name_mi is None else name_mi
-
- result = df.set_index(key, drop=drop, append=append)
-
- # only valid column keys are dropped
- # since B is always passed as array above, nothing is dropped
- expected = df.set_index(["B"], drop=False, append=append)
- expected.index.names = [index_name] + name if append else name
-
- tm.assert_frame_equal(result, expected)
-
- # MultiIndex constructor does not work directly on Series -> lambda
- # also test index name if append=True (name is duplicate here for A & B)
- @pytest.mark.parametrize(
- "box", [Series, Index, np.array, list, lambda x: MultiIndex.from_arrays([x])]
- )
- @pytest.mark.parametrize(
- "append, index_name",
- [(True, None), (True, "A"), (True, "B"), (True, "test"), (False, None)],
- )
- @pytest.mark.parametrize("drop", [True, False])
- def test_set_index_pass_arrays(
- self, frame_of_index_cols, drop, append, index_name, box
- ):
- df = frame_of_index_cols
- df.index.name = index_name
-
- keys = ["A", box(df["B"])]
- # np.array/list "forget" the name of B
- names = ["A", None if box in [np.array, list, tuple, iter] else "B"]
-
- result = df.set_index(keys, drop=drop, append=append)
-
- # only valid column keys are dropped
- # since B is always passed as array above, only A is dropped, if at all
- expected = df.set_index(["A", "B"], drop=False, append=append)
- expected = expected.drop("A", axis=1) if drop else expected
- expected.index.names = [index_name] + names if append else names
-
- tm.assert_frame_equal(result, expected)
-
- # MultiIndex constructor does not work directly on Series -> lambda
- # We also emulate a "constructor" for the label -> lambda
- # also test index name if append=True (name is duplicate here for A)
- @pytest.mark.parametrize(
- "box2",
- [
- Series,
- Index,
- np.array,
- list,
- iter,
- lambda x: MultiIndex.from_arrays([x]),
- lambda x: x.name,
- ],
- )
- @pytest.mark.parametrize(
- "box1",
- [
- Series,
- Index,
- np.array,
- list,
- iter,
- lambda x: MultiIndex.from_arrays([x]),
- lambda x: x.name,
- ],
- )
- @pytest.mark.parametrize(
- "append, index_name", [(True, None), (True, "A"), (True, "test"), (False, None)]
- )
- @pytest.mark.parametrize("drop", [True, False])
- def test_set_index_pass_arrays_duplicate(
- self, frame_of_index_cols, drop, append, index_name, box1, box2
- ):
- df = frame_of_index_cols
- df.index.name = index_name
-
- keys = [box1(df["A"]), box2(df["A"])]
- result = df.set_index(keys, drop=drop, append=append)
-
- # if either box is iter, it has been consumed; re-read
- keys = [box1(df["A"]), box2(df["A"])]
-
- # need to adapt first drop for case that both keys are 'A' --
- # cannot drop the same column twice;
- # plain == would give ambiguous Boolean error for containers
- first_drop = (
- False
- if (
- isinstance(keys[0], str)
- and keys[0] == "A"
- and isinstance(keys[1], str)
- and keys[1] == "A"
- )
- else drop
- )
- # to test against already-tested behaviour, we add sequentially,
- # hence second append always True; must wrap keys in list, otherwise
- # box = list would be interpreted as keys
- expected = df.set_index([keys[0]], drop=first_drop, append=append)
- expected = expected.set_index([keys[1]], drop=drop, append=True)
- tm.assert_frame_equal(result, expected)
-
- @pytest.mark.parametrize("append", [True, False])
- @pytest.mark.parametrize("drop", [True, False])
- def test_set_index_pass_multiindex(self, frame_of_index_cols, drop, append):
- df = frame_of_index_cols
- keys = MultiIndex.from_arrays([df["A"], df["B"]], names=["A", "B"])
-
- result = df.set_index(keys, drop=drop, append=append)
-
- # setting with a MultiIndex will never drop columns
- expected = df.set_index(["A", "B"], drop=False, append=append)
-
- tm.assert_frame_equal(result, expected)
-
- def test_set_index_verify_integrity(self, frame_of_index_cols):
- df = frame_of_index_cols
-
- with pytest.raises(ValueError, match="Index has duplicate keys"):
- df.set_index("A", verify_integrity=True)
- # with MultiIndex
- with pytest.raises(ValueError, match="Index has duplicate keys"):
- df.set_index([df["A"], df["A"]], verify_integrity=True)
-
- @pytest.mark.parametrize("append", [True, False])
- @pytest.mark.parametrize("drop", [True, False])
- def test_set_index_raise_keys(self, frame_of_index_cols, drop, append):
- df = frame_of_index_cols
-
- with pytest.raises(KeyError, match="['foo', 'bar', 'baz']"):
- # column names are A-E, as well as one tuple
- df.set_index(["foo", "bar", "baz"], drop=drop, append=append)
-
- # non-existent key in list with arrays
- with pytest.raises(KeyError, match="X"):
- df.set_index([df["A"], df["B"], "X"], drop=drop, append=append)
-
- msg = "[('foo', 'foo', 'foo', 'bar', 'bar')]"
- # tuples always raise KeyError
- with pytest.raises(KeyError, match=msg):
- df.set_index(tuple(df["A"]), drop=drop, append=append)
-
- # also within a list
- with pytest.raises(KeyError, match=msg):
- df.set_index(["A", df["A"], tuple(df["A"])], drop=drop, append=append)
-
- @pytest.mark.parametrize("append", [True, False])
- @pytest.mark.parametrize("drop", [True, False])
- @pytest.mark.parametrize("box", [set], ids=["set"])
- def test_set_index_raise_on_type(self, frame_of_index_cols, box, drop, append):
- df = frame_of_index_cols
-
- msg = 'The parameter "keys" may be a column key, .*'
- # forbidden type, e.g. set
- with pytest.raises(TypeError, match=msg):
- df.set_index(box(df["A"]), drop=drop, append=append)
-
- # forbidden type in list, e.g. set
- with pytest.raises(TypeError, match=msg):
- df.set_index(["A", df["A"], box(df["A"])], drop=drop, append=append)
-
- # MultiIndex constructor does not work directly on Series -> lambda
- @pytest.mark.parametrize(
- "box",
- [Series, Index, np.array, iter, lambda x: MultiIndex.from_arrays([x])],
- ids=["Series", "Index", "np.array", "iter", "MultiIndex"],
- )
- @pytest.mark.parametrize("length", [4, 6], ids=["too_short", "too_long"])
- @pytest.mark.parametrize("append", [True, False])
- @pytest.mark.parametrize("drop", [True, False])
- def test_set_index_raise_on_len(
- self, frame_of_index_cols, box, length, drop, append
- ):
- # GH 24984
- df = frame_of_index_cols # has length 5
-
- values = np.random.randint(0, 10, (length,))
-
- msg = "Length mismatch: Expected 5 rows, received array of length.*"
-
- # wrong length directly
- with pytest.raises(ValueError, match=msg):
- df.set_index(box(values), drop=drop, append=append)
-
- # wrong length in list
- with pytest.raises(ValueError, match=msg):
- df.set_index(["A", df.A, box(values)], drop=drop, append=append)
-
- def test_set_index_custom_label_type(self):
- # GH 24969
-
- class Thing:
- def __init__(self, name, color):
- self.name = name
- self.color = color
-
- def __str__(self) -> str:
- return f"<Thing {repr(self.name)}>"
-
- # necessary for pretty KeyError
- __repr__ = __str__
-
- thing1 = Thing("One", "red")
- thing2 = Thing("Two", "blue")
- df = DataFrame({thing1: [0, 1], thing2: [2, 3]})
- expected = DataFrame({thing1: [0, 1]}, index=Index([2, 3], name=thing2))
-
- # use custom label directly
- result = df.set_index(thing2)
- tm.assert_frame_equal(result, expected)
-
- # custom label wrapped in list
- result = df.set_index([thing2])
- tm.assert_frame_equal(result, expected)
-
- # missing key
- thing3 = Thing("Three", "pink")
- msg = "<Thing 'Three'>"
- with pytest.raises(KeyError, match=msg):
- # missing label directly
- df.set_index(thing3)
-
- with pytest.raises(KeyError, match=msg):
- # missing label in list
- df.set_index([thing3])
-
- def test_set_index_custom_label_hashable_iterable(self):
- # GH 24969
-
- # actual example discussed in GH 24984 was e.g. for shapely.geometry
- # objects (e.g. a collection of Points) that can be both hashable and
- # iterable; using frozenset as a stand-in for testing here
-
- class Thing(frozenset):
- # need to stabilize repr for KeyError (due to random order in sets)
- def __repr__(self) -> str:
- tmp = sorted(self)
- joined_reprs = ", ".join(map(repr, tmp))
- # double curly brace prints one brace in format string
- return f"frozenset({{{joined_reprs}}})"
-
- thing1 = Thing(["One", "red"])
- thing2 = Thing(["Two", "blue"])
- df = DataFrame({thing1: [0, 1], thing2: [2, 3]})
- expected = DataFrame({thing1: [0, 1]}, index=Index([2, 3], name=thing2))
-
- # use custom label directly
- result = df.set_index(thing2)
- tm.assert_frame_equal(result, expected)
-
- # custom label wrapped in list
- result = df.set_index([thing2])
- tm.assert_frame_equal(result, expected)
-
- # missing key
- thing3 = Thing(["Three", "pink"])
- msg = r"frozenset\(\{'Three', 'pink'\}\)"
- with pytest.raises(KeyError, match=msg):
- # missing label directly
- df.set_index(thing3)
-
- with pytest.raises(KeyError, match=msg):
- # missing label in list
- df.set_index([thing3])
-
- def test_set_index_custom_label_type_raises(self):
- # GH 24969
-
- # purposefully inherit from something unhashable
- class Thing(set):
- def __init__(self, name, color):
- self.name = name
- self.color = color
-
- def __str__(self) -> str:
- return f"<Thing {repr(self.name)}>"
-
- thing1 = Thing("One", "red")
- thing2 = Thing("Two", "blue")
- df = DataFrame([[0, 2], [1, 3]], columns=[thing1, thing2])
-
- msg = 'The parameter "keys" may be a column key, .*'
-
- with pytest.raises(TypeError, match=msg):
- # use custom label directly
- df.set_index(thing2)
-
- with pytest.raises(TypeError, match=msg):
- # custom label wrapped in list
- df.set_index([thing2])
-
- def test_construction_with_categorical_index(self):
- ci = tm.makeCategoricalIndex(10)
- ci.name = "B"
-
- # with Categorical
- df = DataFrame({"A": np.random.randn(10), "B": ci.values})
- idf = df.set_index("B")
- tm.assert_index_equal(idf.index, ci)
-
- # from a CategoricalIndex
- df = DataFrame({"A": np.random.randn(10), "B": ci})
- idf = df.set_index("B")
- tm.assert_index_equal(idf.index, ci)
-
- # round-trip
- idf = idf.reset_index().set_index("B")
- tm.assert_index_equal(idf.index, ci)
-
- def test_set_index_cast_datetimeindex(self):
- df = DataFrame(
- {
- "A": [datetime(2000, 1, 1) + timedelta(i) for i in range(1000)],
- "B": np.random.randn(1000),
- }
- )
-
- idf = df.set_index("A")
- assert isinstance(idf.index, DatetimeIndex)
-
def test_convert_dti_to_series(self):
# don't cast a DatetimeIndex WITH a tz, leave as object
# GH 6032
@@ -538,58 +103,6 @@ def test_convert_dti_to_series(self):
df.pop("ts")
tm.assert_frame_equal(df, expected)
- def test_set_index_timezone(self):
- # GH 12358
- # tz-aware Series should retain the tz
- idx = to_datetime(["2014-01-01 10:10:10"], utc=True).tz_convert("Europe/Rome")
- df = DataFrame({"A": idx})
- assert df.set_index(idx).index[0].hour == 11
- assert DatetimeIndex(Series(df.A))[0].hour == 11
- assert df.set_index(df.A).index[0].hour == 11
-
- def test_set_index_dst(self):
- di = date_range("2006-10-29 00:00:00", periods=3, freq="H", tz="US/Pacific")
-
- df = DataFrame(data={"a": [0, 1, 2], "b": [3, 4, 5]}, index=di).reset_index()
- # single level
- res = df.set_index("index")
- exp = DataFrame(
- data={"a": [0, 1, 2], "b": [3, 4, 5]}, index=Index(di, name="index")
- )
- tm.assert_frame_equal(res, exp)
-
- # GH 12920
- res = df.set_index(["index", "a"])
- exp_index = MultiIndex.from_arrays([di, [0, 1, 2]], names=["index", "a"])
- exp = DataFrame({"b": [3, 4, 5]}, index=exp_index)
- tm.assert_frame_equal(res, exp)
-
- def test_set_index_multiindexcolumns(self):
- columns = MultiIndex.from_tuples([("foo", 1), ("foo", 2), ("bar", 1)])
- df = DataFrame(np.random.randn(3, 3), columns=columns)
- result = df.set_index(df.columns[0])
- expected = df.iloc[:, 1:]
- expected.index = df.iloc[:, 0].values
- expected.index.names = [df.columns[0]]
- tm.assert_frame_equal(result, expected)
-
- def test_set_index_empty_column(self):
- # GH 1971
- df = DataFrame(
- [
- {"a": 1, "p": 0},
- {"a": 2, "m": 10},
- {"a": 3, "m": 11, "p": 20},
- {"a": 4, "m": 12, "p": 21},
- ],
- columns=("a", "m", "p", "x"),
- )
-
- result = df.set_index(["a", "x"])
- expected = df[["m", "p"]]
- expected.index = MultiIndex.from_arrays([df["a"], df["x"]], names=["a", "x"])
- tm.assert_frame_equal(result, expected)
-
def test_set_columns(self, float_string_frame):
cols = Index(np.arange(len(float_string_frame.columns)))
float_string_frame.columns = cols
@@ -622,36 +135,6 @@ def test_dti_set_index_reindex(self):
# Renaming
- def test_set_index_names(self):
- df = tm.makeDataFrame()
- df.index.name = "name"
-
- assert df.set_index(df.index).index.names == ["name"]
-
- mi = MultiIndex.from_arrays(df[["A", "B"]].T.values, names=["A", "B"])
- mi2 = MultiIndex.from_arrays(
- df[["A", "B", "A", "B"]].T.values, names=["A", "B", "C", "D"]
- )
-
- df = df.set_index(["A", "B"])
-
- assert df.set_index(df.index).index.names == ["A", "B"]
-
- # Check that set_index isn't converting a MultiIndex into an Index
- assert isinstance(df.set_index(df.index).index, MultiIndex)
-
- # Check actual equality
- tm.assert_index_equal(df.set_index(df.index).index, mi)
-
- idx2 = df.index.rename(["C", "D"])
-
- # Check that [MultiIndex, MultiIndex] yields a MultiIndex rather
- # than a pair of tuples
- assert isinstance(df.set_index([df.index, idx2]).index, MultiIndex)
-
- # Check equality
- tm.assert_index_equal(df.set_index([df.index, idx2]).index, mi2)
-
def test_reindex_api_equivalence(self):
# equivalence of the labels/axis and index/columns API's
df = DataFrame(
| https://api.github.com/repos/pandas-dev/pandas/pulls/33822 | 2020-04-27T15:31:46Z | 2020-04-27T18:57:12Z | 2020-04-27T18:57:12Z | 2020-04-27T19:35:36Z | |
BUG: repair 'style' kwd handling in DataFrame.plot (#21003) | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index 8b28a4439e1da..39e53daf516c4 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -299,7 +299,7 @@ I/O
Plotting
^^^^^^^^
--
+- Bug in :meth:`DataFrame.plot` where a marker letter in the ``style`` keyword sometimes causes a ``ValueError`` (:issue:`21003`)
-
Groupby/resample/rolling
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py
index f0b35e1cd2a74..def4a1dc3f5c4 100644
--- a/pandas/plotting/_matplotlib/core.py
+++ b/pandas/plotting/_matplotlib/core.py
@@ -1,4 +1,3 @@
-import re
from typing import TYPE_CHECKING, List, Optional, Tuple
import warnings
@@ -55,6 +54,15 @@
from matplotlib.axis import Axis
+def _color_in_style(style: str) -> bool:
+ """
+ Check if there is a color letter in the style string.
+ """
+ from matplotlib.colors import BASE_COLORS
+
+ return not set(BASE_COLORS).isdisjoint(style)
+
+
class MPLPlot:
"""
Base class for assembling a pandas plot using matplotlib
@@ -200,8 +208,6 @@ def __init__(
self._validate_color_args()
def _validate_color_args(self):
- import matplotlib.colors
-
if (
"color" in self.kwds
and self.nseries == 1
@@ -233,13 +239,12 @@ def _validate_color_args(self):
styles = [self.style]
# need only a single match
for s in styles:
- for char in s:
- if char in matplotlib.colors.BASE_COLORS:
- raise ValueError(
- "Cannot pass 'style' string with a color symbol and "
- "'color' keyword argument. Please use one or the other or "
- "pass 'style' without a color symbol"
- )
+ if _color_in_style(s):
+ raise ValueError(
+ "Cannot pass 'style' string with a color symbol and "
+ "'color' keyword argument. Please use one or the "
+ "other or pass 'style' without a color symbol"
+ )
def _iter_data(self, data=None, keep_index=False, fillna=None):
if data is None:
@@ -739,7 +744,7 @@ def _apply_style_colors(self, colors, kwds, col_num, label):
style = self.style
has_color = "color" in kwds or self.colormap is not None
- nocolor_style = style is None or re.match("[a-z]+", style) is None
+ nocolor_style = style is None or not _color_in_style(style)
if (has_color or self.subplots) and nocolor_style:
if isinstance(colors, dict):
kwds["color"] = colors[label]
diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py
index 9ab697cb57690..56c7cb4785668 100644
--- a/pandas/tests/plotting/test_frame.py
+++ b/pandas/tests/plotting/test_frame.py
@@ -205,6 +205,24 @@ def test_color_and_style_arguments(self):
with pytest.raises(ValueError):
df.plot(color=["red", "black"], style=["k-", "r--"])
+ @pytest.mark.parametrize(
+ "color, expected",
+ [
+ ("green", ["green"] * 4),
+ (["yellow", "red", "green", "blue"], ["yellow", "red", "green", "blue"]),
+ ],
+ )
+ def test_color_and_marker(self, color, expected):
+ # GH 21003
+ df = DataFrame(np.random.random((7, 4)))
+ ax = df.plot(color=color, style="d--")
+ # check colors
+ result = [i.get_color() for i in ax.lines]
+ assert result == expected
+ # check markers and linestyles
+ assert all(i.get_linestyle() == "--" for i in ax.lines)
+ assert all(i.get_marker() == "d" for i in ax.lines)
+
def test_nonnumeric_exclude(self):
df = DataFrame({"A": ["x", "y", "z"], "B": [1, 2, 3]})
ax = df.plot()
diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py
index c296e2a6278c5..85c06b2e7b748 100644
--- a/pandas/tests/plotting/test_series.py
+++ b/pandas/tests/plotting/test_series.py
@@ -958,7 +958,7 @@ def test_plot_no_numeric_data(self):
def test_style_single_ok(self):
s = pd.Series([1, 2])
ax = s.plot(style="s", color="C3")
- assert ax.lines[0].get_color() == ["C3"]
+ assert ax.lines[0].get_color() == "C3"
@pytest.mark.parametrize(
"index_name, old_label, new_label",
| - [x] closes #21003
- [x] tests added / passed
- [x] passes `black pandas`
=> `command not found`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
=> `command not found`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/33821 | 2020-04-27T14:16:13Z | 2020-09-05T14:49:10Z | 2020-09-05T14:49:09Z | 2020-09-22T05:26:04Z |
CLN/TYP: update setup.cfg | diff --git a/setup.cfg b/setup.cfg
index 79fe68b7e2dfe..d0216a05a2268 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -141,9 +141,6 @@ ignore_errors=True
[mypy-pandas.tests.tools.test_to_datetime]
ignore_errors=True
-[mypy-pandas.tests.scalar.period.test_period]
-ignore_errors=True
-
[mypy-pandas._testing]
check_untyped_defs=False
| ```
@pytest.mark.xfail(
StrictVersion(dateutil.__version__.split(".dev")[0]) < StrictVersion("2.7.0"),
reason="Bug in dateutil < 2.7.0 when parsing old dates: Period('0001-01-07', 'D')",
strict=False,
)
```
removed in #33680 | https://api.github.com/repos/pandas-dev/pandas/pulls/33818 | 2020-04-27T10:11:09Z | 2020-04-27T12:57:39Z | 2020-04-27T12:57:39Z | 2020-04-28T10:52:47Z |
TST: Separate expanding_apply and rolling_apply out of consistency | diff --git a/pandas/tests/window/moments/test_moments_expanding.py b/pandas/tests/window/moments/test_moments_expanding.py
index 01940d83a4fa9..a358f0e7057f3 100644
--- a/pandas/tests/window/moments/test_moments_expanding.py
+++ b/pandas/tests/window/moments/test_moments_expanding.py
@@ -368,6 +368,14 @@ def test_expanding_consistency(self, min_periods):
),
)
+ @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+ def test_expanding_apply_consistency(self, min_periods):
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ message=".*(empty slice|0 for slice).*",
+ category=RuntimeWarning,
+ )
# test consistency between expanding_xyz() and either (a)
# expanding_apply of Series.xyz(), or (b) expanding_apply of
# np.nanxyz()
diff --git a/pandas/tests/window/moments/test_moments_rolling.py b/pandas/tests/window/moments/test_moments_rolling.py
index 33e870df4d8b2..503f2e12bea03 100644
--- a/pandas/tests/window/moments/test_moments_rolling.py
+++ b/pandas/tests/window/moments/test_moments_rolling.py
@@ -1013,6 +1013,17 @@ def test_rolling_consistency(self, window, min_periods, center):
),
)
+ @pytest.mark.parametrize(
+ "window,min_periods,center", list(_rolling_consistency_cases())
+ )
+ def test_rolling_apply_consistency(self, window, min_periods, center):
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ message=".*(empty slice|0 for slice).*",
+ category=RuntimeWarning,
+ )
# test consistency between rolling_xyz() and either (a)
# rolling_apply of Series.xyz(), or (b) rolling_apply of
# np.nanxyz()
| xref #30577 #30486
This is the second step for breaking up giant consistency test, this PR separates consistency tests about `expanding_apply` and `rolling_apply` out from their big `expanding_consistency` and `rolling_consistency` tests.
The followup after this would be removing `self.data` initiation from `init` and convert to either fixture or funcs with yields so as to gradually move tests out of the whole consistency class and easier for parametrization instead of current looping.
cc @jreback
| https://api.github.com/repos/pandas-dev/pandas/pulls/33817 | 2020-04-27T08:40:49Z | 2020-04-27T20:55:56Z | 2020-04-27T20:55:56Z | 2020-04-27T20:56:39Z |
ERR: Add NumbaUtilError | diff --git a/doc/source/reference/general_utility_functions.rst b/doc/source/reference/general_utility_functions.rst
index 575b82b4b06de..6d43ceb74ab7c 100644
--- a/doc/source/reference/general_utility_functions.rst
+++ b/doc/source/reference/general_utility_functions.rst
@@ -35,9 +35,12 @@ Exceptions and warnings
.. autosummary::
:toctree: api/
+ errors.AccessorRegistrationWarning
errors.DtypeWarning
errors.EmptyDataError
errors.OutOfBoundsDatetime
+ errors.MergeError
+ errors.NumbaUtilError
errors.ParserError
errors.ParserWarning
errors.PerformanceWarning
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index 18752cdc1642e..e90a4eae10853 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -79,7 +79,6 @@
NUMBA_FUNC_CACHE,
check_kwargs_and_nopython,
get_jit_arguments,
- is_numba_util_related_error,
jit_user_function,
split_for_numba,
validate_udf,
@@ -283,10 +282,8 @@ def aggregate(
return self._python_agg_general(
func, *args, engine=engine, engine_kwargs=engine_kwargs, **kwargs
)
- except (ValueError, KeyError) as err:
+ except (ValueError, KeyError):
# Do not catch Numba errors here, we want to raise and not fall back.
- if is_numba_util_related_error(str(err)):
- raise err
# TODO: KeyError is raised in _python_agg_general,
# see see test_groupby.test_basic
result = self._aggregate_named(func, *args, **kwargs)
diff --git a/pandas/core/util/numba_.py b/pandas/core/util/numba_.py
index 215248f5a43c2..c2e4b38ad5b4d 100644
--- a/pandas/core/util/numba_.py
+++ b/pandas/core/util/numba_.py
@@ -8,29 +8,11 @@
from pandas._typing import FrameOrSeries
from pandas.compat._optional import import_optional_dependency
+from pandas.errors import NumbaUtilError
NUMBA_FUNC_CACHE: Dict[Tuple[Callable, str], Callable] = dict()
-def is_numba_util_related_error(err_message: str) -> bool:
- """
- Check if an error was raised from one of the numba utility functions
-
- For cases where a try/except block has mistakenly caught the error
- and we want to re-raise
-
- Parameters
- ----------
- err_message : str,
- exception error message
-
- Returns
- -------
- bool
- """
- return "The first" in err_message or "numba does not" in err_message
-
-
def check_kwargs_and_nopython(
kwargs: Optional[Dict] = None, nopython: Optional[bool] = None
) -> None:
@@ -51,10 +33,10 @@ def check_kwargs_and_nopython(
Raises
------
- ValueError
+ NumbaUtilError
"""
if kwargs and nopython:
- raise ValueError(
+ raise NumbaUtilError(
"numba does not support kwargs with nopython=True: "
"https://github.com/numba/numba/issues/2916"
)
@@ -169,6 +151,10 @@ def f(values, index, ...):
Returns
-------
None
+
+ Raises
+ ------
+ NumbaUtilError
"""
udf_signature = list(inspect.signature(func).parameters.keys())
expected_args = ["values", "index"]
@@ -177,7 +163,7 @@ def f(values, index, ...):
len(udf_signature) < min_number_args
or udf_signature[:min_number_args] != expected_args
):
- raise ValueError(
+ raise NumbaUtilError(
f"The first {min_number_args} arguments to {func.__name__} must be "
f"{expected_args}"
)
diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py
index 29e69cc5fe509..ef841d2dd4918 100644
--- a/pandas/errors/__init__.py
+++ b/pandas/errors/__init__.py
@@ -184,3 +184,9 @@ def __str__(self) -> str:
else:
name = type(self.class_instance).__name__
return f"This {self.methodtype} must be defined in the concrete class {name}"
+
+
+class NumbaUtilError(Exception):
+ """
+ Error raised for unsupported Numba engine routines.
+ """
diff --git a/pandas/tests/groupby/aggregate/test_numba.py b/pandas/tests/groupby/aggregate/test_numba.py
index 70b0a027f1bd1..f23d7765eb508 100644
--- a/pandas/tests/groupby/aggregate/test_numba.py
+++ b/pandas/tests/groupby/aggregate/test_numba.py
@@ -1,6 +1,7 @@
import numpy as np
import pytest
+from pandas.errors import NumbaUtilError
import pandas.util._test_decorators as td
from pandas import DataFrame
@@ -17,10 +18,10 @@ def incorrect_function(x):
{"key": ["a", "a", "b", "b", "a"], "data": [1.0, 2.0, 3.0, 4.0, 5.0]},
columns=["key", "data"],
)
- with pytest.raises(ValueError, match=f"The first 2"):
+ with pytest.raises(NumbaUtilError, match=f"The first 2"):
data.groupby("key").agg(incorrect_function, engine="numba")
- with pytest.raises(ValueError, match=f"The first 2"):
+ with pytest.raises(NumbaUtilError, match=f"The first 2"):
data.groupby("key")["data"].agg(incorrect_function, engine="numba")
@@ -33,10 +34,10 @@ def incorrect_function(x, **kwargs):
{"key": ["a", "a", "b", "b", "a"], "data": [1.0, 2.0, 3.0, 4.0, 5.0]},
columns=["key", "data"],
)
- with pytest.raises(ValueError, match="numba does not support"):
+ with pytest.raises(NumbaUtilError, match="numba does not support"):
data.groupby("key").agg(incorrect_function, engine="numba", a=1)
- with pytest.raises(ValueError, match="numba does not support"):
+ with pytest.raises(NumbaUtilError, match="numba does not support"):
data.groupby("key")["data"].agg(incorrect_function, engine="numba", a=1)
diff --git a/pandas/tests/groupby/transform/test_numba.py b/pandas/tests/groupby/transform/test_numba.py
index 28904b669ae56..e2b957f1a7ae7 100644
--- a/pandas/tests/groupby/transform/test_numba.py
+++ b/pandas/tests/groupby/transform/test_numba.py
@@ -1,5 +1,6 @@
import pytest
+from pandas.errors import NumbaUtilError
import pandas.util._test_decorators as td
from pandas import DataFrame
@@ -16,10 +17,10 @@ def incorrect_function(x):
{"key": ["a", "a", "b", "b", "a"], "data": [1.0, 2.0, 3.0, 4.0, 5.0]},
columns=["key", "data"],
)
- with pytest.raises(ValueError, match=f"The first 2"):
+ with pytest.raises(NumbaUtilError, match=f"The first 2"):
data.groupby("key").transform(incorrect_function, engine="numba")
- with pytest.raises(ValueError, match=f"The first 2"):
+ with pytest.raises(NumbaUtilError, match=f"The first 2"):
data.groupby("key")["data"].transform(incorrect_function, engine="numba")
@@ -32,10 +33,10 @@ def incorrect_function(x, **kwargs):
{"key": ["a", "a", "b", "b", "a"], "data": [1.0, 2.0, 3.0, 4.0, 5.0]},
columns=["key", "data"],
)
- with pytest.raises(ValueError, match="numba does not support"):
+ with pytest.raises(NumbaUtilError, match="numba does not support"):
data.groupby("key").transform(incorrect_function, engine="numba", a=1)
- with pytest.raises(ValueError, match="numba does not support"):
+ with pytest.raises(NumbaUtilError, match="numba does not support"):
data.groupby("key")["data"].transform(incorrect_function, engine="numba", a=1)
diff --git a/pandas/tests/test_errors.py b/pandas/tests/test_errors.py
index 515d798fe4322..6a1a74c73288f 100644
--- a/pandas/tests/test_errors.py
+++ b/pandas/tests/test_errors.py
@@ -18,6 +18,7 @@
"ParserWarning",
"MergeError",
"OptionError",
+ "NumbaUtilError",
],
)
def test_exception_importable(exc):
diff --git a/pandas/tests/window/test_apply.py b/pandas/tests/window/test_apply.py
index 7132e64c1191c..34cf0a3054889 100644
--- a/pandas/tests/window/test_apply.py
+++ b/pandas/tests/window/test_apply.py
@@ -1,6 +1,7 @@
import numpy as np
import pytest
+from pandas.errors import NumbaUtilError
import pandas.util._test_decorators as td
from pandas import DataFrame, Series, Timestamp, date_range
@@ -134,7 +135,7 @@ def test_invalid_raw_numba():
@td.skip_if_no("numba")
def test_invalid_kwargs_nopython():
- with pytest.raises(ValueError, match="numba does not support kwargs with"):
+ with pytest.raises(NumbaUtilError, match="numba does not support kwargs with"):
Series(range(1)).rolling(1).apply(
lambda x: x, kwargs={"a": 1}, engine="numba", raw=True
)
| - xref https://github.com/pandas-dev/pandas/pull/33388#discussion_r415172278
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` | https://api.github.com/repos/pandas-dev/pandas/pulls/33816 | 2020-04-27T05:18:54Z | 2020-04-27T20:17:45Z | 2020-04-27T20:17:44Z | 2020-04-27T20:46:12Z |
TST: check freq on series.index in assert_series_equal | diff --git a/pandas/_testing.py b/pandas/_testing.py
index 18b5677e7864d..eb4eb86c78b2d 100644
--- a/pandas/_testing.py
+++ b/pandas/_testing.py
@@ -1171,6 +1171,10 @@ def assert_series_equal(
check_categorical=check_categorical,
obj=f"{obj}.index",
)
+ if isinstance(left.index, (pd.DatetimeIndex, pd.TimedeltaIndex)):
+ lidx = left.index
+ ridx = right.index
+ assert lidx.freq == ridx.freq, (lidx.freq, ridx.freq)
if check_dtype:
# We want to skip exact dtype checking when `check_categorical`
diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py
index 0675ba874846b..b085ee968dadb 100644
--- a/pandas/tests/arithmetic/test_numeric.py
+++ b/pandas/tests/arithmetic/test_numeric.py
@@ -919,6 +919,8 @@ def _check_op(series, other, op, pos_only=False):
cython_or_numpy = op(left, right)
python = left.combine(right, op)
+ if isinstance(other, Series) and not other.index.equals(series.index):
+ python.index = python.index._with_freq(None)
tm.assert_series_equal(cython_or_numpy, python)
def check(series, other):
diff --git a/pandas/tests/frame/methods/test_at_time.py b/pandas/tests/frame/methods/test_at_time.py
index 108bbbfa183c4..71368f270147f 100644
--- a/pandas/tests/frame/methods/test_at_time.py
+++ b/pandas/tests/frame/methods/test_at_time.py
@@ -83,4 +83,8 @@ def test_at_time_axis(self, axis):
expected = ts.loc[:, indices]
result = ts.at_time("9:30", axis=axis)
+
+ # Without clearing freq, result has freq 1440T and expected 5T
+ result.index = result.index._with_freq(None)
+ expected.index = expected.index._with_freq(None)
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/frame/methods/test_shift.py b/pandas/tests/frame/methods/test_shift.py
index f6c89172bbf86..95f9fd9d7caf3 100644
--- a/pandas/tests/frame/methods/test_shift.py
+++ b/pandas/tests/frame/methods/test_shift.py
@@ -177,8 +177,12 @@ def test_tshift(self, datetime_frame):
columns=datetime_frame.columns,
)
shifted = inferred_ts.tshift(1)
+
+ expected = datetime_frame.tshift(1)
+ expected.index = expected.index._with_freq(None)
+ tm.assert_frame_equal(shifted, expected)
+
unshifted = shifted.tshift(-1)
- tm.assert_frame_equal(shifted, datetime_frame.tshift(1))
tm.assert_frame_equal(unshifted, inferred_ts)
no_freq = datetime_frame.iloc[[0, 5, 7], :]
diff --git a/pandas/tests/groupby/test_timegrouper.py b/pandas/tests/groupby/test_timegrouper.py
index 6d29ebd7ba795..06a83f4c000cf 100644
--- a/pandas/tests/groupby/test_timegrouper.py
+++ b/pandas/tests/groupby/test_timegrouper.py
@@ -747,6 +747,7 @@ def test_nunique_with_timegrouper_and_nat(self):
grouper = pd.Grouper(key="time", freq="h")
result = test.groupby(grouper)["data"].nunique()
expected = test[test.time.notnull()].groupby(grouper)["data"].nunique()
+ expected.index = expected.index._with_freq(None)
tm.assert_series_equal(result, expected)
def test_scalar_call_versus_list_call(self):
diff --git a/pandas/tests/indexes/timedeltas/test_ops.py b/pandas/tests/indexes/timedeltas/test_ops.py
index 19cbd74b31172..3e452e7e2841d 100644
--- a/pandas/tests/indexes/timedeltas/test_ops.py
+++ b/pandas/tests/indexes/timedeltas/test_ops.py
@@ -18,10 +18,14 @@ def test_value_counts_unique(self):
idx = TimedeltaIndex(np.repeat(idx.values, range(1, len(idx) + 1)))
exp_idx = timedelta_range("1 days 18:00:00", freq="-1H", periods=10)
+ exp_idx = exp_idx._with_freq(None)
expected = Series(range(10, 0, -1), index=exp_idx, dtype="int64")
- for obj in [idx, Series(idx)]:
- tm.assert_series_equal(obj.value_counts(), expected)
+ obj = idx
+ tm.assert_series_equal(obj.value_counts(), expected)
+
+ obj = Series(idx)
+ tm.assert_series_equal(obj.value_counts(), expected)
expected = timedelta_range("1 days 09:00:00", freq="H", periods=10)
tm.assert_index_equal(idx.unique(), expected)
diff --git a/pandas/tests/indexing/test_datetime.py b/pandas/tests/indexing/test_datetime.py
index 17ca23055f6e0..ad71b6b72df33 100644
--- a/pandas/tests/indexing/test_datetime.py
+++ b/pandas/tests/indexing/test_datetime.py
@@ -146,7 +146,7 @@ def test_indexing_with_datetimeindex_tz(self):
for sel in (index, list(index)):
# getitem
result = ser[sel]
- expected = ser
+ expected = ser.copy()
if sel is not index:
expected.index = expected.index._with_freq(None)
tm.assert_series_equal(result, expected)
@@ -159,7 +159,10 @@ def test_indexing_with_datetimeindex_tz(self):
# .loc getitem
result = ser.loc[sel]
- tm.assert_series_equal(result, ser)
+ expected = ser.copy()
+ if sel is not index:
+ expected.index = expected.index._with_freq(None)
+ tm.assert_series_equal(result, expected)
# .loc setitem
result = ser.copy()
diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py
index f15d39e9e6456..3b4cbbd0086ef 100644
--- a/pandas/tests/resample/test_datetime_index.py
+++ b/pandas/tests/resample/test_datetime_index.py
@@ -6,6 +6,7 @@
import pytest
import pytz
+from pandas._libs import lib
from pandas.errors import UnsupportedFunctionCall
import pandas as pd
@@ -62,6 +63,7 @@ def test_custom_grouper(index):
arr = [1] + [5] * 2592
idx = dti[0:-1:5]
idx = idx.append(dti[-1:])
+ idx = pd.DatetimeIndex(idx, freq="5T")
expect = Series(arr, index=idx)
# GH2763 - return in put dtype if we can
@@ -502,15 +504,18 @@ def test_resample_how_method():
)
expected = Series(
[11, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, 22],
- index=[
- Timestamp("2015-03-31 21:48:50"),
- Timestamp("2015-03-31 21:49:00"),
- Timestamp("2015-03-31 21:49:10"),
- Timestamp("2015-03-31 21:49:20"),
- Timestamp("2015-03-31 21:49:30"),
- Timestamp("2015-03-31 21:49:40"),
- Timestamp("2015-03-31 21:49:50"),
- ],
+ index=pd.DatetimeIndex(
+ [
+ Timestamp("2015-03-31 21:48:50"),
+ Timestamp("2015-03-31 21:49:00"),
+ Timestamp("2015-03-31 21:49:10"),
+ Timestamp("2015-03-31 21:49:20"),
+ Timestamp("2015-03-31 21:49:30"),
+ Timestamp("2015-03-31 21:49:40"),
+ Timestamp("2015-03-31 21:49:50"),
+ ],
+ freq="10s",
+ ),
)
tm.assert_series_equal(s.resample("10S").mean(), expected)
@@ -778,7 +783,7 @@ def test_resample_single_group():
[30.1, 31.6],
index=[Timestamp("20070915 15:30:00"), Timestamp("20070915 15:40:00")],
)
- expected = Series([0.75], index=[Timestamp("20070915")])
+ expected = Series([0.75], index=pd.DatetimeIndex([Timestamp("20070915")], freq="D"))
result = s.resample("D").apply(lambda x: np.std(x))
tm.assert_series_equal(result, expected)
@@ -801,7 +806,9 @@ def test_resample_float_base():
base = 17 + 43.51 / 60
result = s.resample("3min", base=base).size()
- expected = Series(3, index=pd.DatetimeIndex(["2018-11-26 16:17:43.51"]))
+ expected = Series(
+ 3, index=pd.DatetimeIndex(["2018-11-26 16:17:43.51"], freq="3min")
+ )
tm.assert_series_equal(result, expected)
@@ -938,6 +945,8 @@ def test_resample_anchored_intraday(simple_date_range_series):
result = df.resample("M").mean()
expected = df.resample("M", kind="period").mean().to_timestamp(how="end")
expected.index += Timedelta(1, "ns") - Timedelta(1, "D")
+ expected.index = expected.index._with_freq("infer")
+ assert expected.index.freq == "M"
tm.assert_frame_equal(result, expected)
result = df.resample("M", closed="left").mean()
@@ -945,6 +954,8 @@ def test_resample_anchored_intraday(simple_date_range_series):
exp = exp.to_timestamp(how="end")
exp.index = exp.index + Timedelta(1, "ns") - Timedelta(1, "D")
+ exp.index = exp.index._with_freq("infer")
+ assert exp.index.freq == "M"
tm.assert_frame_equal(result, exp)
rng = date_range("1/1/2012", "4/1/2012", freq="100min")
@@ -953,12 +964,16 @@ def test_resample_anchored_intraday(simple_date_range_series):
result = df.resample("Q").mean()
expected = df.resample("Q", kind="period").mean().to_timestamp(how="end")
expected.index += Timedelta(1, "ns") - Timedelta(1, "D")
+ expected.index._data.freq = "Q"
+ expected.index._freq = lib.no_default
tm.assert_frame_equal(result, expected)
result = df.resample("Q", closed="left").mean()
expected = df.tshift(1, freq="D").resample("Q", kind="period", closed="left").mean()
expected = expected.to_timestamp(how="end")
expected.index += Timedelta(1, "ns") - Timedelta(1, "D")
+ expected.index._data.freq = "Q"
+ expected.index._freq = lib.no_default
tm.assert_frame_equal(result, expected)
ts = simple_date_range_series("2012-04-29 23:00", "2012-04-30 5:00", freq="h")
@@ -1151,6 +1166,8 @@ def test_resample_timegrouper():
name="A",
)
expected = DataFrame({"B": [1, 0, 2, 2, 1]}, index=exp_idx)
+ if df["A"].isna().any():
+ expected.index = expected.index._with_freq(None)
tm.assert_frame_equal(result, expected)
result = df.groupby(pd.Grouper(freq="M", key="A")).count()
@@ -1163,6 +1180,8 @@ def test_resample_timegrouper():
index=exp_idx,
columns=["B", "C"],
)
+ if df["A"].isna().any():
+ expected.index = expected.index._with_freq(None)
tm.assert_frame_equal(result, expected)
result = df.groupby(pd.Grouper(freq="M", key="A")).count()
@@ -1291,7 +1310,8 @@ def test_resample_across_dst():
dti2 = DatetimeIndex(
pd.to_datetime(df2.ts, unit="s")
.dt.tz_localize("UTC")
- .dt.tz_convert("Europe/Madrid")
+ .dt.tz_convert("Europe/Madrid"),
+ freq="H",
)
df = DataFrame([5, 5], index=dti1)
@@ -1322,13 +1342,17 @@ def test_resample_dst_anchor():
# 5172
dti = DatetimeIndex([datetime(2012, 11, 4, 23)], tz="US/Eastern")
df = DataFrame([5], index=dti)
- tm.assert_frame_equal(
- df.resample(rule="D").sum(), DataFrame([5], index=df.index.normalize())
- )
+
+ dti = DatetimeIndex(df.index.normalize(), freq="D")
+ expected = DataFrame([5], index=dti)
+ tm.assert_frame_equal(df.resample(rule="D").sum(), expected)
df.resample(rule="MS").sum()
tm.assert_frame_equal(
df.resample(rule="MS").sum(),
- DataFrame([5], index=DatetimeIndex([datetime(2012, 11, 1)], tz="US/Eastern")),
+ DataFrame(
+ [5],
+ index=DatetimeIndex([datetime(2012, 11, 1)], tz="US/Eastern", freq="MS"),
+ ),
)
dti = date_range("2013-09-30", "2013-11-02", freq="30Min", tz="Europe/Paris")
@@ -1424,7 +1448,9 @@ def test_downsample_across_dst_weekly():
result = df.resample("1W").sum()
expected = DataFrame(
[23, 42],
- index=pd.DatetimeIndex(["2017-03-26", "2017-04-02"], tz="Europe/Amsterdam"),
+ index=pd.DatetimeIndex(
+ ["2017-03-26", "2017-04-02"], tz="Europe/Amsterdam", freq="W"
+ ),
)
tm.assert_frame_equal(result, expected)
@@ -1447,12 +1473,12 @@ def test_downsample_dst_at_midnight():
data = list(range(len(index)))
dataframe = pd.DataFrame(data, index=index)
result = dataframe.groupby(pd.Grouper(freq="1D")).mean()
- expected = DataFrame(
- [7.5, 28.0, 44.5],
- index=date_range("2018-11-03", periods=3).tz_localize(
- "America/Havana", ambiguous=True
- ),
+
+ dti = date_range("2018-11-03", periods=3).tz_localize(
+ "America/Havana", ambiguous=True
)
+ dti = pd.DatetimeIndex(dti, freq="D")
+ expected = DataFrame([7.5, 28.0, 44.5], index=dti,)
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py
index 70b65209db955..ebc75018bb52d 100644
--- a/pandas/tests/resample/test_period_index.py
+++ b/pandas/tests/resample/test_period_index.py
@@ -270,7 +270,10 @@ def test_resample_with_pytz(self):
)
result = s.resample("D").mean()
expected = Series(
- 2, index=pd.DatetimeIndex(["2017-01-01", "2017-01-02"], tz="US/Eastern")
+ 2,
+ index=pd.DatetimeIndex(
+ ["2017-01-01", "2017-01-02"], tz="US/Eastern", freq="D"
+ ),
)
tm.assert_series_equal(result, expected)
# Especially assert that the timezone is LMT for pytz
@@ -308,6 +311,7 @@ def test_resample_nonexistent_time_bin_edge(self):
index = date_range("2017-03-12", "2017-03-12 1:45:00", freq="15T")
s = Series(np.zeros(len(index)), index=index)
expected = s.tz_localize("US/Pacific")
+ expected.index = pd.DatetimeIndex(expected.index, freq="900S")
result = expected.resample("900S").mean()
tm.assert_series_equal(result, expected)
@@ -471,6 +475,7 @@ def test_resample_tz_localized(self):
]
exp = ts_local_naive.resample("W").mean().tz_localize("America/Los_Angeles")
+ exp.index = pd.DatetimeIndex(exp.index, freq="W")
tm.assert_series_equal(result, exp)
@@ -582,6 +587,7 @@ def test_resample_with_dst_time_change(self):
index = pd.to_datetime(expected_index_values, utc=True).tz_convert(
"America/Chicago"
)
+ index = pd.DatetimeIndex(index, freq="12h")
expected = pd.DataFrame(
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0],
index=index,
@@ -650,7 +656,9 @@ def test_evenly_divisible_with_no_extra_bins(self):
df = DataFrame(np.random.randn(9, 3), index=date_range("2000-1-1", periods=9))
result = df.resample("5D").mean()
expected = pd.concat([df.iloc[0:5].mean(), df.iloc[5:].mean()], axis=1).T
- expected.index = [Timestamp("2000-1-1"), Timestamp("2000-1-6")]
+ expected.index = pd.DatetimeIndex(
+ [Timestamp("2000-1-1"), Timestamp("2000-1-6")], freq="5D"
+ )
tm.assert_frame_equal(result, expected)
index = date_range(start="2001-5-4", periods=28)
@@ -836,6 +844,9 @@ def test_resample_with_non_zero_base(self, start, end, start_freq, end_freq, bas
# to_timestamp casts 24H -> D
result = result.asfreq(end_freq) if end_freq == "24H" else result
expected = s.to_timestamp().resample(end_freq, base=base).mean()
+ if end_freq == "M":
+ # TODO: is non-tick the relevant characteristic?
+ expected.index = expected.index._with_freq(None)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize(
diff --git a/pandas/tests/resample/test_time_grouper.py b/pandas/tests/resample/test_time_grouper.py
index bf998a6e83909..49ac5f81f9c02 100644
--- a/pandas/tests/resample/test_time_grouper.py
+++ b/pandas/tests/resample/test_time_grouper.py
@@ -170,7 +170,7 @@ def test_resample_entirly_nat_window(method, method_args, unit):
s = pd.Series([0] * 2 + [np.nan] * 2, index=pd.date_range("2017", periods=4))
result = methodcaller(method, **method_args)(s.resample("2d"))
expected = pd.Series(
- [0.0, unit], index=pd.to_datetime(["2017-01-01", "2017-01-03"])
+ [0.0, unit], index=pd.DatetimeIndex(["2017-01-01", "2017-01-03"], freq="2D")
)
tm.assert_series_equal(result, expected)
@@ -207,7 +207,8 @@ def test_aggregate_with_nat(func, fill_value):
pad = DataFrame([[fill_value] * 4], index=[3], columns=["A", "B", "C", "D"])
expected = normal_result.append(pad)
expected = expected.sort_index()
- expected.index = date_range(start="2013-01-01", freq="D", periods=5, name="key")
+ dti = date_range(start="2013-01-01", freq="D", periods=5, name="key")
+ expected.index = dti._with_freq(None) # TODO: is this desired?
tm.assert_frame_equal(expected, dt_result)
assert dt_result.index.name == "key"
@@ -237,7 +238,9 @@ def test_aggregate_with_nat_size():
pad = Series([0], index=[3])
expected = normal_result.append(pad)
expected = expected.sort_index()
- expected.index = date_range(start="2013-01-01", freq="D", periods=5, name="key")
+ expected.index = date_range(
+ start="2013-01-01", freq="D", periods=5, name="key"
+ )._with_freq(None)
tm.assert_series_equal(expected, dt_result)
assert dt_result.index.name == "key"
@@ -269,8 +272,9 @@ def test_repr():
def test_upsample_sum(method, method_args, expected_values):
s = pd.Series(1, index=pd.date_range("2017", periods=2, freq="H"))
resampled = s.resample("30T")
- index = pd.to_datetime(
- ["2017-01-01T00:00:00", "2017-01-01T00:30:00", "2017-01-01T01:00:00"]
+ index = pd.DatetimeIndex(
+ ["2017-01-01T00:00:00", "2017-01-01T00:30:00", "2017-01-01T01:00:00"],
+ freq="30T",
)
result = methodcaller(method, **method_args)(resampled)
expected = pd.Series(expected_values, index=index)
diff --git a/pandas/tests/resample/test_timedelta.py b/pandas/tests/resample/test_timedelta.py
index a4d14f127b80e..9fc355a45b656 100644
--- a/pandas/tests/resample/test_timedelta.py
+++ b/pandas/tests/resample/test_timedelta.py
@@ -102,7 +102,7 @@ def test_resample_categorical_data_with_timedeltaindex():
result = df.resample("10s").agg(lambda x: (x.value_counts().index[0]))
expected = DataFrame(
{"Group_obj": ["A", "A"], "Group": ["A", "A"]},
- index=pd.to_timedelta([0, 10], unit="s"),
+ index=pd.TimedeltaIndex([0, 10], unit="s", freq="10s"),
)
expected = expected.reindex(["Group_obj", "Group"], axis=1)
expected["Group"] = expected["Group_obj"]
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
index e49b80e476003..c07a5673fe503 100644
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -423,7 +423,7 @@ def test_pivot_no_values(self):
index=pd.Grouper(freq="A"), columns=pd.Grouper(key="dt", freq="M")
)
exp = pd.DataFrame(
- [3], index=pd.DatetimeIndex(["2011-12-31"]), columns=exp_columns
+ [3], index=pd.DatetimeIndex(["2011-12-31"], freq="A"), columns=exp_columns
)
tm.assert_frame_equal(res, exp)
@@ -1224,7 +1224,7 @@ def test_pivot_timegrouper(self):
expected = DataFrame(
np.array([10, 18, 3], dtype="int64").reshape(1, 3),
- index=[datetime(2013, 12, 31)],
+ index=pd.DatetimeIndex([datetime(2013, 12, 31)], freq="A"),
columns="Carl Joe Mark".split(),
)
expected.index.name = "Date"
@@ -1250,7 +1250,9 @@ def test_pivot_timegrouper(self):
expected = DataFrame(
np.array([1, np.nan, 3, 9, 18, np.nan]).reshape(2, 3),
- index=[datetime(2013, 1, 1), datetime(2013, 7, 1)],
+ index=pd.DatetimeIndex(
+ [datetime(2013, 1, 1), datetime(2013, 7, 1)], freq="6MS"
+ ),
columns="Carl Joe Mark".split(),
)
expected.index.name = "Date"
@@ -1407,18 +1409,24 @@ def test_pivot_timegrouper(self):
np.nan,
]
).reshape(4, 4),
- index=[
- datetime(2013, 9, 30),
- datetime(2013, 10, 31),
- datetime(2013, 11, 30),
- datetime(2013, 12, 31),
- ],
- columns=[
- datetime(2013, 9, 30),
- datetime(2013, 10, 31),
- datetime(2013, 11, 30),
- datetime(2013, 12, 31),
- ],
+ index=pd.DatetimeIndex(
+ [
+ datetime(2013, 9, 30),
+ datetime(2013, 10, 31),
+ datetime(2013, 11, 30),
+ datetime(2013, 12, 31),
+ ],
+ freq="M",
+ ),
+ columns=pd.DatetimeIndex(
+ [
+ datetime(2013, 9, 30),
+ datetime(2013, 10, 31),
+ datetime(2013, 11, 30),
+ datetime(2013, 12, 31),
+ ],
+ freq="M",
+ ),
)
expected.index.name = "Date"
expected.columns.name = "PayDay"
diff --git a/pandas/tests/series/indexing/test_datetime.py b/pandas/tests/series/indexing/test_datetime.py
index e369631a5565d..22ef966299d5b 100644
--- a/pandas/tests/series/indexing/test_datetime.py
+++ b/pandas/tests/series/indexing/test_datetime.py
@@ -51,7 +51,7 @@ def test_fancy_setitem():
def test_dti_reset_index_round_trip():
- dti = date_range(start="1/1/2001", end="6/1/2001", freq="D")
+ dti = date_range(start="1/1/2001", end="6/1/2001", freq="D")._with_freq(None)
d1 = DataFrame({"v": np.random.rand(len(dti))}, index=dti)
d2 = d1.reset_index()
assert d2.dtypes[0] == np.dtype("M8[ns]")
@@ -568,6 +568,7 @@ def compare(slobj):
result = ts2[slobj].copy()
result = result.sort_index()
expected = ts[slobj]
+ expected.index = expected.index._with_freq(None)
tm.assert_series_equal(result, expected)
compare(slice("2011-01-01", "2011-01-15"))
@@ -582,6 +583,7 @@ def compare(slobj):
# single values
result = ts2["2011"].sort_index()
expected = ts["2011"]
+ expected.index = expected.index._with_freq(None)
tm.assert_series_equal(result, expected)
# diff freq
diff --git a/pandas/tests/series/methods/test_at_time.py b/pandas/tests/series/methods/test_at_time.py
index d9985cf33776a..810e4c1446708 100644
--- a/pandas/tests/series/methods/test_at_time.py
+++ b/pandas/tests/series/methods/test_at_time.py
@@ -43,12 +43,17 @@ def test_at_time(self):
expected = ts[(rng.hour == 9) & (rng.minute == 30)]
exp_df = df[(rng.hour == 9) & (rng.minute == 30)]
+ result.index = result.index._with_freq(None)
tm.assert_series_equal(result, expected)
tm.assert_frame_equal(result_df, exp_df)
chunk = df.loc["1/4/2000":]
result = chunk.loc[time(9, 30)]
expected = result_df[-1:]
+
+ # Without resetting the freqs, these are 5 min and 1440 min, respectively
+ result.index = result.index._with_freq(None)
+ expected.index = expected.index._with_freq(None)
tm.assert_frame_equal(result, expected)
# midnight, everything
diff --git a/pandas/tests/series/methods/test_shift.py b/pandas/tests/series/methods/test_shift.py
index e8d7f5958d0a1..686e66162fe0b 100644
--- a/pandas/tests/series/methods/test_shift.py
+++ b/pandas/tests/series/methods/test_shift.py
@@ -212,8 +212,11 @@ def test_tshift(self, datetime_series):
datetime_series.values, Index(np.asarray(datetime_series.index)), name="ts"
)
shifted = inferred_ts.tshift(1)
+ expected = datetime_series.tshift(1)
+ expected.index = expected.index._with_freq(None)
+ tm.assert_series_equal(shifted, expected)
+
unshifted = shifted.tshift(-1)
- tm.assert_series_equal(shifted, datetime_series.tshift(1))
tm.assert_series_equal(unshifted, inferred_ts)
no_freq = datetime_series[[0, 5, 7]]
diff --git a/pandas/tests/series/test_cumulative.py b/pandas/tests/series/test_cumulative.py
index 0cb1c038478f5..259c5d53c5492 100644
--- a/pandas/tests/series/test_cumulative.py
+++ b/pandas/tests/series/test_cumulative.py
@@ -53,6 +53,7 @@ def test_cummin(self, datetime_series):
result = ts.cummin()[1::2]
expected = np.minimum.accumulate(ts.dropna())
+ result.index = result.index._with_freq(None)
tm.assert_series_equal(result, expected)
@pytest.mark.xfail(
@@ -70,6 +71,7 @@ def test_cummax(self, datetime_series):
result = ts.cummax()[1::2]
expected = np.maximum.accumulate(ts.dropna())
+ result.index = result.index._with_freq(None)
tm.assert_series_equal(result, expected)
@pytest.mark.parametrize("tz", [None, "US/Pacific"])
diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py
index 9e9b93a499487..a64a6bc584cf6 100644
--- a/pandas/tests/series/test_missing.py
+++ b/pandas/tests/series/test_missing.py
@@ -744,6 +744,7 @@ def test_dropna_intervals(self):
def test_valid(self, datetime_series):
ts = datetime_series.copy()
+ ts.index = ts.index._with_freq(None)
ts[::2] = np.NaN
result = ts.dropna()
diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py
index 3c3108835416a..15b6481c08a61 100644
--- a/pandas/tests/series/test_timeseries.py
+++ b/pandas/tests/series/test_timeseries.py
@@ -39,6 +39,7 @@ def test_promote_datetime_date(self):
result = ts + ts2
result2 = ts2 + ts
expected = ts + ts[5:]
+ expected.index = expected.index._with_freq(None)
tm.assert_series_equal(result, expected)
tm.assert_series_equal(result2, expected)
diff --git a/pandas/tests/window/common.py b/pandas/tests/window/common.py
index 6aeada3152dbb..a2450f4ac5203 100644
--- a/pandas/tests/window/common.py
+++ b/pandas/tests/window/common.py
@@ -352,6 +352,7 @@ def get_result(obj, obj2=None):
result = result.loc[(slice(None), 1), 5]
result.index = result.index.droplevel(1)
expected = get_result(self.frame[1], self.frame[5])
+ expected.index = expected.index._with_freq(None)
tm.assert_series_equal(result, expected, check_names=False)
diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py
index ab2c7fcb7a0dc..866b7da59382d 100644
--- a/pandas/tests/window/test_rolling.py
+++ b/pandas/tests/window/test_rolling.py
@@ -7,7 +7,7 @@
import pandas.util._test_decorators as td
import pandas as pd
-from pandas import DataFrame, Index, Series
+from pandas import DataFrame, Series
import pandas._testing as tm
from pandas.core.window import Rolling
from pandas.tests.window.common import Base
@@ -436,7 +436,9 @@ def test_rolling_window_as_string():
+ [95.0] * 20
)
- expected = Series(expData, index=Index(days, name="DateCol"), name="metric")
+ expected = Series(
+ expData, index=days.rename("DateCol")._with_freq(None), name="metric"
+ )
tm.assert_series_equal(result, expected)
| Before long we'll roll that check into assert_index_equal | https://api.github.com/repos/pandas-dev/pandas/pulls/33815 | 2020-04-27T02:14:35Z | 2020-04-27T13:00:18Z | 2020-04-27T13:00:18Z | 2020-05-06T20:08:13Z |
TST: Clean moments consistency | diff --git a/pandas/tests/window/common.py b/pandas/tests/window/common.py
index 6aeada3152dbb..d1d0fb519aa31 100644
--- a/pandas/tests/window/common.py
+++ b/pandas/tests/window/common.py
@@ -252,43 +252,15 @@ def _test_moments_consistency_var_debiasing_factors(
var_debiasing_factors_x = var_debiasing_factors(x)
tm.assert_equal(var_unbiased_x, var_biased_x * var_debiasing_factors_x)
- def _test_moments_consistency(
- self,
- min_periods,
- count,
- mean,
- corr,
- var_unbiased=None,
- std_unbiased=None,
- cov_unbiased=None,
- var_biased=None,
- std_biased=None,
- cov_biased=None,
+ def _test_moments_consistency_var_data(
+ self, min_periods, count, mean, var_unbiased, var_biased
):
-
for (x, is_constant, no_nans) in self.data:
count_x = count(x)
mean_x = mean(x)
-
- for (std, var, cov) in [
- (std_biased, var_biased, cov_biased),
- (std_unbiased, var_unbiased, cov_unbiased),
- ]:
-
- # check that var(x), std(x), and cov(x) are all >= 0
+ for var in [var_biased, var_unbiased]:
var_x = var(x)
- std_x = std(x)
assert not (var_x < 0).any().any()
- assert not (std_x < 0).any().any()
- if cov:
- cov_x_x = cov(x, x)
- assert not (cov_x_x < 0).any().any()
-
- # check that var(x) == cov(x, x)
- tm.assert_equal(var_x, cov_x_x)
-
- # check that var(x) == std(x)^2
- tm.assert_equal(var_x, std_x * std_x)
if var is var_biased:
# check that biased var(x) == mean(x^2) - mean(x)^2
@@ -304,45 +276,88 @@ def _test_moments_consistency(
expected[count_x < 2] = np.nan
tm.assert_equal(var_x, expected)
- if isinstance(x, Series):
- for (y, is_constant, no_nans) in self.data:
- if not x.isna().equals(y.isna()):
- # can only easily test two Series with similar
- # structure
- continue
-
- # check that cor(x, y) is symmetric
- corr_x_y = corr(x, y)
- corr_y_x = corr(y, x)
- tm.assert_equal(corr_x_y, corr_y_x)
-
- if cov:
- # check that cov(x, y) is symmetric
- cov_x_y = cov(x, y)
- cov_y_x = cov(y, x)
- tm.assert_equal(cov_x_y, cov_y_x)
-
- # check that cov(x, y) == (var(x+y) - var(x) -
- # var(y)) / 2
- var_x_plus_y = var(x + y)
- var_y = var(y)
- tm.assert_equal(
- cov_x_y, 0.5 * (var_x_plus_y - var_x - var_y)
- )
-
- # check that corr(x, y) == cov(x, y) / (std(x) *
- # std(y))
- std_y = std(y)
- tm.assert_equal(corr_x_y, cov_x_y / (std_x * std_y))
-
- if cov is cov_biased:
- # check that biased cov(x, y) == mean(x*y) -
- # mean(x)*mean(y)
- mean_y = mean(y)
- mean_x_times_y = mean(x * y)
- tm.assert_equal(
- cov_x_y, mean_x_times_y - (mean_x * mean_y)
- )
+ def _test_moments_consistency_std_data(
+ self, std_unbiased, var_unbiased, std_biased, var_biased
+ ):
+ for (x, is_constant, no_nans) in self.data:
+ for (std, var) in [(std_biased, var_biased), (std_unbiased, var_unbiased)]:
+ var_x = var(x)
+ std_x = std(x)
+ assert not (var_x < 0).any().any()
+ assert not (std_x < 0).any().any()
+
+ # check that var(x) == std(x)^2
+ tm.assert_equal(var_x, std_x * std_x)
+
+ def _test_moments_consistency_cov_data(
+ self, cov_unbiased, var_unbiased, cov_biased, var_biased
+ ):
+ for (x, is_constant, no_nans) in self.data:
+ for (cov, var) in [(cov_biased, var_biased), (cov_unbiased, var_unbiased)]:
+ var_x = var(x)
+ assert not (var_x < 0).any().any()
+ if cov:
+ cov_x_x = cov(x, x)
+ assert not (cov_x_x < 0).any().any()
+
+ # check that var(x) == cov(x, x)
+ tm.assert_equal(var_x, cov_x_x)
+
+ def _test_moments_consistency_series_data(
+ self,
+ corr,
+ mean,
+ std_biased,
+ std_unbiased,
+ cov_unbiased,
+ var_unbiased,
+ var_biased,
+ cov_biased,
+ ):
+ for (x, is_constant, no_nans) in self.data:
+ if isinstance(x, Series):
+ y = x
+ mean_x = mean(x)
+ if not x.isna().equals(y.isna()):
+ # can only easily test two Series with similar
+ # structure
+ pass
+
+ # check that cor(x, y) is symmetric
+ corr_x_y = corr(x, y)
+ corr_y_x = corr(y, x)
+ tm.assert_equal(corr_x_y, corr_y_x)
+
+ for (std, var, cov) in [
+ (std_biased, var_biased, cov_biased),
+ (std_unbiased, var_unbiased, cov_unbiased),
+ ]:
+ var_x = var(x)
+ std_x = std(x)
+
+ if cov:
+ # check that cov(x, y) is symmetric
+ cov_x_y = cov(x, y)
+ cov_y_x = cov(y, x)
+ tm.assert_equal(cov_x_y, cov_y_x)
+
+ # check that cov(x, y) == (var(x+y) - var(x) -
+ # var(y)) / 2
+ var_x_plus_y = var(x + y)
+ var_y = var(y)
+ tm.assert_equal(cov_x_y, 0.5 * (var_x_plus_y - var_x - var_y))
+
+ # check that corr(x, y) == cov(x, y) / (std(x) *
+ # std(y))
+ std_y = std(y)
+ tm.assert_equal(corr_x_y, cov_x_y / (std_x * std_y))
+
+ if cov is cov_biased:
+ # check that biased cov(x, y) == mean(x*y) -
+ # mean(x)*mean(y)
+ mean_y = mean(y)
+ mean_x_times_y = mean(x * y)
+ tm.assert_equal(cov_x_y, mean_x_times_y - (mean_x * mean_y))
def _check_pairwise_moment(self, dispatch, name, **kwargs):
def get_result(obj, obj2=None):
diff --git a/pandas/tests/window/moments/test_moments_ewm.py b/pandas/tests/window/moments/test_moments_ewm.py
index 599761259e041..78b086927adfb 100644
--- a/pandas/tests/window/moments/test_moments_ewm.py
+++ b/pandas/tests/window/moments/test_moments_ewm.py
@@ -398,10 +398,90 @@ def _ewma(s, com, min_periods, adjust, ignore_na):
)
),
)
- # test consistency between different ewm* moments
- self._test_moments_consistency(
- min_periods=min_periods,
+
+ @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+ @pytest.mark.parametrize("adjust", [True, False])
+ @pytest.mark.parametrize("ignore_na", [True, False])
+ def test_ewm_consistency_var(self, min_periods, adjust, ignore_na):
+ com = 3.0
+ self._test_moments_consistency_var_data(
+ min_periods,
count=lambda x: x.expanding().count(),
+ mean=lambda x: x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).mean(),
+ var_unbiased=lambda x: (
+ x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).var(bias=False)
+ ),
+ var_biased=lambda x: (
+ x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).var(bias=True)
+ ),
+ )
+
+ @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+ @pytest.mark.parametrize("adjust", [True, False])
+ @pytest.mark.parametrize("ignore_na", [True, False])
+ def test_ewm_consistency_std(self, min_periods, adjust, ignore_na):
+ com = 3.0
+ self._test_moments_consistency_std_data(
+ var_unbiased=lambda x: (
+ x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).var(bias=False)
+ ),
+ std_unbiased=lambda x: (
+ x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).std(bias=False)
+ ),
+ var_biased=lambda x: (
+ x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).var(bias=True)
+ ),
+ std_biased=lambda x: x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).std(bias=True),
+ )
+
+ @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+ @pytest.mark.parametrize("adjust", [True, False])
+ @pytest.mark.parametrize("ignore_na", [True, False])
+ def test_ewm_consistency_cov(self, min_periods, adjust, ignore_na):
+ com = 3.0
+ self._test_moments_consistency_cov_data(
+ var_unbiased=lambda x: (
+ x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).var(bias=False)
+ ),
+ cov_unbiased=lambda x, y: (
+ x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).cov(y, bias=False)
+ ),
+ var_biased=lambda x: (
+ x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).var(bias=True)
+ ),
+ cov_biased=lambda x, y: (
+ x.ewm(
+ com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
+ ).cov(y, bias=True)
+ ),
+ )
+
+ @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+ @pytest.mark.parametrize("adjust", [True, False])
+ @pytest.mark.parametrize("ignore_na", [True, False])
+ def test_ewm_consistency_series_data(self, min_periods, adjust, ignore_na):
+ com = 3.0
+ self._test_moments_consistency_series_data(
mean=lambda x: x.ewm(
com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na
).mean(),
diff --git a/pandas/tests/window/moments/test_moments_expanding.py b/pandas/tests/window/moments/test_moments_expanding.py
index 9dfaecee9caeb..01940d83a4fa9 100644
--- a/pandas/tests/window/moments/test_moments_expanding.py
+++ b/pandas/tests/window/moments/test_moments_expanding.py
@@ -367,20 +367,6 @@ def test_expanding_consistency(self, min_periods):
/ (x.expanding().count() - 1.0).replace(0.0, np.nan)
),
)
- self._test_moments_consistency(
- min_periods=min_periods,
- count=lambda x: x.expanding(min_periods=min_periods).count(),
- mean=lambda x: x.expanding(min_periods=min_periods).mean(),
- corr=lambda x, y: x.expanding(min_periods=min_periods).corr(y),
- var_unbiased=lambda x: x.expanding(min_periods=min_periods).var(),
- std_unbiased=lambda x: x.expanding(min_periods=min_periods).std(),
- cov_unbiased=lambda x, y: x.expanding(min_periods=min_periods).cov(y),
- var_biased=lambda x: x.expanding(min_periods=min_periods).var(ddof=0),
- std_biased=lambda x: x.expanding(min_periods=min_periods).std(ddof=0),
- cov_biased=lambda x, y: x.expanding(min_periods=min_periods).cov(
- y, ddof=0
- ),
- )
# test consistency between expanding_xyz() and either (a)
# expanding_apply of Series.xyz(), or (b) expanding_apply of
@@ -418,3 +404,44 @@ def test_expanding_consistency(self, min_periods):
# GH 9422
if name in ["sum", "prod"]:
tm.assert_equal(expanding_f_result, expanding_apply_f_result)
+
+ @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+ def test_moments_consistency_var(self, min_periods):
+ self._test_moments_consistency_var_data(
+ min_periods=min_periods,
+ count=lambda x: x.expanding(min_periods=min_periods).count(),
+ mean=lambda x: x.expanding(min_periods=min_periods).mean(),
+ var_unbiased=lambda x: x.expanding(min_periods=min_periods).var(),
+ var_biased=lambda x: x.expanding(min_periods=min_periods).var(ddof=0),
+ )
+
+ @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+ def test_expanding_consistency_std(self, min_periods):
+ self._test_moments_consistency_std_data(
+ var_unbiased=lambda x: x.expanding(min_periods=min_periods).var(),
+ std_unbiased=lambda x: x.expanding(min_periods=min_periods).std(),
+ var_biased=lambda x: x.expanding(min_periods=min_periods).var(ddof=0),
+ std_biased=lambda x: x.expanding(min_periods=min_periods).std(ddof=0),
+ )
+
+ @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+ def test_expanding_consistency_cov(self, min_periods):
+ self._test_moments_consistency_cov_data(
+ var_unbiased=lambda x: x.expanding(min_periods=min_periods).var(),
+ cov_unbiased=lambda x, y: x.expanding(min_periods=min_periods).cov(y),
+ var_biased=lambda x: x.expanding(min_periods=min_periods).var(ddof=0),
+ cov_biased=lambda x, y: x.expanding(min_periods=min_periods).cov(y, ddof=0),
+ )
+
+ @pytest.mark.parametrize("min_periods", [0, 1, 2, 3, 4])
+ def test_expanding_consistency_series(self, min_periods):
+ self._test_moments_consistency_series_data(
+ mean=lambda x: x.expanding(min_periods=min_periods).mean(),
+ corr=lambda x, y: x.expanding(min_periods=min_periods).corr(y),
+ var_unbiased=lambda x: x.expanding(min_periods=min_periods).var(),
+ std_unbiased=lambda x: x.expanding(min_periods=min_periods).std(),
+ cov_unbiased=lambda x, y: x.expanding(min_periods=min_periods).cov(y),
+ var_biased=lambda x: x.expanding(min_periods=min_periods).var(ddof=0),
+ std_biased=lambda x: x.expanding(min_periods=min_periods).std(ddof=0),
+ cov_biased=lambda x, y: x.expanding(min_periods=min_periods).cov(y, ddof=0),
+ )
diff --git a/pandas/tests/window/moments/test_moments_rolling.py b/pandas/tests/window/moments/test_moments_rolling.py
index 3c5352fcd997d..33e870df4d8b2 100644
--- a/pandas/tests/window/moments/test_moments_rolling.py
+++ b/pandas/tests/window/moments/test_moments_rolling.py
@@ -1013,55 +1013,6 @@ def test_rolling_consistency(self, window, min_periods, center):
),
)
- self._test_moments_consistency(
- min_periods=min_periods,
- count=lambda x: (
- x.rolling(
- window=window, min_periods=min_periods, center=center
- ).count()
- ),
- mean=lambda x: (
- x.rolling(
- window=window, min_periods=min_periods, center=center
- ).mean()
- ),
- corr=lambda x, y: (
- x.rolling(
- window=window, min_periods=min_periods, center=center
- ).corr(y)
- ),
- var_unbiased=lambda x: (
- x.rolling(
- window=window, min_periods=min_periods, center=center
- ).var()
- ),
- std_unbiased=lambda x: (
- x.rolling(
- window=window, min_periods=min_periods, center=center
- ).std()
- ),
- cov_unbiased=lambda x, y: (
- x.rolling(
- window=window, min_periods=min_periods, center=center
- ).cov(y)
- ),
- var_biased=lambda x: (
- x.rolling(
- window=window, min_periods=min_periods, center=center
- ).var(ddof=0)
- ),
- std_biased=lambda x: (
- x.rolling(
- window=window, min_periods=min_periods, center=center
- ).std(ddof=0)
- ),
- cov_biased=lambda x, y: (
- x.rolling(
- window=window, min_periods=min_periods, center=center
- ).cov(y, ddof=0)
- ),
- )
-
# test consistency between rolling_xyz() and either (a)
# rolling_apply of Series.xyz(), or (b) rolling_apply of
# np.nanxyz()
@@ -1104,6 +1055,111 @@ def test_rolling_consistency(self, window, min_periods, center):
if name in ["sum", "prod"]:
tm.assert_equal(rolling_f_result, rolling_apply_f_result)
+ @pytest.mark.parametrize(
+ "window,min_periods,center", list(_rolling_consistency_cases())
+ )
+ def test_rolling_consistency_var(self, window, min_periods, center):
+ self._test_moments_consistency_var_data(
+ min_periods,
+ count=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).count()
+ ),
+ mean=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).mean()
+ ),
+ var_unbiased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).var()
+ ),
+ var_biased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).var(
+ ddof=0
+ )
+ ),
+ )
+
+ @pytest.mark.parametrize(
+ "window,min_periods,center", list(_rolling_consistency_cases())
+ )
+ def test_rolling_consistency_std(self, window, min_periods, center):
+ self._test_moments_consistency_std_data(
+ var_unbiased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).var()
+ ),
+ std_unbiased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).std()
+ ),
+ var_biased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).var(
+ ddof=0
+ )
+ ),
+ std_biased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).std(
+ ddof=0
+ )
+ ),
+ )
+
+ @pytest.mark.parametrize(
+ "window,min_periods,center", list(_rolling_consistency_cases())
+ )
+ def test_rolling_consistency_cov(self, window, min_periods, center):
+ self._test_moments_consistency_cov_data(
+ var_unbiased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).var()
+ ),
+ cov_unbiased=lambda x, y: (
+ x.rolling(window=window, min_periods=min_periods, center=center).cov(y)
+ ),
+ var_biased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).var(
+ ddof=0
+ )
+ ),
+ cov_biased=lambda x, y: (
+ x.rolling(window=window, min_periods=min_periods, center=center).cov(
+ y, ddof=0
+ )
+ ),
+ )
+
+ @pytest.mark.parametrize(
+ "window,min_periods,center", list(_rolling_consistency_cases())
+ )
+ def test_rolling_consistency_series(self, window, min_periods, center):
+ self._test_moments_consistency_series_data(
+ mean=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).mean()
+ ),
+ corr=lambda x, y: (
+ x.rolling(window=window, min_periods=min_periods, center=center).corr(y)
+ ),
+ var_unbiased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).var()
+ ),
+ std_unbiased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).std()
+ ),
+ cov_unbiased=lambda x, y: (
+ x.rolling(window=window, min_periods=min_periods, center=center).cov(y)
+ ),
+ var_biased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).var(
+ ddof=0
+ )
+ ),
+ std_biased=lambda x: (
+ x.rolling(window=window, min_periods=min_periods, center=center).std(
+ ddof=0
+ )
+ ),
+ cov_biased=lambda x, y: (
+ x.rolling(window=window, min_periods=min_periods, center=center).cov(
+ y, ddof=0
+ )
+ ),
+ )
+
# binary moments
def test_rolling_cov(self):
A = self.series
| As discussed in https://github.com/pandas-dev/pandas/pull/30577#issuecomment-570014613
This PR is the first step to achieve it, it basically does one thing: break up the giant consistency test in `common` into four tests based on test contents: `var`, `std`, `cov`, and `series data`.
cc @jreback | https://api.github.com/repos/pandas-dev/pandas/pulls/33813 | 2020-04-26T20:28:20Z | 2020-04-26T21:23:58Z | 2020-04-26T21:23:58Z | 2020-05-03T00:38:59Z |
TST: check freq in assert_equal | diff --git a/pandas/_testing.py b/pandas/_testing.py
index 21e74dafcc944..7ca14546fd46b 100644
--- a/pandas/_testing.py
+++ b/pandas/_testing.py
@@ -1429,6 +1429,8 @@ def assert_equal(left, right, **kwargs):
if isinstance(left, pd.Index):
assert_index_equal(left, right, **kwargs)
+ if isinstance(left, (pd.DatetimeIndex, pd.TimedeltaIndex)):
+ assert left.freq == right.freq, (left.freq, right.freq)
elif isinstance(left, pd.Series):
assert_series_equal(left, right, **kwargs)
elif isinstance(left, pd.DataFrame):
diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py
index afdfece842ef9..83d81ccf84b45 100644
--- a/pandas/tests/arithmetic/test_datetime64.py
+++ b/pandas/tests/arithmetic/test_datetime64.py
@@ -897,7 +897,7 @@ def test_dt64arr_add_sub_td64ndarray(self, tz_naive_fixture, box_with_array):
)
def test_dt64arr_sub_dtscalar(self, box_with_array, ts):
# GH#8554, GH#22163 DataFrame op should _not_ return dt64 dtype
- idx = pd.date_range("2013-01-01", periods=3)
+ idx = pd.date_range("2013-01-01", periods=3)._with_freq(None)
idx = tm.box_expected(idx, box_with_array)
expected = pd.TimedeltaIndex(["0 Days", "1 Day", "2 Days"])
@@ -912,7 +912,7 @@ def test_dt64arr_sub_datetime64_not_ns(self, box_with_array):
dt64 = np.datetime64("2013-01-01")
assert dt64.dtype == "datetime64[D]"
- dti = pd.date_range("20130101", periods=3)
+ dti = pd.date_range("20130101", periods=3)._with_freq(None)
dtarr = tm.box_expected(dti, box_with_array)
expected = pd.TimedeltaIndex(["0 Days", "1 Day", "2 Days"])
@@ -926,6 +926,7 @@ def test_dt64arr_sub_datetime64_not_ns(self, box_with_array):
def test_dt64arr_sub_timestamp(self, box_with_array):
ser = pd.date_range("2014-03-17", periods=2, freq="D", tz="US/Eastern")
+ ser = ser._with_freq(None)
ts = ser[0]
ser = tm.box_expected(ser, box_with_array)
| Before long we'll move this check into assert_index_equal, for now just want to get validation in place where feasible. | https://api.github.com/repos/pandas-dev/pandas/pulls/33812 | 2020-04-26T20:07:40Z | 2020-04-26T20:53:29Z | 2020-04-26T20:53:29Z | 2020-04-26T20:55:14Z |
BUG: pickle after _with_freq | diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 407daf15d5cce..b13a682ef3985 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -410,7 +410,7 @@ def ceil(self, freq, ambiguous="raise", nonexistent="raise"):
def _with_freq(self, freq):
"""
- Helper to set our freq in-place, returning self to allow method chaining.
+ Helper to get a view on the same data, with a new freq.
Parameters
----------
@@ -418,7 +418,7 @@ def _with_freq(self, freq):
Returns
-------
- self
+ Same type as self
"""
# GH#29843
if freq is None:
@@ -433,8 +433,9 @@ def _with_freq(self, freq):
assert freq == "infer"
freq = frequencies.to_offset(self.inferred_freq)
- self._freq = freq
- return self
+ arr = self.view()
+ arr._freq = freq
+ return arr
class DatetimeLikeArrayMixin(
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index f41044db2b49c..ae119e72e37e1 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -44,7 +44,7 @@
from pandas.core.ops import get_op_result_name
from pandas.core.tools.timedeltas import to_timedelta
-from pandas.tseries.frequencies import DateOffset, to_offset
+from pandas.tseries.frequencies import DateOffset
from pandas.tseries.offsets import Tick
_index_doc_kwargs = dict(ibase._index_doc_kwargs)
@@ -678,20 +678,8 @@ def freqstr(self):
return self.freq.freqstr
def _with_freq(self, freq):
- index = self.copy(deep=False)
- if freq is None:
- # Even if we _can_ have a freq, we might want to set it to None
- index._freq = None
- elif len(self) == 0 and isinstance(freq, DateOffset):
- # Always valid. In the TimedeltaArray case, we assume this
- # is a Tick offset.
- index._freq = freq
- else:
- assert freq == "infer", freq
- freq = to_offset(self.inferred_freq)
- index._freq = freq
-
- return index
+ arr = self._data._with_freq(freq)
+ return type(self)._simple_new(arr, name=self.name)
def _shallow_copy(self, values=None, name: Label = lib.no_default):
name = self.name if name is lib.no_default else name
diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py
index 81fa1a27ac911..e0e5beaf48e20 100644
--- a/pandas/tests/indexes/datetimes/test_datetime.py
+++ b/pandas/tests/indexes/datetimes/test_datetime.py
@@ -38,6 +38,13 @@ def test_pickle(self):
idx_p = tm.round_trip_pickle(idx)
tm.assert_index_equal(idx, idx_p)
+ def test_pickle_after_set_freq(self):
+ dti = date_range("20130101", periods=3, tz="US/Eastern", name="foo")
+ dti = dti._with_freq(None)
+
+ res = tm.round_trip_pickle(dti)
+ tm.assert_index_equal(res, dti)
+
def test_reindex_preserves_tz_if_target_is_empty_list_or_array(self):
# GH7774
index = date_range("20130101", periods=3, tz="US/Eastern")
diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py
index 637a2629dda8a..5efa1a75700e0 100644
--- a/pandas/tests/indexes/timedeltas/test_timedelta.py
+++ b/pandas/tests/indexes/timedeltas/test_timedelta.py
@@ -47,6 +47,13 @@ def test_shift(self):
def test_pickle_compat_construction(self):
pass
+ def test_pickle_after_set_freq(self):
+ tdi = timedelta_range("1 day", periods=4, freq="s")
+ tdi = tdi._with_freq(None)
+
+ res = tm.round_trip_pickle(tdi)
+ tm.assert_index_equal(res, tdi)
+
def test_isin(self):
index = tm.makeTimedeltaIndex(4)
| introduced in #33552 | https://api.github.com/repos/pandas-dev/pandas/pulls/33811 | 2020-04-26T19:51:44Z | 2020-04-26T20:52:37Z | 2020-04-26T20:52:37Z | 2020-04-26T20:55:29Z |
BUG: Don't raise in DataFrame.corr with pd.NA | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 08d20af314110..b2d3c588c3bb8 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -569,7 +569,7 @@ 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 :meth:`DataFrame.corr` and :meth:`DataFrame.cov` raising when handling nullable integer columns with ``pandas.NA`` (:issue:`33803`)
Conversion
^^^^^^^^^^
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 5810e86f2c8b1..4b4801f4e8c58 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -84,7 +84,6 @@
validate_numeric_casting,
)
from pandas.core.dtypes.common import (
- ensure_float64,
ensure_int64,
ensure_platform_int,
infer_dtype_from_object,
@@ -7871,16 +7870,16 @@ def corr(self, method="pearson", min_periods=1) -> "DataFrame":
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
- mat = numeric_df.values
+ mat = numeric_df.astype(float, copy=False).to_numpy()
if method == "pearson":
- correl = libalgos.nancorr(ensure_float64(mat), minp=min_periods)
+ correl = libalgos.nancorr(mat, minp=min_periods)
elif method == "spearman":
- correl = libalgos.nancorr_spearman(ensure_float64(mat), minp=min_periods)
+ correl = libalgos.nancorr_spearman(mat, minp=min_periods)
elif method == "kendall" or callable(method):
if min_periods is None:
min_periods = 1
- mat = ensure_float64(mat).T
+ mat = mat.T
corrf = nanops.get_corr_func(method)
K = len(cols)
correl = np.empty((K, K), dtype=float)
@@ -8006,19 +8005,19 @@ def cov(self, min_periods=None) -> "DataFrame":
numeric_df = self._get_numeric_data()
cols = numeric_df.columns
idx = cols.copy()
- mat = numeric_df.values
+ mat = numeric_df.astype(float, copy=False).to_numpy()
if notna(mat).all():
if min_periods is not None and min_periods > len(mat):
- baseCov = np.empty((mat.shape[1], mat.shape[1]))
- baseCov.fill(np.nan)
+ base_cov = np.empty((mat.shape[1], mat.shape[1]))
+ base_cov.fill(np.nan)
else:
- baseCov = np.cov(mat.T)
- baseCov = baseCov.reshape((len(cols), len(cols)))
+ base_cov = np.cov(mat.T)
+ base_cov = base_cov.reshape((len(cols), len(cols)))
else:
- baseCov = libalgos.nancorr(ensure_float64(mat), cov=True, minp=min_periods)
+ base_cov = libalgos.nancorr(mat, cov=True, minp=min_periods)
- return self._constructor(baseCov, index=idx, columns=cols)
+ return self._constructor(base_cov, index=idx, columns=cols)
def corrwith(self, other, axis=0, drop=False, method="pearson") -> Series:
"""
diff --git a/pandas/tests/frame/methods/test_cov_corr.py b/pandas/tests/frame/methods/test_cov_corr.py
index 5c13b60aae0d0..7d75db55c3073 100644
--- a/pandas/tests/frame/methods/test_cov_corr.py
+++ b/pandas/tests/frame/methods/test_cov_corr.py
@@ -58,6 +58,17 @@ def test_cov(self, float_frame, float_string_frame):
)
tm.assert_frame_equal(result, expected)
+ @pytest.mark.parametrize(
+ "other_column", [pd.array([1, 2, 3]), np.array([1.0, 2.0, 3.0])]
+ )
+ def test_cov_nullable_integer(self, other_column):
+ # https://github.com/pandas-dev/pandas/issues/33803
+ data = pd.DataFrame({"a": pd.array([1, 2, None]), "b": other_column})
+ result = data.cov()
+ arr = np.array([[0.5, 0.5], [0.5, 1.0]])
+ expected = pd.DataFrame(arr, columns=["a", "b"], index=["a", "b"])
+ tm.assert_frame_equal(result, expected)
+
class TestDataFrameCorr:
# DataFrame.corr(), as opposed to DataFrame.corrwith
@@ -153,6 +164,22 @@ def test_corr_int(self):
df3.cov()
df3.corr()
+ @td.skip_if_no_scipy
+ @pytest.mark.parametrize(
+ "nullable_column", [pd.array([1, 2, 3]), pd.array([1, 2, None])]
+ )
+ @pytest.mark.parametrize(
+ "other_column",
+ [pd.array([1, 2, 3]), np.array([1.0, 2.0, 3.0]), np.array([1.0, 2.0, np.nan])],
+ )
+ @pytest.mark.parametrize("method", ["pearson", "spearman", "kendall"])
+ def test_corr_nullable_integer(self, nullable_column, other_column, method):
+ # https://github.com/pandas-dev/pandas/issues/33803
+ data = pd.DataFrame({"a": nullable_column, "b": other_column})
+ result = data.corr(method=method)
+ expected = pd.DataFrame(np.ones((2, 2)), columns=["a", "b"], index=["a", "b"])
+ tm.assert_frame_equal(result, expected)
+
class TestDataFrameCorrWith:
def test_corrwith(self, datetime_frame):
| - [x] closes #33803
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/33809 | 2020-04-26T19:00:04Z | 2020-04-27T23:53:59Z | 2020-04-27T23:53:59Z | 2020-09-27T03:27:52Z |
CLN: use unpack_zerodim_and_defer in timedeltas | diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py
index 7cffe6a5a16a9..a460d07e1f6f2 100644
--- a/pandas/core/arrays/timedeltas.py
+++ b/pandas/core/arrays/timedeltas.py
@@ -27,12 +27,7 @@
pandas_dtype,
)
from pandas.core.dtypes.dtypes import DatetimeTZDtype
-from pandas.core.dtypes.generic import (
- ABCDataFrame,
- ABCIndexClass,
- ABCSeries,
- ABCTimedeltaIndex,
-)
+from pandas.core.dtypes.generic import ABCSeries, ABCTimedeltaIndex
from pandas.core.dtypes.missing import isna
from pandas.core import nanops
@@ -40,6 +35,7 @@
from pandas.core.arrays import datetimelike as dtl
import pandas.core.common as com
from pandas.core.construction import extract_array
+from pandas.core.ops.common import unpack_zerodim_and_defer
from pandas.tseries.frequencies import to_offset
from pandas.tseries.offsets import Tick
@@ -456,12 +452,8 @@ def _addsub_object_array(self, other, op):
f"Cannot add/subtract non-tick DateOffset to {type(self).__name__}"
) from err
+ @unpack_zerodim_and_defer("__mul__")
def __mul__(self, other):
- other = lib.item_from_zerodim(other)
-
- if isinstance(other, (ABCDataFrame, ABCSeries, ABCIndexClass)):
- return NotImplemented
-
if is_scalar(other):
# numpy will accept float and int, raise TypeError for others
result = self._data * other
@@ -492,12 +484,9 @@ def __mul__(self, other):
__rmul__ = __mul__
+ @unpack_zerodim_and_defer("__truediv__")
def __truediv__(self, other):
# timedelta / X is well-defined for timedelta-like or numeric X
- other = lib.item_from_zerodim(other)
-
- if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)):
- return NotImplemented
if isinstance(other, (timedelta, np.timedelta64, Tick)):
other = Timedelta(other)
@@ -553,13 +542,9 @@ def __truediv__(self, other):
result = self._data / other
return type(self)(result)
+ @unpack_zerodim_and_defer("__rtruediv__")
def __rtruediv__(self, other):
# X / timedelta is defined only for timedelta-like X
- other = lib.item_from_zerodim(other)
-
- if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)):
- return NotImplemented
-
if isinstance(other, (timedelta, np.timedelta64, Tick)):
other = Timedelta(other)
if other is NaT:
@@ -599,11 +584,9 @@ def __rtruediv__(self, other):
f"Cannot divide {other.dtype} data by {type(self).__name__}"
)
+ @unpack_zerodim_and_defer("__floordiv__")
def __floordiv__(self, other):
- if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)):
- return NotImplemented
- other = lib.item_from_zerodim(other)
if is_scalar(other):
if isinstance(other, (timedelta, np.timedelta64, Tick)):
other = Timedelta(other)
@@ -665,11 +648,9 @@ def __floordiv__(self, other):
dtype = getattr(other, "dtype", type(other).__name__)
raise TypeError(f"Cannot divide {dtype} by {type(self).__name__}")
+ @unpack_zerodim_and_defer("__rfloordiv__")
def __rfloordiv__(self, other):
- if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)):
- return NotImplemented
- other = lib.item_from_zerodim(other)
if is_scalar(other):
if isinstance(other, (timedelta, np.timedelta64, Tick)):
other = Timedelta(other)
@@ -714,32 +695,23 @@ def __rfloordiv__(self, other):
dtype = getattr(other, "dtype", type(other).__name__)
raise TypeError(f"Cannot divide {dtype} by {type(self).__name__}")
+ @unpack_zerodim_and_defer("__mod__")
def __mod__(self, other):
# Note: This is a naive implementation, can likely be optimized
- if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)):
- return NotImplemented
-
- other = lib.item_from_zerodim(other)
if isinstance(other, (timedelta, np.timedelta64, Tick)):
other = Timedelta(other)
return self - (self // other) * other
+ @unpack_zerodim_and_defer("__rmod__")
def __rmod__(self, other):
# Note: This is a naive implementation, can likely be optimized
- if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)):
- return NotImplemented
-
- other = lib.item_from_zerodim(other)
if isinstance(other, (timedelta, np.timedelta64, Tick)):
other = Timedelta(other)
return other - (other // self) * self
+ @unpack_zerodim_and_defer("__divmod__")
def __divmod__(self, other):
# Note: This is a naive implementation, can likely be optimized
- if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)):
- return NotImplemented
-
- other = lib.item_from_zerodim(other)
if isinstance(other, (timedelta, np.timedelta64, Tick)):
other = Timedelta(other)
@@ -747,12 +719,9 @@ def __divmod__(self, other):
res2 = self - res1 * other
return res1, res2
+ @unpack_zerodim_and_defer("__rdivmod__")
def __rdivmod__(self, other):
# Note: This is a naive implementation, can likely be optimized
- if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)):
- return NotImplemented
-
- other = lib.item_from_zerodim(other)
if isinstance(other, (timedelta, np.timedelta64, Tick)):
other = Timedelta(other)
| https://api.github.com/repos/pandas-dev/pandas/pulls/33808 | 2020-04-26T17:00:34Z | 2020-04-26T19:24:46Z | 2020-04-26T19:24:46Z | 2020-04-26T19:33:14Z | |
TST: Added message to bare pytest.raises in test_join_multi_levels (#… | diff --git a/pandas/tests/reshape/merge/test_multi.py b/pandas/tests/reshape/merge/test_multi.py
index 1f78c1900d237..61fdafa0c6db2 100644
--- a/pandas/tests/reshape/merge/test_multi.py
+++ b/pandas/tests/reshape/merge/test_multi.py
@@ -582,13 +582,15 @@ def test_join_multi_levels(self):
# invalid cases
household.index.name = "foo"
- with pytest.raises(ValueError):
+ with pytest.raises(
+ ValueError, match="cannot join with no overlapping index names"
+ ):
household.join(portfolio, how="inner")
portfolio2 = portfolio.copy()
portfolio2.index.set_names(["household_id", "foo"])
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match="columns overlap but no suffix specified"):
portfolio2.join(portfolio, how="inner")
def test_join_multi_levels2(self):
| …30999)
Updated tests in test_join_multi_levels to include messages for pytest.raises.
- [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/33806 | 2020-04-26T16:01:09Z | 2020-04-26T19:50:19Z | 2020-04-26T19:50:18Z | 2020-04-26T20:31:07Z |
BUG: can't concatenate DataFrame with Series with duplicate keys | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 7ad7e8f5a27b0..23a772ae6c405 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -723,6 +723,7 @@ Reshaping
- Bug in :meth:`concat` where when passing a non-dict mapping as ``objs`` would raise a ``TypeError`` (:issue:`32863`)
- :meth:`DataFrame.agg` now provides more descriptive ``SpecificationError`` message when attempting to aggregating non-existant column (:issue:`32755`)
- Bug in :meth:`DataFrame.unstack` when MultiIndexed columns and MultiIndexed rows were used (:issue:`32624`, :issue:`24729` and :issue:`28306`)
+- 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`)
diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py
index a868e663b06a5..2f66cbf44788d 100644
--- a/pandas/core/reshape/concat.py
+++ b/pandas/core/reshape/concat.py
@@ -619,10 +619,10 @@ def _make_concat_multiindex(indexes, keys, levels=None, names=None) -> MultiInde
for hlevel, level in zip(zipped, levels):
to_concat = []
for key, index in zip(hlevel, indexes):
- try:
- i = level.get_loc(key)
- except KeyError as err:
- raise ValueError(f"Key {key} not in level {level}") from err
+ mask = level == key
+ if not mask.any():
+ raise ValueError(f"Key {key} not in level {level}")
+ i = np.nonzero(level == key)[0][0]
to_concat.append(np.repeat(i, len(index)))
codes_list.append(np.concatenate(to_concat))
diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py
index 7c01664df0607..6625ab86cfed4 100644
--- a/pandas/tests/reshape/test_concat.py
+++ b/pandas/tests/reshape/test_concat.py
@@ -2802,3 +2802,18 @@ def test_concat_multiindex_datetime_object_index():
)
result = concat([s, s2], axis=1)
tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("keys", [["e", "f", "f"], ["f", "e", "f"]])
+def test_duplicate_keys(keys):
+ # GH 33654
+ df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
+ s1 = Series([7, 8, 9], name="c")
+ s2 = Series([10, 11, 12], name="d")
+ result = concat([df, s1, s2], axis=1, keys=keys)
+ expected_values = [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
+ expected_columns = pd.MultiIndex.from_tuples(
+ [(keys[0], "a"), (keys[0], "b"), (keys[1], "c"), (keys[2], "d")]
+ )
+ expected = DataFrame(expected_values, columns=expected_columns)
+ tm.assert_frame_equal(result, expected)
| - [x] closes #33654
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/33805 | 2020-04-26T10:01:32Z | 2020-05-01T16:50:31Z | 2020-05-01T16:50:30Z | 2020-05-01T17:23:29Z |
BUG: support corr and cov functions for custom BaseIndexer rolling windows | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 845f7773c263c..0e87b319add6b 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -175,8 +175,7 @@ Other API changes
- Added :meth:`DataFrame.value_counts` (:issue:`5377`)
- :meth:`Groupby.groups` now returns an abbreviated representation when called on large dataframes (:issue:`1135`)
- ``loc`` lookups with an object-dtype :class:`Index` and an integer key will now raise ``KeyError`` instead of ``TypeError`` when key is missing (:issue:`31905`)
-- Using a :func:`pandas.api.indexers.BaseIndexer` with ``cov``, ``corr`` will now raise a ``NotImplementedError`` (:issue:`32865`)
-- Using a :func:`pandas.api.indexers.BaseIndexer` with ``count``, ``min``, ``max``, ``median``, ``skew`` will now return correct results for any monotonic :func:`pandas.api.indexers.BaseIndexer` descendant (:issue:`32865`)
+- Using a :func:`pandas.api.indexers.BaseIndexer` with ``count``, ``min``, ``max``, ``median``, ``skew``, ``cov``, ``corr`` will now return correct results for any monotonic :func:`pandas.api.indexers.BaseIndexer` descendant (:issue:`32865`)
- Added a :func:`pandas.api.indexers.FixedForwardWindowIndexer` class to support forward-looking windows during ``rolling`` operations.
-
diff --git a/pandas/core/window/common.py b/pandas/core/window/common.py
index 082c2f533f3de..12b73646e14bf 100644
--- a/pandas/core/window/common.py
+++ b/pandas/core/window/common.py
@@ -324,25 +324,3 @@ def func(arg, window, min_periods=None):
return cfunc(arg, window, min_periods)
return func
-
-
-def validate_baseindexer_support(func_name: Optional[str]) -> None:
- # GH 32865: These functions work correctly with a BaseIndexer subclass
- BASEINDEXER_WHITELIST = {
- "count",
- "min",
- "max",
- "mean",
- "sum",
- "median",
- "std",
- "var",
- "skew",
- "kurt",
- "quantile",
- }
- if isinstance(func_name, str) and func_name not in BASEINDEXER_WHITELIST:
- raise NotImplementedError(
- f"{func_name} is not supported with using a BaseIndexer "
- f"subclasses. You can use .apply() with {func_name}."
- )
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index 24130c044d186..6c775953e18db 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -48,7 +48,6 @@
calculate_center_offset,
calculate_min_periods,
get_weighted_roll_func,
- validate_baseindexer_support,
zsqrt,
)
from pandas.core.window.indexers import (
@@ -393,12 +392,11 @@ def _get_cython_func_type(self, func: str) -> Callable:
return self._get_roll_func(f"{func}_variable")
return partial(self._get_roll_func(f"{func}_fixed"), win=self._get_window())
- def _get_window_indexer(self, window: int, func_name: Optional[str]) -> BaseIndexer:
+ def _get_window_indexer(self, window: int) -> BaseIndexer:
"""
Return an indexer class that will compute the window start and end bounds
"""
if isinstance(self.window, BaseIndexer):
- validate_baseindexer_support(func_name)
return self.window
if self.is_freq_type:
return VariableWindowIndexer(index_array=self._on.asi8, window_size=window)
@@ -444,7 +442,7 @@ def _apply(
blocks, obj = self._create_blocks()
block_list = list(blocks)
- window_indexer = self._get_window_indexer(window, name)
+ window_indexer = self._get_window_indexer(window)
results = []
exclude: List[Scalar] = []
@@ -1632,20 +1630,23 @@ def quantile(self, quantile, interpolation="linear", **kwargs):
"""
def cov(self, other=None, pairwise=None, ddof=1, **kwargs):
- if isinstance(self.window, BaseIndexer):
- validate_baseindexer_support("cov")
-
if other is None:
other = self._selected_obj
# only default unset
pairwise = True if pairwise is None else pairwise
other = self._shallow_copy(other)
- # GH 16058: offset window
- if self.is_freq_type:
- window = self.win_freq
+ # GH 32865. We leverage rolling.mean, so we pass
+ # to the rolling constructors the data used when constructing self:
+ # window width, frequency data, or a BaseIndexer subclass
+ if isinstance(self.window, BaseIndexer):
+ window = self.window
else:
- window = self._get_window(other)
+ # GH 16058: offset window
+ if self.is_freq_type:
+ window = self.win_freq
+ else:
+ window = self._get_window(other)
def _get_cov(X, Y):
# GH #12373 : rolling functions error on float32 data
@@ -1778,15 +1779,19 @@ def _get_cov(X, Y):
)
def corr(self, other=None, pairwise=None, **kwargs):
- if isinstance(self.window, BaseIndexer):
- validate_baseindexer_support("corr")
-
if other is None:
other = self._selected_obj
# only default unset
pairwise = True if pairwise is None else pairwise
other = self._shallow_copy(other)
- window = self._get_window(other) if not self.is_freq_type else self.win_freq
+
+ # GH 32865. We leverage rolling.cov and rolling.std here, so we pass
+ # to the rolling constructors the data used when constructing self:
+ # window width, frequency data, or a BaseIndexer subclass
+ if isinstance(self.window, BaseIndexer):
+ window = self.window
+ else:
+ window = self._get_window(other) if not self.is_freq_type else self.win_freq
def _get_corr(a, b):
a = a.rolling(
diff --git a/pandas/tests/window/test_base_indexer.py b/pandas/tests/window/test_base_indexer.py
index 15e6a904dd11a..df58028dee862 100644
--- a/pandas/tests/window/test_base_indexer.py
+++ b/pandas/tests/window/test_base_indexer.py
@@ -82,19 +82,6 @@ def get_window_bounds(self, num_values, min_periods, center, closed):
df.rolling(indexer, win_type="boxcar")
-@pytest.mark.parametrize("func", ["cov", "corr"])
-def test_notimplemented_functions(func):
- # GH 32865
- class CustomIndexer(BaseIndexer):
- def get_window_bounds(self, num_values, min_periods, center, closed):
- return np.array([0, 1]), np.array([1, 2])
-
- df = DataFrame({"values": range(2)})
- indexer = CustomIndexer()
- with pytest.raises(NotImplementedError, match=f"{func} is not supported"):
- getattr(df.rolling(indexer), func)()
-
-
@pytest.mark.parametrize("constructor", [Series, DataFrame])
@pytest.mark.parametrize(
"func,np_func,expected,np_kwargs",
@@ -210,3 +197,40 @@ def test_rolling_forward_skewness(constructor):
]
)
tm.assert_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "func,expected",
+ [
+ ("cov", [2.0, 2.0, 2.0, 97.0, 2.0, -93.0, 2.0, 2.0, np.nan, np.nan],),
+ (
+ "corr",
+ [
+ 1.0,
+ 1.0,
+ 1.0,
+ 0.8704775290207161,
+ 0.018229084250926637,
+ -0.861357304646493,
+ 1.0,
+ 1.0,
+ np.nan,
+ np.nan,
+ ],
+ ),
+ ],
+)
+def test_rolling_forward_cov_corr(func, expected):
+ values1 = np.arange(10).reshape(-1, 1)
+ values2 = values1 * 2
+ values1[5, 0] = 100
+ values = np.concatenate([values1, values2], axis=1)
+
+ indexer = FixedForwardWindowIndexer(window_size=3)
+ rolling = DataFrame(values).rolling(window=indexer, min_periods=3)
+ # We are interested in checking only pairwise covariance / correlation
+ result = getattr(rolling, func)().loc[(slice(None), 1), 0]
+ result = result.reset_index(drop=True)
+ expected = Series(expected)
+ expected.name = result.name
+ tm.assert_equal(result, expected)
| - [X] closes #32865
- [X] reverts #33057
- [X] 2 tests added / 2 passed
- [X] passes `black pandas`
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [X] whatsnew entry
## Scope of PR
This is the final PR needed to solve #32865. It fixes `cov` and `corr` by passing the correct argument to `rolling` constructors if the functions are called with a custom `BaseIndexer` subclass. A separate test is added for `cov` and `corr` as the previous tests were single-variable and wouldn't work with two columns of data. I also propose we revert #33057.
## Details
The reason `cov` and `corr` didn't work was that we were passing `_get_window` results (usually, window width), instead of the `BaseIndexer` subclass to `rolling` constructors called inside the function. Passing `self.window` (when necessary) fixes the issue.
The new test asserts only against an explicit array, because shoehorning a comparison against `np.cov` an `np.corrcoef` is ugly (I've tried). Our `rolling.apply` isn't really suited to be called with bivariate statistics functions, and the necessary gymnastics didn't look good to me. I don't believe the minor benefit would be worth, but please say if you think coomparing against numpy is necessary.
Thanks to @mroeschke for implementing the `NotImplemented` error-raising behavior in #33057 . Now that all the functions are fixed, I propose we revert that commit.
## Background on the wider issue
We currently don't support several rolling window functions when building a rolling window object using a custom class descended from `pandas.api.indexers.Baseindexer`. The implementations were written with backward-looking windows in mind, and this led to these functions breaking.
Currently, using these functions returns a `NotImplemented` error thanks to #33057, but ideally we want to update the implementations, so that they will work without a performance hit. This is what I aim to do over a series of PRs.
## Perf notes
No changes to algorithms. | https://api.github.com/repos/pandas-dev/pandas/pulls/33804 | 2020-04-26T08:51:23Z | 2020-04-27T18:59:44Z | 2020-04-27T18:59:43Z | 2020-07-09T15:12:53Z |
BUG: incorrect freq in PeriodIndex-Period | diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index 4ddac12ae8155..f41044db2b49c 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -88,7 +88,7 @@ def wrapped(self, other):
if result is NotImplemented:
return NotImplemented
- new_freq = self._get_addsub_freq(other)
+ new_freq = self._get_addsub_freq(other, result)
result._freq = new_freq
return result
@@ -451,14 +451,16 @@ def _partial_date_slice(
# --------------------------------------------------------------------
# Arithmetic Methods
- def _get_addsub_freq(self, other) -> Optional[DateOffset]:
+ def _get_addsub_freq(self, other, result) -> Optional[DateOffset]:
"""
Find the freq we expect the result of an addition/subtraction operation
to have.
"""
if is_period_dtype(self.dtype):
- # Only used for ops that stay PeriodDtype
- return self.freq
+ if is_period_dtype(result.dtype):
+ # Only used for ops that stay PeriodDtype
+ return self.freq
+ return None
elif self.freq is None:
return None
elif lib.is_scalar(other) and isna(other):
diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py
index 4cf1988a33de1..55a547b361eb3 100644
--- a/pandas/tests/arithmetic/test_period.py
+++ b/pandas/tests/arithmetic/test_period.py
@@ -1444,8 +1444,13 @@ def test_pi_sub_period(self):
tm.assert_index_equal(result, exp)
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)
+ result = idx - pd.Period("NaT", freq="M")
+ tm.assert_index_equal(result, exp)
+ assert result.freq == exp.freq
+
+ result = pd.Period("NaT", freq="M") - idx
+ tm.assert_index_equal(result, exp)
+ assert result.freq == exp.freq
def test_pi_sub_pdnat(self):
# GH#13071
| introduced in #33552 | https://api.github.com/repos/pandas-dev/pandas/pulls/33801 | 2020-04-26T02:11:24Z | 2020-04-26T19:23:57Z | 2020-04-26T19:23:57Z | 2020-04-26T19:34:01Z |
IO: Fix feather s3 and http paths | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index cd1cb0b64f74a..188dfd893d66b 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -586,6 +586,7 @@ I/O
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`)
Plotting
^^^^^^^^
diff --git a/pandas/io/feather_format.py b/pandas/io/feather_format.py
index cd7045e7f2d2e..dfa43942fc8b3 100644
--- a/pandas/io/feather_format.py
+++ b/pandas/io/feather_format.py
@@ -4,7 +4,7 @@
from pandas import DataFrame, Int64Index, RangeIndex
-from pandas.io.common import stringify_path
+from pandas.io.common import get_filepath_or_buffer, stringify_path
def to_feather(df: DataFrame, path, **kwargs):
@@ -98,6 +98,12 @@ def read_feather(path, columns=None, use_threads: bool = True):
import_optional_dependency("pyarrow")
from pyarrow import feather
- path = stringify_path(path)
+ path, _, _, should_close = get_filepath_or_buffer(path)
+
+ df = feather.read_feather(path, columns=columns, use_threads=bool(use_threads))
+
+ # s3fs only validates the credentials when the file is closed.
+ if should_close:
+ path.close()
- return feather.read_feather(path, columns=columns, use_threads=bool(use_threads))
+ return df
diff --git a/pandas/tests/io/conftest.py b/pandas/tests/io/conftest.py
index fe71ca77a7dda..f1de15dd34464 100644
--- a/pandas/tests/io/conftest.py
+++ b/pandas/tests/io/conftest.py
@@ -15,7 +15,7 @@ def tips_file(datapath):
@pytest.fixture
def jsonl_file(datapath):
- """Path a JSONL dataset"""
+ """Path to a JSONL dataset"""
return datapath("io", "parser", "data", "items.jsonl")
@@ -26,7 +26,12 @@ def salaries_table(datapath):
@pytest.fixture
-def s3_resource(tips_file, jsonl_file):
+def feather_file(datapath):
+ return datapath("io", "data", "feather", "feather-0_3_1.feather")
+
+
+@pytest.fixture
+def s3_resource(tips_file, jsonl_file, feather_file):
"""
Fixture for mocking S3 interaction.
@@ -58,6 +63,7 @@ def s3_resource(tips_file, jsonl_file):
("tips.csv.gz", tips_file + ".gz"),
("tips.csv.bz2", tips_file + ".bz2"),
("items.jsonl", jsonl_file),
+ ("simple_dataset.feather", feather_file),
]
def add_tips_files(bucket_name):
diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py
index 0f09659a24936..000fc605dd5b1 100644
--- a/pandas/tests/io/parser/test_network.py
+++ b/pandas/tests/io/parser/test_network.py
@@ -13,6 +13,7 @@
from pandas import DataFrame
import pandas._testing as tm
+from pandas.io.feather_format import read_feather
from pandas.io.parsers import read_csv
@@ -203,7 +204,6 @@ def test_read_csv_chunked_download(self, s3_resource, caplog):
import s3fs
df = DataFrame(np.random.randn(100000, 4), columns=list("abcd"))
- buf = BytesIO()
str_buf = StringIO()
df.to_csv(str_buf)
@@ -227,3 +227,10 @@ def test_read_s3_with_hash_in_key(self, tips_df):
# GH 25945
result = read_csv("s3://pandas-test/tips#1.csv")
tm.assert_frame_equal(tips_df, result)
+
+ @td.skip_if_no("pyarrow")
+ def test_read_feather_s3_file_path(self, feather_file):
+ # GH 29055
+ expected = read_feather(feather_file)
+ res = read_feather("s3://pandas-test/simple_dataset.feather")
+ tm.assert_frame_equal(expected, res)
diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py
index 0755501ee6285..b43c8e82d4cce 100644
--- a/pandas/tests/io/test_feather.py
+++ b/pandas/tests/io/test_feather.py
@@ -159,3 +159,15 @@ def test_path_localpath(self):
def test_passthrough_keywords(self):
df = tm.makeDataFrame().reset_index()
self.check_round_trip(df, write_kwargs=dict(version=1))
+
+ @td.skip_if_no("pyarrow")
+ @tm.network
+ def test_http_path(self, feather_file):
+ # GH 29055
+ url = (
+ "https://raw.githubusercontent.com/pandas-dev/pandas/master/"
+ "pandas/tests/io/data/feather/feather-0_3_1.feather"
+ )
+ expected = pd.read_feather(feather_file)
+ res = pd.read_feather(url)
+ tm.assert_frame_equal(expected, res)
| - [x] closes #29055
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/33798 | 2020-04-26T01:01:29Z | 2020-04-26T19:31:34Z | 2020-04-26T19:31:34Z | 2020-04-27T23:47:23Z |
REF: mix NDArrayBackedExtensionArray into PandasArray | diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py
index 0ed9de804c55e..d1f8957859337 100644
--- a/pandas/core/arrays/_mixins.py
+++ b/pandas/core/arrays/_mixins.py
@@ -1,10 +1,11 @@
-from typing import Any, Sequence, TypeVar
+from typing import Any, Sequence, Tuple, TypeVar
import numpy as np
+from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
-from pandas.core.algorithms import take
+from pandas.core.algorithms import take, unique
from pandas.core.arrays.base import ExtensionArray
_T = TypeVar("_T", bound="NDArrayBackedExtensionArray")
@@ -60,3 +61,59 @@ def _validate_fill_value(self, fill_value):
ValueError
"""
raise AbstractMethodError(self)
+
+ # ------------------------------------------------------------------------
+
+ @property
+ def shape(self) -> Tuple[int, ...]:
+ return self._ndarray.shape
+
+ def __len__(self) -> int:
+ return self.shape[0]
+
+ @property
+ def ndim(self) -> int:
+ return len(self.shape)
+
+ @property
+ def size(self) -> int:
+ return np.prod(self.shape)
+
+ @property
+ def nbytes(self) -> int:
+ return self._ndarray.nbytes
+
+ def reshape(self: _T, *args, **kwargs) -> _T:
+ new_data = self._ndarray.reshape(*args, **kwargs)
+ return self._from_backing_data(new_data)
+
+ def ravel(self: _T, *args, **kwargs) -> _T:
+ new_data = self._ndarray.ravel(*args, **kwargs)
+ return self._from_backing_data(new_data)
+
+ @property
+ def T(self: _T) -> _T:
+ new_data = self._ndarray.T
+ return self._from_backing_data(new_data)
+
+ # ------------------------------------------------------------------------
+
+ def copy(self: _T) -> _T:
+ new_data = self._ndarray.copy()
+ return self._from_backing_data(new_data)
+
+ def repeat(self: _T, repeats, axis=None) -> _T:
+ """
+ Repeat elements of an array.
+
+ See Also
+ --------
+ numpy.ndarray.repeat
+ """
+ nv.validate_repeat(tuple(), dict(axis=axis))
+ new_data = self._ndarray.repeat(repeats, axis=axis)
+ return self._from_backing_data(new_data)
+
+ def unique(self: _T) -> _T:
+ new_data = unique(self._ndarray)
+ return self._from_backing_data(new_data)
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index b5d9386aa62c3..bf14ed44e3a1c 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -9,14 +9,7 @@
from pandas._libs import algos as libalgos, hashtable as htable
from pandas._typing import ArrayLike, Dtype, Ordered, Scalar
-from pandas.compat.numpy import function as nv
-from pandas.util._decorators import (
- Appender,
- Substitution,
- cache_readonly,
- deprecate_kwarg,
- doc,
-)
+from pandas.util._decorators import cache_readonly, deprecate_kwarg, doc
from pandas.util._validators import validate_bool_kwarg, validate_fillna_kwargs
from pandas.core.dtypes.cast import (
@@ -52,7 +45,6 @@
from pandas.core.algorithms import _get_data_algo, factorize, take_1d, unique1d
from pandas.core.array_algos.transforms import shift
from pandas.core.arrays._mixins import _T, NDArrayBackedExtensionArray
-from pandas.core.arrays.base import _extension_array_shared_docs
from pandas.core.base import NoNewAttributesMixin, PandasObject, _shared_docs
import pandas.core.common as com
from pandas.core.construction import array, extract_array, sanitize_array
@@ -449,14 +441,6 @@ def _formatter(self, boxed=False):
# Defer to CategoricalFormatter's formatter.
return None
- def copy(self) -> "Categorical":
- """
- Copy constructor.
- """
- return self._constructor(
- values=self._codes.copy(), dtype=self.dtype, fastpath=True
- )
-
def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike:
"""
Coerce this type to another dtype
@@ -484,13 +468,6 @@ def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike:
raise ValueError("Cannot convert float NaN to integer")
return np.array(self, dtype=dtype, copy=copy)
- @cache_readonly
- def size(self) -> int:
- """
- Return the len of myself.
- """
- return self._codes.size
-
@cache_readonly
def itemsize(self) -> int:
"""
@@ -1194,20 +1171,6 @@ def map(self, mapper):
__le__ = _cat_compare_op(operator.le)
__ge__ = _cat_compare_op(operator.ge)
- # for Series/ndarray like compat
- @property
- def shape(self):
- """
- Shape of the Categorical.
-
- For internal compatibility with numpy arrays.
-
- Returns
- -------
- shape : tuple
- """
- return tuple([len(self._codes)])
-
def shift(self, periods, fill_value=None):
"""
Shift Categorical by desired number of periods.
@@ -1313,13 +1276,6 @@ def __setstate__(self, state):
for k, v in state.items():
setattr(self, k, v)
- @property
- def T(self) -> "Categorical":
- """
- Return transposed numpy array.
- """
- return self
-
@property
def nbytes(self):
return self._codes.nbytes + self.dtype.categories.values.nbytes
@@ -1865,12 +1821,6 @@ def take_nd(self, indexer, allow_fill: bool = False, fill_value=None):
)
return self.take(indexer, allow_fill=allow_fill, fill_value=fill_value)
- def __len__(self) -> int:
- """
- The length of this Categorical.
- """
- return len(self._codes)
-
def __iter__(self):
"""
Returns an Iterator over the values of this Categorical.
@@ -2337,13 +2287,6 @@ def describe(self):
return result
- @Substitution(klass="Categorical")
- @Appender(_extension_array_shared_docs["repeat"])
- def repeat(self, repeats, axis=None):
- nv.validate_repeat(tuple(), dict(axis=axis))
- codes = self._codes.repeat(repeats)
- return self._constructor(values=codes, dtype=self.dtype, fastpath=True)
-
# Implement the ExtensionArray interface
@property
def _can_hold_na(self):
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index af5834f01c24c..145d6ffe4f078 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -465,24 +465,6 @@ def _from_backing_data(self: _T, arr: np.ndarray) -> _T:
# ------------------------------------------------------------------
- @property
- def ndim(self) -> int:
- return self._data.ndim
-
- @property
- def shape(self):
- return self._data.shape
-
- def reshape(self, *args, **kwargs):
- # Note: we drop any freq
- data = self._data.reshape(*args, **kwargs)
- return type(self)(data, dtype=self.dtype)
-
- def ravel(self, *args, **kwargs):
- # Note: we drop any freq
- data = self._data.ravel(*args, **kwargs)
- return type(self)(data, dtype=self.dtype)
-
@property
def _box_func(self):
"""
@@ -532,24 +514,12 @@ def _formatter(self, boxed=False):
# ----------------------------------------------------------------
# Array-Like / EA-Interface Methods
- @property
- def nbytes(self):
- return self._data.nbytes
-
def __array__(self, dtype=None) -> np.ndarray:
# used for Timedelta/DatetimeArray, overwritten by PeriodArray
if is_object_dtype(dtype):
return np.array(list(self), dtype=object)
return self._data
- @property
- def size(self) -> int:
- """The number of elements in this array."""
- return np.prod(self.shape)
-
- def __len__(self) -> int:
- return len(self._data)
-
def __getitem__(self, key):
"""
This getitem defers to the underlying array, which by-definition can
@@ -680,10 +650,6 @@ def view(self, dtype=None):
# ------------------------------------------------------------------
# ExtensionArray Interface
- def unique(self):
- result = unique1d(self.asi8)
- return type(self)(result, dtype=self.dtype)
-
@classmethod
def _concat_same_type(cls, to_concat, axis: int = 0):
@@ -927,18 +893,6 @@ def searchsorted(self, value, side="left", sorter=None):
# TODO: Use datetime64 semantics for sorting, xref GH#29844
return self.asi8.searchsorted(value, side=side, sorter=sorter)
- def repeat(self, repeats, *args, **kwargs):
- """
- Repeat elements of an array.
-
- See Also
- --------
- numpy.ndarray.repeat
- """
- nv.validate_repeat(args, kwargs)
- values = self._data.repeat(repeats)
- return type(self)(values.view("i8"), dtype=self.dtype)
-
def value_counts(self, dropna=False):
"""
Return a Series containing counts of unique values.
diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py
index 6806ed2afcf5c..b9384aa1bb092 100644
--- a/pandas/core/arrays/numpy_.py
+++ b/pandas/core/arrays/numpy_.py
@@ -17,8 +17,9 @@
from pandas import compat
from pandas.core import nanops
-from pandas.core.algorithms import searchsorted, take, unique
+from pandas.core.algorithms import searchsorted
from pandas.core.array_algos import masked_reductions
+from pandas.core.arrays._mixins import NDArrayBackedExtensionArray
from pandas.core.arrays.base import ExtensionArray, ExtensionOpsMixin
from pandas.core.construction import extract_array
from pandas.core.indexers import check_array_indexer
@@ -120,7 +121,9 @@ def itemsize(self) -> int:
return self._dtype.itemsize
-class PandasArray(ExtensionArray, ExtensionOpsMixin, NDArrayOperatorsMixin):
+class PandasArray(
+ NDArrayBackedExtensionArray, ExtensionOpsMixin, NDArrayOperatorsMixin
+):
"""
A pandas ExtensionArray for NumPy data.
@@ -191,6 +194,9 @@ def _from_factorized(cls, values, original) -> "PandasArray":
def _concat_same_type(cls, to_concat) -> "PandasArray":
return cls(np.concatenate(to_concat))
+ def _from_backing_data(self, arr: np.ndarray) -> "PandasArray":
+ return type(self)(arr)
+
# ------------------------------------------------------------------------
# Data
@@ -272,13 +278,6 @@ def __setitem__(self, key, value) -> None:
self._ndarray[key] = value
- def __len__(self) -> int:
- return len(self._ndarray)
-
- @property
- def nbytes(self) -> int:
- return self._ndarray.nbytes
-
def isna(self) -> np.ndarray:
return isna(self._ndarray)
@@ -311,17 +310,11 @@ def fillna(
new_values = self.copy()
return new_values
- def take(self, indices, allow_fill=False, fill_value=None) -> "PandasArray":
+ def _validate_fill_value(self, fill_value):
if fill_value is None:
# Primarily for subclasses
fill_value = self.dtype.na_value
- result = take(
- self._ndarray, indices, allow_fill=allow_fill, fill_value=fill_value
- )
- return type(self)(result)
-
- def copy(self) -> "PandasArray":
- return type(self)(self._ndarray.copy())
+ return fill_value
def _values_for_argsort(self) -> np.ndarray:
return self._ndarray
@@ -329,9 +322,6 @@ def _values_for_argsort(self) -> np.ndarray:
def _values_for_factorize(self) -> Tuple[np.ndarray, int]:
return self._ndarray, -1
- def unique(self) -> "PandasArray":
- return type(self)(unique(self._ndarray))
-
# ------------------------------------------------------------------------
# Reductions
| Share several more methods in NDArrayBackedExtensionArray. | https://api.github.com/repos/pandas-dev/pandas/pulls/33797 | 2020-04-25T22:12:02Z | 2020-04-25T23:56:02Z | 2020-04-25T23:56:02Z | 2020-04-26T14:09:12Z |
CLN: remove unused PeriodEngine methods | diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx
index d8e0d9c6bd7ab..871360672c6f0 100644
--- a/pandas/_libs/index.pyx
+++ b/pandas/_libs/index.pyx
@@ -21,14 +21,13 @@ cnp.import_array()
cimport pandas._libs.util as util
-from pandas._libs.tslibs import Period
+from pandas._libs.tslibs import Period, Timedelta
from pandas._libs.tslibs.nattype cimport c_NaT as NaT
from pandas._libs.tslibs.c_timestamp cimport _Timestamp
from pandas._libs.hashtable cimport HashTable
from pandas._libs import algos, hashtable as _hash
-from pandas._libs.tslibs import Timedelta, period as periodlib
from pandas._libs.missing import checknull
@@ -501,38 +500,6 @@ cdef class PeriodEngine(Int64Engine):
cdef _call_monotonic(self, values):
return algos.is_monotonic(values, timelike=True)
- def get_indexer(self, values):
- cdef:
- ndarray[int64_t, ndim=1] ordinals
-
- super(PeriodEngine, self)._ensure_mapping_populated()
-
- freq = super(PeriodEngine, self).vgetter().freq
- ordinals = periodlib.extract_ordinals(values, freq)
-
- return self.mapping.lookup(ordinals)
-
- def get_pad_indexer(self, other: np.ndarray, limit=None) -> np.ndarray:
- freq = super(PeriodEngine, self).vgetter().freq
- ordinal = periodlib.extract_ordinals(other, freq)
-
- return algos.pad(self._get_index_values(),
- np.asarray(ordinal), limit=limit)
-
- def get_backfill_indexer(self, other: np.ndarray, limit=None) -> np.ndarray:
- freq = super(PeriodEngine, self).vgetter().freq
- ordinal = periodlib.extract_ordinals(other, freq)
-
- return algos.backfill(self._get_index_values(),
- np.asarray(ordinal), limit=limit)
-
- def get_indexer_non_unique(self, targets):
- freq = super(PeriodEngine, self).vgetter().freq
- ordinal = periodlib.extract_ordinals(targets, freq)
- ordinal_array = np.asarray(ordinal)
-
- return super(PeriodEngine, self).get_indexer_non_unique(ordinal_array)
-
cdef class BaseMultiIndexCodesEngine:
"""
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py
index 957c01c2dca96..c2e4932a8f8e7 100644
--- a/pandas/core/indexes/period.py
+++ b/pandas/core/indexes/period.py
@@ -1,6 +1,5 @@
from datetime import datetime, timedelta
from typing import Any
-import weakref
import numpy as np
@@ -322,12 +321,6 @@ def _formatter_func(self):
# ------------------------------------------------------------------------
# Indexing
- @cache_readonly
- def _engine(self):
- # To avoid a reference cycle, pass a weakref of self._values to _engine_type.
- period = weakref.ref(self._values)
- return self._engine_type(period, len(self))
-
@doc(Index.__contains__)
def __contains__(self, key: Any) -> bool:
if isinstance(key, Period):
| https://api.github.com/repos/pandas-dev/pandas/pulls/33796 | 2020-04-25T21:00:30Z | 2020-04-25T21:39:32Z | 2020-04-25T21:39:32Z | 2020-04-25T21:40:33Z | |
DOC: Fix typos and improve parts of docs | diff --git a/doc/source/getting_started/intro_tutorials/02_read_write.rst b/doc/source/getting_started/intro_tutorials/02_read_write.rst
index 412a5f9e7485f..12fa2a1e094d6 100644
--- a/doc/source/getting_started/intro_tutorials/02_read_write.rst
+++ b/doc/source/getting_started/intro_tutorials/02_read_write.rst
@@ -23,7 +23,7 @@
<div class="card-body">
<p class="card-text">
-This tutorial uses the titanic data set, stored as CSV. The data
+This tutorial uses the Titanic data set, stored as CSV. The data
consists of the following data columns:
- PassengerId: Id of every passenger.
@@ -61,7 +61,7 @@ How do I read and write tabular data?
<ul class="task-bullet">
<li>
-I want to analyse the titanic passenger data, available as a CSV file.
+I want to analyze the Titanic passenger data, available as a CSV file.
.. ipython:: python
@@ -134,7 +134,7 @@ strings (``object``).
<ul class="task-bullet">
<li>
-My colleague requested the titanic data as a spreadsheet.
+My colleague requested the Titanic data as a spreadsheet.
.. ipython:: python
diff --git a/doc/source/getting_started/intro_tutorials/03_subset_data.rst b/doc/source/getting_started/intro_tutorials/03_subset_data.rst
index 31f434758876f..8476fee5e1eee 100644
--- a/doc/source/getting_started/intro_tutorials/03_subset_data.rst
+++ b/doc/source/getting_started/intro_tutorials/03_subset_data.rst
@@ -330,7 +330,7 @@ When using the column names, row labels or a condition expression, use
the ``loc`` operator in front of the selection brackets ``[]``. For both
the part before and after the comma, you can use a single label, a list
of labels, a slice of labels, a conditional expression or a colon. Using
-a colon specificies you want to select all rows or columns.
+a colon specifies you want to select all rows or columns.
.. raw:: html
diff --git a/doc/source/getting_started/intro_tutorials/06_calculate_statistics.rst b/doc/source/getting_started/intro_tutorials/06_calculate_statistics.rst
index 7a94c90525027..c7363b94146ac 100644
--- a/doc/source/getting_started/intro_tutorials/06_calculate_statistics.rst
+++ b/doc/source/getting_started/intro_tutorials/06_calculate_statistics.rst
@@ -23,7 +23,7 @@
<div class="card-body">
<p class="card-text">
-This tutorial uses the titanic data set, stored as CSV. The data
+This tutorial uses the Titanic data set, stored as CSV. The data
consists of the following data columns:
- PassengerId: Id of every passenger.
@@ -72,7 +72,7 @@ Aggregating statistics
<ul class="task-bullet">
<li>
-What is the average age of the titanic passengers?
+What is the average age of the Titanic passengers?
.. ipython:: python
@@ -95,7 +95,7 @@ across rows by default.
<ul class="task-bullet">
<li>
-What is the median age and ticket fare price of the titanic passengers?
+What is the median age and ticket fare price of the Titanic passengers?
.. ipython:: python
@@ -148,7 +148,7 @@ Aggregating statistics grouped by category
<ul class="task-bullet">
<li>
-What is the average age for male versus female titanic passengers?
+What is the average age for male versus female Titanic passengers?
.. ipython:: python
diff --git a/doc/source/getting_started/intro_tutorials/07_reshape_table_layout.rst b/doc/source/getting_started/intro_tutorials/07_reshape_table_layout.rst
index b28a9012a4ad9..a9652969ffc79 100644
--- a/doc/source/getting_started/intro_tutorials/07_reshape_table_layout.rst
+++ b/doc/source/getting_started/intro_tutorials/07_reshape_table_layout.rst
@@ -23,7 +23,7 @@
<div class="card-body">
<p class="card-text">
-This tutorial uses the titanic data set, stored as CSV. The data
+This tutorial uses the Titanic data set, stored as CSV. The data
consists of the following data columns:
- PassengerId: Id of every passenger.
@@ -122,7 +122,7 @@ Sort table rows
<ul class="task-bullet">
<li>
-I want to sort the titanic data according to the age of the passengers.
+I want to sort the Titanic data according to the age of the passengers.
.. ipython:: python
@@ -138,7 +138,7 @@ I want to sort the titanic data according to the age of the passengers.
<ul class="task-bullet">
<li>
-I want to sort the titanic data according to the cabin class and age in descending order.
+I want to sort the Titanic data according to the cabin class and age in descending order.
.. ipython:: python
@@ -282,7 +282,7 @@ For more information about :meth:`~DataFrame.pivot_table`, see the user guide se
</div>
.. note::
- If case you are wondering, :meth:`~DataFrame.pivot_table` is indeed directly linked
+ In case you are wondering, :meth:`~DataFrame.pivot_table` is indeed directly linked
to :meth:`~DataFrame.groupby`. The same result can be derived by grouping on both
``parameter`` and ``location``:
@@ -338,7 +338,7 @@ newly created column.
The solution is the short version on how to apply :func:`pandas.melt`. The method
will *melt* all columns NOT mentioned in ``id_vars`` together into two
-columns: A columns with the column header names and a column with the
+columns: A column with the column header names and a column with the
values itself. The latter column gets by default the name ``value``.
The :func:`pandas.melt` method can be defined in more detail:
@@ -357,8 +357,8 @@ The result in the same, but in more detail defined:
- ``value_vars`` defines explicitly which columns to *melt* together
- ``value_name`` provides a custom column name for the values column
- instead of the default columns name ``value``
-- ``var_name`` provides a custom column name for the columns collecting
+ instead of the default column name ``value``
+- ``var_name`` provides a custom column name for the column collecting
the column header names. Otherwise it takes the index name or a
default ``variable``
@@ -383,7 +383,7 @@ Conversion from wide to long format with :func:`pandas.melt` is explained in the
<h4>REMEMBER</h4>
- Sorting by one or more columns is supported by ``sort_values``
-- The ``pivot`` function is purely restructering of the data,
+- The ``pivot`` function is purely restructuring of the data,
``pivot_table`` supports aggregations
- The reverse of ``pivot`` (long to wide format) is ``melt`` (wide to
long format)
diff --git a/doc/source/getting_started/intro_tutorials/08_combine_dataframes.rst b/doc/source/getting_started/intro_tutorials/08_combine_dataframes.rst
index b6b3c97f2405b..600a75b156ac4 100644
--- a/doc/source/getting_started/intro_tutorials/08_combine_dataframes.rst
+++ b/doc/source/getting_started/intro_tutorials/08_combine_dataframes.rst
@@ -305,7 +305,7 @@ More information on join/merge of tables is provided in the user guide section o
<div class="shadow gs-callout gs-callout-remember">
<h4>REMEMBER</h4>
-- Multiple tables can be concatenated both column as row wise using
+- Multiple tables can be concatenated both column-wise and row-wise using
the ``concat`` function.
- For database-like merging/joining of tables, use the ``merge``
function.
diff --git a/doc/source/getting_started/intro_tutorials/09_timeseries.rst b/doc/source/getting_started/intro_tutorials/09_timeseries.rst
index 15bdf43543d9a..19351e0e3bc75 100644
--- a/doc/source/getting_started/intro_tutorials/09_timeseries.rst
+++ b/doc/source/getting_started/intro_tutorials/09_timeseries.rst
@@ -78,7 +78,7 @@ provide any datetime operations (e.g. extract the year, day of the
week,…). By applying the ``to_datetime`` function, pandas interprets the
strings and convert these to datetime (i.e. ``datetime64[ns, UTC]``)
objects. In pandas we call these datetime objects similar to
-``datetime.datetime`` from the standard library a :class:`pandas.Timestamp`.
+``datetime.datetime`` from the standard library as :class:`pandas.Timestamp`.
.. raw:: html
@@ -99,7 +99,7 @@ objects. In pandas we call these datetime objects similar to
Why are these :class:`pandas.Timestamp` objects useful? Let’s illustrate the added
value with some example cases.
- What is the start and end date of the time series data set working
+ What is the start and end date of the time series data set we are working
with?
.. ipython:: python
@@ -214,7 +214,7 @@ Plot the typical :math:`NO_2` pattern during the day of our time series of all s
Similar to the previous case, we want to calculate a given statistic
(e.g. mean :math:`NO_2`) **for each hour of the day** and we can use the
-split-apply-combine approach again. For this case, the datetime property ``hour``
+split-apply-combine approach again. For this case, we use the datetime property ``hour``
of pandas ``Timestamp``, which is also accessible by the ``dt`` accessor.
.. raw:: html
diff --git a/doc/source/getting_started/intro_tutorials/10_text_data.rst b/doc/source/getting_started/intro_tutorials/10_text_data.rst
index a7f3bdc9abcc6..93ad35fb1960b 100644
--- a/doc/source/getting_started/intro_tutorials/10_text_data.rst
+++ b/doc/source/getting_started/intro_tutorials/10_text_data.rst
@@ -23,7 +23,7 @@
<div class="card-body">
<p class="card-text">
-This tutorial uses the titanic data set, stored as CSV. The data
+This tutorial uses the Titanic data set, stored as CSV. The data
consists of the following data columns:
- PassengerId: Id of every passenger.
@@ -102,7 +102,7 @@ Create a new column ``Surname`` that contains the surname of the Passengers by e
Using the :meth:`Series.str.split` method, each of the values is returned as a list of
2 elements. The first element is the part before the comma and the
-second element the part after the comma.
+second element is the part after the comma.
.. ipython:: python
@@ -135,7 +135,7 @@ More information on extracting parts of strings is available in the user guide s
<ul class="task-bullet">
<li>
-Extract the passenger data about the Countess on board of the Titanic.
+Extract the passenger data about the Countesses on board of the Titanic.
.. ipython:: python
@@ -145,15 +145,15 @@ Extract the passenger data about the Countess on board of the Titanic.
titanic[titanic["Name"].str.contains("Countess")]
-(*Interested in her story? See*\ `Wikipedia <https://en.wikipedia.org/wiki/No%C3%ABl_Leslie,_Countess_of_Rothes>`__\ *!*)
+(*Interested in her story? See *\ `Wikipedia <https://en.wikipedia.org/wiki/No%C3%ABl_Leslie,_Countess_of_Rothes>`__\ *!*)
The string method :meth:`Series.str.contains` checks for each of the values in the
column ``Name`` if the string contains the word ``Countess`` and returns
for each of the values ``True`` (``Countess`` is part of the name) of
-``False`` (``Countess`` is notpart of the name). This output can be used
+``False`` (``Countess`` is not part of the name). This output can be used
to subselect the data using conditional (boolean) indexing introduced in
the :ref:`subsetting of data tutorial <10min_tut_03_subset>`. As there was
-only 1 Countess on the Titanic, we get one row as a result.
+only one Countess on the Titanic, we get one row as a result.
.. raw:: html
@@ -161,8 +161,8 @@ only 1 Countess on the Titanic, we get one row as a result.
</ul>
.. note::
- More powerful extractions on strings is supported, as the
- :meth:`Series.str.contains` and :meth:`Series.str.extract` methods accepts `regular
+ More powerful extractions on strings are supported, as the
+ :meth:`Series.str.contains` and :meth:`Series.str.extract` methods accept `regular
expressions <https://docs.python.org/3/library/re.html>`__, but out of
scope of this tutorial.
@@ -182,7 +182,7 @@ More information on extracting parts of strings is available in the user guide s
<ul class="task-bullet">
<li>
-Which passenger of the titanic has the longest name?
+Which passenger of the Titanic has the longest name?
.. ipython:: python
@@ -220,7 +220,7 @@ we can do a selection using the ``loc`` operator, introduced in the
<ul class="task-bullet">
<li>
-In the ‘Sex’ columns, replace values of ‘male’ by ‘M’ and all ‘female’ values by ‘F’
+In the "Sex" column, replace values of "male" by "M" and values of "female" by "F"
.. ipython:: python
diff --git a/doc/source/user_guide/10min.rst b/doc/source/user_guide/10min.rst
index 9994287c827e3..93c50fff40305 100644
--- a/doc/source/user_guide/10min.rst
+++ b/doc/source/user_guide/10min.rst
@@ -664,7 +664,7 @@ Convert the raw grades to a categorical data type.
df["grade"]
Rename the categories to more meaningful names (assigning to
-:meth:`Series.cat.categories` is inplace!).
+:meth:`Series.cat.categories` is in place!).
.. ipython:: python
diff --git a/doc/source/user_guide/basics.rst b/doc/source/user_guide/basics.rst
index 055b43bc1e59b..a57998d6605d4 100644
--- a/doc/source/user_guide/basics.rst
+++ b/doc/source/user_guide/basics.rst
@@ -68,7 +68,7 @@ the ``.array`` property
s.index.array
:attr:`~Series.array` will always be an :class:`~pandas.api.extensions.ExtensionArray`.
-The exact details of what an :class:`~pandas.api.extensions.ExtensionArray` is and why pandas uses them is a bit
+The exact details of what an :class:`~pandas.api.extensions.ExtensionArray` is and why pandas uses them are a bit
beyond the scope of this introduction. See :ref:`basics.dtypes` for more.
If you know you need a NumPy array, use :meth:`~Series.to_numpy`
@@ -518,7 +518,7 @@ data (``True`` by default):
Combined with the broadcasting / arithmetic behavior, one can describe various
statistical procedures, like standardization (rendering data zero mean and
-standard deviation 1), very concisely:
+standard deviation of 1), very concisely:
.. ipython:: python
@@ -700,7 +700,7 @@ By default all columns are used but a subset can be selected using the ``subset`
frame = pd.DataFrame(data)
frame.value_counts()
-Similarly, you can get the most frequently occurring value(s) (the mode) of the values in a Series or DataFrame:
+Similarly, you can get the most frequently occurring value(s), i.e. the mode, of the values in a Series or DataFrame:
.. ipython:: python
@@ -1022,7 +1022,7 @@ Mixed dtypes
++++++++++++
When presented with mixed dtypes that cannot aggregate, ``.agg`` will only take the valid
-aggregations. This is similar to how groupby ``.agg`` works.
+aggregations. This is similar to how ``.groupby.agg`` works.
.. ipython:: python
@@ -1041,7 +1041,7 @@ aggregations. This is similar to how groupby ``.agg`` works.
Custom describe
+++++++++++++++
-With ``.agg()`` is it possible to easily create a custom describe function, similar
+With ``.agg()`` it is possible to easily create a custom describe function, similar
to the built in :ref:`describe function <basics.describe>`.
.. ipython:: python
@@ -1083,7 +1083,8 @@ function name or a user defined function.
tsdf.transform('abs')
tsdf.transform(lambda x: x.abs())
-Here :meth:`~DataFrame.transform` received a single function; this is equivalent to a ufunc application.
+Here :meth:`~DataFrame.transform` received a single function; this is equivalent to a `ufunc
+<https://numpy.org/doc/stable/reference/ufuncs.html>`__ application.
.. ipython:: python
@@ -1457,7 +1458,7 @@ for altering the ``Series.name`` attribute.
.. versionadded:: 0.24.0
-The methods :meth:`~DataFrame.rename_axis` and :meth:`~Series.rename_axis`
+The methods :meth:`DataFrame.rename_axis` and :meth:`Series.rename_axis`
allow specific names of a `MultiIndex` to be changed (as opposed to the
labels).
| - [ ] 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/33793 | 2020-04-25T18:28:13Z | 2020-05-11T00:32:33Z | 2020-05-11T00:32:33Z | 2020-05-12T07:59:38Z |
REF: remove need to override get_indexer_non_unique in DatetimeIndexOpsMixin | diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx
index d8e0d9c6bd7ab..5f04c2c7cd14e 100644
--- a/pandas/_libs/index.pyx
+++ b/pandas/_libs/index.pyx
@@ -441,6 +441,10 @@ cdef class DatetimeEngine(Int64Engine):
except KeyError:
raise KeyError(val)
+ def get_indexer_non_unique(self, targets):
+ # we may get datetime64[ns] or timedelta64[ns], cast these to int64
+ return super().get_indexer_non_unique(targets.view("i8"))
+
def get_indexer(self, values):
self._ensure_mapping_populated()
if values.dtype != self._get_box_dtype():
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 5cad76fd18c58..69e9b77633b56 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -13,7 +13,7 @@
from pandas._libs.tslibs import OutOfBoundsDatetime, Timestamp
from pandas._libs.tslibs.period import IncompatibleFrequency
from pandas._libs.tslibs.timezones import tz_compare
-from pandas._typing import Label
+from pandas._typing import DtypeObj, Label
from pandas.compat import set_function_name
from pandas.compat.numpy import function as nv
from pandas.util._decorators import Appender, Substitution, cache_readonly, doc
@@ -4626,6 +4626,10 @@ def get_indexer_non_unique(self, target):
if pself is not self or ptarget is not target:
return pself.get_indexer_non_unique(ptarget)
+ if not self._is_comparable_dtype(target.dtype):
+ no_matches = -1 * np.ones(self.shape, dtype=np.intp)
+ return no_matches, no_matches
+
if is_categorical_dtype(target.dtype):
tgt_values = np.asarray(target)
else:
@@ -4651,16 +4655,33 @@ def get_indexer_for(self, target, **kwargs):
indexer, _ = self.get_indexer_non_unique(target, **kwargs)
return indexer
- def _maybe_promote(self, other):
- # A hack, but it works
+ def _maybe_promote(self, other: "Index"):
+ """
+ When dealing with an object-dtype Index and a non-object Index, see
+ if we can upcast the object-dtype one to improve performance.
+ """
if self.inferred_type == "date" and isinstance(other, ABCDatetimeIndex):
return type(other)(self), other
+ elif self.inferred_type == "timedelta" and isinstance(other, ABCTimedeltaIndex):
+ # TODO: we dont have tests that get here
+ return type(other)(self), other
elif self.inferred_type == "boolean":
if not is_object_dtype(self.dtype):
return self.astype("object"), other.astype("object")
+
+ if not is_object_dtype(self.dtype) and is_object_dtype(other.dtype):
+ # Reverse op so we dont need to re-implement on the subclasses
+ other, self = other._maybe_promote(self)
+
return self, other
+ def _is_comparable_dtype(self, dtype: DtypeObj) -> bool:
+ """
+ Can we compare values of the given dtype to our own?
+ """
+ return True
+
def groupby(self, values) -> PrettyDict[Hashable, np.ndarray]:
"""
Group the index labels by a given array of values.
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index cf653a6875a9c..f40fdc469bb92 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -8,14 +8,13 @@
from pandas._libs import NaT, iNaT, join as libjoin, lib
from pandas._libs.tslibs import timezones
-from pandas._typing import DtypeObj, Label
+from pandas._typing import Label
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
from pandas.util._decorators import Appender, cache_readonly, doc
from pandas.core.dtypes.common import (
ensure_int64,
- ensure_platform_int,
is_bool_dtype,
is_dtype_equal,
is_integer,
@@ -31,7 +30,7 @@
from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin
from pandas.core.base import IndexOpsMixin
import pandas.core.indexes.base as ibase
-from pandas.core.indexes.base import Index, _index_shared_docs, ensure_index
+from pandas.core.indexes.base import Index, _index_shared_docs
from pandas.core.indexes.extension import (
ExtensionIndex,
inherit_names,
@@ -99,12 +98,6 @@ class DatetimeIndexOpsMixin(ExtensionIndex):
def is_all_dates(self) -> bool:
return True
- def _is_comparable_dtype(self, dtype: DtypeObj) -> bool:
- """
- Can we compare values of the given dtype to our own?
- """
- raise AbstractMethodError(self)
-
# ------------------------------------------------------------------------
# Abstract data attributes
@@ -430,21 +423,6 @@ def _partial_date_slice(
# try to find the dates
return (lhs_mask & rhs_mask).nonzero()[0]
- @Appender(Index.get_indexer_non_unique.__doc__)
- def get_indexer_non_unique(self, target):
- target = ensure_index(target)
- pself, ptarget = self._maybe_promote(target)
- if pself is not self or ptarget is not target:
- return pself.get_indexer_non_unique(ptarget)
-
- if not self._is_comparable_dtype(target.dtype):
- no_matches = -1 * np.ones(self.shape, dtype=np.intp)
- return no_matches, no_matches
-
- tgt_values = target.asi8
- indexer, missing = self._engine.get_indexer_non_unique(tgt_values)
- return ensure_platform_int(indexer), missing
-
# --------------------------------------------------------------------
__add__ = make_wrapped_arith_op("__add__")
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index 649d4e6dfc384..1b43176d4b3e3 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -538,11 +538,6 @@ def _validate_partial_date_slice(self, reso: str):
# _parsed_string_to_bounds allows it.
raise KeyError
- def _maybe_promote(self, other):
- if other.inferred_type == "date":
- other = DatetimeIndex(other)
- return self, other
-
def get_loc(self, key, method=None, tolerance=None):
"""
Get integer location for requested label
diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py
index ad698afaedb59..741951d480d18 100644
--- a/pandas/core/indexes/timedeltas.py
+++ b/pandas/core/indexes/timedeltas.py
@@ -197,11 +197,6 @@ def astype(self, dtype, copy=True):
return Index(result.astype("i8"), name=self.name)
return DatetimeIndexOpsMixin.astype(self, dtype, copy=copy)
- def _maybe_promote(self, other):
- if other.inferred_type == "timedelta":
- other = TimedeltaIndex(other)
- return self, other
-
def _is_comparable_dtype(self, dtype: DtypeObj) -> bool:
"""
Can we compare values of the given dtype to our own?
| https://api.github.com/repos/pandas-dev/pandas/pulls/33792 | 2020-04-25T17:05:31Z | 2020-04-25T20:51:26Z | 2020-04-25T20:51:26Z | 2020-04-25T21:03:17Z | |
DOC: Link to table schema and remove reference to internal API | diff --git a/pandas/io/json/_table_schema.py b/pandas/io/json/_table_schema.py
index 6061af72901a5..50686594a7576 100644
--- a/pandas/io/json/_table_schema.py
+++ b/pandas/io/json/_table_schema.py
@@ -211,7 +211,9 @@ def build_table_schema(data, index=True, primary_key=None, version=True):
Notes
-----
- See `_as_json_table_type` for conversion types.
+ See `Table Schema
+ <https://pandas.pydata.org/docs/user_guide/io.html#table-schema>`__ for
+ conversion types.
Timedeltas as converted to ISO8601 duration format with
9 decimal places after the seconds field for nanosecond precision.
| - [x] closes #33130
- [ ] tests added / passed (Not needed)
- [x] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` (Markdown link which will not be shown)
- [ ] whatsnew entry (Not needed)
| https://api.github.com/repos/pandas-dev/pandas/pulls/33791 | 2020-04-25T14:59:44Z | 2020-04-29T22:49:08Z | 2020-04-29T22:49:08Z | 2020-04-29T22:49:11Z |
CLN: Pass numpy args as kwargs | diff --git a/pandas/compat/numpy/function.py b/pandas/compat/numpy/function.py
index 30768f9bf2b06..d7a14c28cc9ca 100644
--- a/pandas/compat/numpy/function.py
+++ b/pandas/compat/numpy/function.py
@@ -251,11 +251,16 @@ def validate_cum_func_with_skipna(skipna, args, kwargs, name):
STAT_FUNC_DEFAULTS["dtype"] = None
STAT_FUNC_DEFAULTS["out"] = None
-PROD_DEFAULTS = SUM_DEFAULTS = STAT_FUNC_DEFAULTS.copy()
+SUM_DEFAULTS = STAT_FUNC_DEFAULTS.copy()
SUM_DEFAULTS["axis"] = None
SUM_DEFAULTS["keepdims"] = False
SUM_DEFAULTS["initial"] = None
+PROD_DEFAULTS = STAT_FUNC_DEFAULTS.copy()
+PROD_DEFAULTS["axis"] = None
+PROD_DEFAULTS["keepdims"] = False
+PROD_DEFAULTS["initial"] = None
+
MEDIAN_DEFAULTS = STAT_FUNC_DEFAULTS.copy()
MEDIAN_DEFAULTS["overwrite_input"] = False
MEDIAN_DEFAULTS["keepdims"] = False
diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py
index e9950e0edaffb..6806ed2afcf5c 100644
--- a/pandas/core/arrays/numpy_.py
+++ b/pandas/core/arrays/numpy_.py
@@ -365,36 +365,14 @@ def max(self, skipna: bool = True, **kwargs) -> Scalar:
)
return result
- def sum(
- self,
- axis=None,
- dtype=None,
- out=None,
- keepdims=False,
- initial=None,
- skipna=True,
- min_count=0,
- ):
- nv.validate_sum(
- (), dict(dtype=dtype, out=out, keepdims=keepdims, initial=initial)
- )
+ def sum(self, axis=None, skipna=True, min_count=0, **kwargs) -> Scalar:
+ nv.validate_sum((), kwargs)
return nanops.nansum(
self._ndarray, axis=axis, skipna=skipna, min_count=min_count
)
- def prod(
- self,
- axis=None,
- dtype=None,
- out=None,
- keepdims=False,
- initial=None,
- skipna=True,
- min_count=0,
- ):
- nv.validate_prod(
- (), dict(dtype=dtype, out=out, keepdims=keepdims, initial=initial)
- )
+ def prod(self, axis=None, skipna=True, min_count=0, **kwargs) -> Scalar:
+ nv.validate_prod((), kwargs)
return nanops.nanprod(
self._ndarray, axis=axis, skipna=skipna, min_count=min_count
)
| This is already done in some places for PandasArray, e.g., min / max, and seems cleaner with less boilerplate | https://api.github.com/repos/pandas-dev/pandas/pulls/33789 | 2020-04-25T14:35:04Z | 2020-04-25T21:47:28Z | 2020-04-25T21:47:28Z | 2020-04-25T22:00:36Z |
DOC: Remove ambiguity in fill_value documentation | diff --git a/pandas/core/ops/docstrings.py b/pandas/core/ops/docstrings.py
index 449a477646c02..4ace873f029ae 100644
--- a/pandas/core/ops/docstrings.py
+++ b/pandas/core/ops/docstrings.py
@@ -399,7 +399,7 @@ def _make_flex_doc(op_name, typ):
Return {desc} of series and other, element-wise (binary operator `{op_name}`).
Equivalent to ``{equiv}``, but with support to substitute a fill_value for
-missing data in one of the inputs.
+missing data in either one of the inputs.
Parameters
----------
@@ -408,7 +408,7 @@ def _make_flex_doc(op_name, typ):
Fill existing missing (NaN) values, and any new element needed for
successful Series alignment, with this value before computation.
If data in both corresponding Series locations is missing
- the result will be missing.
+ the result of filling (at that location) will be missing.
level : int or name
Broadcast across a level, matching Index values on the
passed MultiIndex level.
| - [x] closes #33380
- [ ] tests added / passed (Not needed)
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry (Not needed)
| https://api.github.com/repos/pandas-dev/pandas/pulls/33788 | 2020-04-25T14:30:52Z | 2020-04-25T21:48:50Z | 2020-04-25T21:48:50Z | 2020-04-26T08:00:14Z |
BUG, TST, DOC: fix core.missing._akima_interpolate will raise AttributeError | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index e8fdaf0ae5d49..478956666e625 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -538,6 +538,7 @@ Missing
- Calling :meth:`fillna` on an empty Series now correctly returns a shallow copied object. The behaviour is now consistent with :class:`Index`, :class:`DataFrame` and a non-empty :class:`Series` (:issue:`32543`).
- Bug in :meth:`replace` when argument ``to_replace`` is of type dict/list and is used on a :class:`Series` containing ``<NA>`` was raising a ``TypeError``. The method now handles this by ignoring ``<NA>`` values when doing the comparison for the replacement (:issue:`32621`)
- Bug in :meth:`~Series.any` and :meth:`~Series.all` incorrectly returning ``<NA>`` for all ``False`` or all ``True`` values using the nulllable boolean dtype and with ``skipna=False`` (:issue:`33253`)
+- Clarified documentation on interpolate with method =akima. The ``der`` parameter must be scalar or None (:issue:`33426`)
MultiIndex
^^^^^^^^^^
diff --git a/pandas/core/missing.py b/pandas/core/missing.py
index 2acaa808d8324..7b5399ca85e79 100644
--- a/pandas/core/missing.py
+++ b/pandas/core/missing.py
@@ -445,8 +445,9 @@ def _akima_interpolate(xi, yi, x, der=0, axis=0):
A 1-D array of real values. `yi`'s length along the interpolation
axis must be equal to the length of `xi`. If N-D array, use axis
parameter to select correct axis.
- x : scalar or array_like of length M.
- der : int or list, optional
+ x : scalar or array_like
+ Of length M.
+ der : int, optional
How many derivatives to extract; None for all potentially
nonzero derivatives (that is a number equal to the number
of points), or a list of derivatives to extract. This number
@@ -468,12 +469,7 @@ def _akima_interpolate(xi, yi, x, der=0, axis=0):
P = interpolate.Akima1DInterpolator(xi, yi, axis=axis)
- if der == 0:
- return P(x)
- elif interpolate._isscalar(der):
- return P(x, der=der)
- else:
- return [P(x, nu) for nu in der]
+ return P(x, nu=der)
def _cubicspline_interpolate(xi, yi, x, axis=0, bc_type="not-a-knot", extrapolate=None):
diff --git a/pandas/tests/series/methods/test_interpolate.py b/pandas/tests/series/methods/test_interpolate.py
index b26cb21bc5f3d..db1c07e1bd276 100644
--- a/pandas/tests/series/methods/test_interpolate.py
+++ b/pandas/tests/series/methods/test_interpolate.py
@@ -133,17 +133,28 @@ def test_interpolate_akima(self):
ser = Series([10, 11, 12, 13])
+ # interpolate at new_index where `der` is zero
expected = Series(
[11.00, 11.25, 11.50, 11.75, 12.00, 12.25, 12.50, 12.75, 13.00],
index=Index([1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0]),
)
- # interpolate at new_index
new_index = ser.index.union(Index([1.25, 1.5, 1.75, 2.25, 2.5, 2.75])).astype(
float
)
interp_s = ser.reindex(new_index).interpolate(method="akima")
tm.assert_series_equal(interp_s[1:3], expected)
+ # interpolate at new_index where `der` is a non-zero int
+ expected = Series(
+ [11.0, 1.0, 1.0, 1.0, 12.0, 1.0, 1.0, 1.0, 13.0],
+ index=Index([1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0]),
+ )
+ new_index = ser.index.union(Index([1.25, 1.5, 1.75, 2.25, 2.5, 2.75])).astype(
+ float
+ )
+ interp_s = ser.reindex(new_index).interpolate(method="akima", der=1)
+ tm.assert_series_equal(interp_s[1:3], expected)
+
@td.skip_if_no_scipy
def test_interpolate_piecewise_polynomial(self):
ser = Series([10, 11, 12, 13])
| - [x] closes #33426
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Wasn't sure if this warranted a whatsnew entry since its mostly code cleanup | https://api.github.com/repos/pandas-dev/pandas/pulls/33784 | 2020-04-25T04:54:33Z | 2020-04-26T19:57:38Z | 2020-04-26T19:57:38Z | 2020-04-26T19:57:42Z |
DOC: fix doc for crosstab with Categorical data input | diff --git a/doc/source/user_guide/reshaping.rst b/doc/source/user_guide/reshaping.rst
index 7e890962d8da1..c476e33b8ddde 100644
--- a/doc/source/user_guide/reshaping.rst
+++ b/doc/source/user_guide/reshaping.rst
@@ -471,9 +471,8 @@ If ``crosstab`` receives only two Series, it will provide a frequency table.
pd.crosstab(df['A'], df['B'])
-Any input passed containing ``Categorical`` data will have **all** of its
-categories included in the cross-tabulation, even if the actual data does
-not contain any instances of a particular category.
+``crosstab`` can also be implemented
+to ``Categorical`` data.
.. ipython:: python
@@ -481,6 +480,15 @@ not contain any instances of a particular category.
bar = pd.Categorical(['d', 'e'], categories=['d', 'e', 'f'])
pd.crosstab(foo, bar)
+If you want to include **all** of data categories even if the actual data does
+not contain any instances of a particular category, you should set ``dropna=False``.
+
+For example:
+
+.. ipython:: python
+
+ pd.crosstab(foo, bar, dropna=False)
+
Normalization
~~~~~~~~~~~~~
| Crosstab function should set dropna=False to keep the categories which not appear in the data, but in the DOC, it seems to be inconsistent with the description. Two examples for comparison may be better for users to get this point.
https://pandas.pydata.org/docs/dev/user_guide/reshaping.html#cross-tabulations | https://api.github.com/repos/pandas-dev/pandas/pulls/33783 | 2020-04-25T03:10:39Z | 2020-04-27T02:16:26Z | 2020-04-27T02:16:26Z | 2020-04-27T02:17:12Z |
BUG: Add warning if rows have more columns than expected | diff --git a/asv_bench/benchmarks/io/excel.py b/asv_bench/benchmarks/io/excel.py
index 80af2cff41769..e9776ff2c641e 100644
--- a/asv_bench/benchmarks/io/excel.py
+++ b/asv_bench/benchmarks/io/excel.py
@@ -11,7 +11,7 @@
def _generate_dataframe():
- N = 2000
+ N = 20000
C = 5
df = DataFrame(
np.random.randn(N, C),
@@ -69,5 +69,9 @@ def time_read_excel(self, engine):
fname = self.fname_odf if engine == "odf" else self.fname_excel
read_excel(fname, engine=engine)
+ def nrows_read_excel(self, engine):
+ fname = self.fname_odf if engine == "odf" else self.fname_excel
+ read_excel(fname, engine=engine, nrows=1)
+
from ..pandas_vb_common import setup # noqa: F401 isort:skip
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index ede4fdc5e1d8b..209883dab3ce6 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -49,7 +49,7 @@
pandas_dtype,
)
from pandas.core.dtypes.dtypes import CategoricalDtype
-from pandas.core.dtypes.missing import isna
+from pandas.core.dtypes.missing import isna, notna
from pandas.core import algorithms
from pandas.core.arrays import Categorical
@@ -1322,6 +1322,31 @@ def _validate_parse_dates_arg(parse_dates):
return parse_dates
+def _check_unexpected_data(columns, data, index_col):
+ """
+ Checks if ammount of columns in data matches expected number of columns.
+ Raises a warning if those numbers don't match.
+
+ Parameters
+ ----------
+ columns : list
+ List that contains columns names.
+ data : array-like
+ Object that contains column data.
+ index_col : list or False, optional
+ Columns to use as the index.
+ """
+ if index_col is None or index_col is False:
+ index_col = []
+ expected_columns = len(columns) + len(index_col)
+ if expected_columns != len(data) and notna(data[expected_columns:]).any():
+ warnings.warn(
+ "Expected {} columns instead of {}".format(expected_columns, len(data)),
+ ParserWarning,
+ stacklevel=2,
+ )
+
+
class ParserBase:
def __init__(self, kwds):
self.names = kwds.get("names")
@@ -2136,6 +2161,8 @@ def read(self, nrows=None):
# columns as list
alldata = [x[1] for x in data]
+ if self.usecols is None:
+ _check_unexpected_data(names, data, self.index_col)
data = {k: v for k, (i, v) in zip(names, data)}
@@ -2144,7 +2171,6 @@ def read(self, nrows=None):
# maybe create a mi on the columns
names = self._maybe_make_multi_index_columns(names, self.col_names)
-
return index, names, data
def _filter_usecols(self, names):
@@ -2495,6 +2521,10 @@ def read(self, rows=None):
content = content[1:]
alldata = self._rows_to_cols(content)
+
+ if self.usecols is None:
+ _check_unexpected_data(columns, alldata, self.index_col)
+
data = self._exclude_implicit_index(alldata)
columns = self._maybe_dedup_names(self.columns)
diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py
index a6a9e5c5610f2..f199267d0d462 100644
--- a/pandas/tests/io/parser/test_common.py
+++ b/pandas/tests/io/parser/test_common.py
@@ -15,7 +15,7 @@
import pytest
from pandas._libs.tslib import Timestamp
-from pandas.errors import DtypeWarning, EmptyDataError, ParserError
+from pandas.errors import DtypeWarning, EmptyDataError, ParserError, ParserWarning
import pandas.util._test_decorators as td
from pandas import DataFrame, Index, MultiIndex, Series, compat, concat, option_context
@@ -1071,8 +1071,8 @@ def test_trailing_delimiters(all_parsers):
4,5,6,
7,8,9,"""
parser = all_parsers
- result = parser.read_csv(StringIO(data), index_col=False)
-
+ with tm.assert_produces_warning(ParserWarning):
+ result = parser.read_csv(StringIO(data), index_col=False)
expected = DataFrame({"A": [1, 4, 7], "B": [2, 5, 8], "C": [3, 6, 9]})
tm.assert_frame_equal(result, expected)
@@ -2178,7 +2178,8 @@ def test_no_header_two_extra_columns(all_parsers):
ref = DataFrame([["foo", "bar", "baz"]], columns=column_names)
stream = StringIO("foo,bar,baz,bam,blah")
parser = all_parsers
- df = parser.read_csv(stream, header=None, names=column_names, index_col=False)
+ with tm.assert_produces_warning(ParserWarning):
+ df = parser.read_csv(stream, header=None, names=column_names, index_col=False)
tm.assert_frame_equal(df, ref)
@@ -2241,3 +2242,10 @@ def test_read_table_delim_whitespace_non_default_sep(all_parsers, delimiter):
with pytest.raises(ValueError, match=msg):
parser.read_table(f, delim_whitespace=True, delimiter=delimiter)
+
+
+def test_first_row_length(all_parsers):
+ stream = StringIO("col1,col2,col3\n0,1,2,X\n4,5,6,\n6,7,8")
+ parser = all_parsers
+ with tm.assert_produces_warning(ParserWarning):
+ parser.read_csv(stream, index_col=False)
| - [x] closes #33037
- [x] tests added and passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] warning when read rows have more columns than expected | https://api.github.com/repos/pandas-dev/pandas/pulls/33782 | 2020-04-25T02:08:16Z | 2021-01-01T21:54:02Z | null | 2021-01-01T21:54:02Z |
TST: more specific freq attrs | diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py
index 3e31c1acbe09d..9be741274c15a 100644
--- a/pandas/tests/arrays/categorical/test_constructors.py
+++ b/pandas/tests/arrays/categorical/test_constructors.py
@@ -331,6 +331,7 @@ def test_constructor_with_datetimelike(self, dtl):
def test_constructor_from_index_series_datetimetz(self):
idx = date_range("2015-01-01 10:00", freq="D", periods=3, tz="US/Eastern")
+ idx = idx._with_freq(None) # freq not preserved in result.categories
result = Categorical(idx)
tm.assert_index_equal(result.categories, idx)
@@ -339,6 +340,7 @@ def test_constructor_from_index_series_datetimetz(self):
def test_constructor_from_index_series_timedelta(self):
idx = timedelta_range("1 days", freq="D", periods=3)
+ idx = idx._with_freq(None) # freq not preserved in result.categories
result = Categorical(idx)
tm.assert_index_equal(result.categories, idx)
diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py
index 80739b9512953..580c0c7a8cab5 100644
--- a/pandas/tests/arrays/test_datetimelike.py
+++ b/pandas/tests/arrays/test_datetimelike.py
@@ -302,8 +302,14 @@ def test_round(self, tz_naive_fixture):
result = dti.round(freq="2T")
expected = dti - pd.Timedelta(minutes=1)
+ expected = expected._with_freq(None)
tm.assert_index_equal(result, expected)
+ dta = dti._data
+ result = dta.round(freq="2T")
+ expected = expected._data._with_freq(None)
+ tm.assert_datetime_array_equal(result, expected)
+
def test_array_interface(self, datetime_index):
arr = DatetimeArray(datetime_index)
diff --git a/pandas/tests/frame/methods/test_tz_convert.py b/pandas/tests/frame/methods/test_tz_convert.py
index ea8c4b88538d4..d2ab7a386a92d 100644
--- a/pandas/tests/frame/methods/test_tz_convert.py
+++ b/pandas/tests/frame/methods/test_tz_convert.py
@@ -44,6 +44,12 @@ def test_tz_convert_and_localize(self, fn):
# GH7846
df2 = DataFrame(np.ones(5), MultiIndex.from_arrays([l0, l1]))
+ # freq is not preserved in MultiIndex construction
+ l1_expected = l1_expected._with_freq(None)
+ l0_expected = l0_expected._with_freq(None)
+ l1 = l1._with_freq(None)
+ l0 = l0._with_freq(None)
+
df3 = getattr(df2, fn)("US/Pacific", level=0)
assert not df3.index.levels[0].equals(l0)
tm.assert_index_equal(df3.index.levels[0], l0_expected)
diff --git a/pandas/tests/frame/test_axis_select_reindex.py b/pandas/tests/frame/test_axis_select_reindex.py
index f61512b1a62d9..b68e20bee63fc 100644
--- a/pandas/tests/frame/test_axis_select_reindex.py
+++ b/pandas/tests/frame/test_axis_select_reindex.py
@@ -91,7 +91,8 @@ def test_reindex(self, float_frame):
# pass non-Index
newFrame = float_frame.reindex(list(datetime_series.index))
- tm.assert_index_equal(newFrame.index, datetime_series.index)
+ expected = datetime_series.index._with_freq(None)
+ tm.assert_index_equal(newFrame.index, expected)
# copy with no axes
result = float_frame.reindex()
diff --git a/pandas/tests/frame/test_to_csv.py b/pandas/tests/frame/test_to_csv.py
index a9d9d0ace8701..9c656dd69abe2 100644
--- a/pandas/tests/frame/test_to_csv.py
+++ b/pandas/tests/frame/test_to_csv.py
@@ -54,6 +54,8 @@ def test_to_csv_from_csv1(self, float_frame, datetime_frame):
float_frame.to_csv(path, index=False)
# test roundtrip
+ # freq does not roundtrip
+ datetime_frame.index = datetime_frame.index._with_freq(None)
datetime_frame.to_csv(path)
recons = self.read_csv(path)
tm.assert_frame_equal(datetime_frame, recons)
@@ -1157,6 +1159,7 @@ def test_to_csv_with_dst_transitions(self):
)
for i in [times, times + pd.Timedelta("10s")]:
+ i = i._with_freq(None) # freq is not preserved by read_csv
time_range = np.array(range(len(i)), dtype="int64")
df = DataFrame({"A": time_range}, index=i)
df.to_csv(path, index=True)
@@ -1170,6 +1173,8 @@ def test_to_csv_with_dst_transitions(self):
# GH11619
idx = pd.date_range("2015-01-01", "2015-12-31", freq="H", tz="Europe/Paris")
+ idx = idx._with_freq(None) # freq does not round-trip
+ idx._data._freq = None # otherwise there is trouble on unpickle
df = DataFrame({"values": 1, "idx": idx}, index=idx)
with tm.ensure_clean("csv_date_format_with_dst") as path:
df.to_csv(path, index=True)
diff --git a/pandas/tests/groupby/test_timegrouper.py b/pandas/tests/groupby/test_timegrouper.py
index 7cac13efb71f3..6d29ebd7ba795 100644
--- a/pandas/tests/groupby/test_timegrouper.py
+++ b/pandas/tests/groupby/test_timegrouper.py
@@ -8,7 +8,16 @@
import pytz
import pandas as pd
-from pandas import DataFrame, Index, MultiIndex, Series, Timestamp, date_range
+from pandas import (
+ DataFrame,
+ DatetimeIndex,
+ Index,
+ MultiIndex,
+ Series,
+ Timestamp,
+ date_range,
+ offsets,
+)
import pandas._testing as tm
from pandas.core.groupby.grouper import Grouper
from pandas.core.groupby.ops import BinGrouper
@@ -243,17 +252,20 @@ def test_timegrouper_with_reg_groups(self):
# single groupers
expected = DataFrame(
- {"Quantity": [31], "Date": [datetime(2013, 10, 31, 0, 0)]}
- ).set_index("Date")
+ [[31]],
+ columns=["Quantity"],
+ index=DatetimeIndex(
+ [datetime(2013, 10, 31, 0, 0)], freq=offsets.MonthEnd(), name="Date"
+ ),
+ )
result = df.groupby(pd.Grouper(freq="1M")).sum()
tm.assert_frame_equal(result, expected)
result = df.groupby([pd.Grouper(freq="1M")]).sum()
tm.assert_frame_equal(result, expected)
- expected = DataFrame(
- {"Quantity": [31], "Date": [datetime(2013, 11, 30, 0, 0)]}
- ).set_index("Date")
+ expected.index = expected.index.shift(1)
+ assert expected.index.freq == offsets.MonthEnd()
result = df.groupby(pd.Grouper(freq="1M", key="Date")).sum()
tm.assert_frame_equal(result, expected)
@@ -448,7 +460,7 @@ def test_groupby_groups_datetimeindex(self):
for date in dates:
result = grouped.get_group(date)
data = [[df.loc[date, "A"], df.loc[date, "B"]]]
- expected_index = pd.DatetimeIndex([date], name="date")
+ expected_index = pd.DatetimeIndex([date], name="date", freq="D")
expected = pd.DataFrame(data, columns=list("AB"), index=expected_index)
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/indexes/datetimes/test_astype.py b/pandas/tests/indexes/datetimes/test_astype.py
index 6ef831a9daaaf..3e7e76bba0dde 100644
--- a/pandas/tests/indexes/datetimes/test_astype.py
+++ b/pandas/tests/indexes/datetimes/test_astype.py
@@ -75,8 +75,10 @@ def test_astype_tzaware_to_tzaware(self):
def test_astype_tznaive_to_tzaware(self):
# GH 18951: tz-naive to tz-aware
idx = date_range("20170101", periods=4)
+ idx = idx._with_freq(None) # tz_localize does not preserve freq
result = idx.astype("datetime64[ns, US/Eastern]")
expected = date_range("20170101", periods=4, tz="US/Eastern")
+ expected = expected._with_freq(None)
tm.assert_index_equal(result, expected)
def test_astype_str_nat(self):
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index 1083f1c332705..7b42e9646918e 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -383,6 +383,7 @@ def test_constructor_dtypes_datetime(self, tz_naive_fixture, attr, klass):
@pytest.mark.parametrize("klass", [pd.Index, pd.TimedeltaIndex])
def test_constructor_dtypes_timedelta(self, attr, klass):
index = pd.timedelta_range("1 days", periods=5)
+ index = index._with_freq(None) # wont be preserved by constructors
dtype = index.dtype
values = getattr(index, attr)
diff --git a/pandas/tests/series/indexing/test_alter_index.py b/pandas/tests/series/indexing/test_alter_index.py
index 558f10d967df6..0415434f01fcf 100644
--- a/pandas/tests/series/indexing/test_alter_index.py
+++ b/pandas/tests/series/indexing/test_alter_index.py
@@ -75,6 +75,7 @@ def test_reindex_with_datetimes():
result = ts.reindex(list(ts.index[5:10]))
expected = ts[5:10]
+ expected.index = expected.index._with_freq(None)
tm.assert_series_equal(result, expected)
result = ts[list(ts.index[5:10])]
@@ -91,6 +92,7 @@ def test_reindex_corner(datetime_series):
# pass non-Index
reindexed = datetime_series.reindex(list(datetime_series.index))
+ datetime_series.index = datetime_series.index._with_freq(None)
tm.assert_series_equal(datetime_series, reindexed)
# bad fill method
diff --git a/pandas/tests/series/methods/test_sort_index.py b/pandas/tests/series/methods/test_sort_index.py
index d43b7efc779b0..39f872394d16b 100644
--- a/pandas/tests/series/methods/test_sort_index.py
+++ b/pandas/tests/series/methods/test_sort_index.py
@@ -13,6 +13,8 @@ def test_sort_index_name(self, datetime_series):
assert result.name == datetime_series.name
def test_sort_index(self, datetime_series):
+ datetime_series.index = datetime_series.index._with_freq(None)
+
rindex = list(datetime_series.index)
random.shuffle(rindex)
@@ -45,6 +47,7 @@ def test_sort_index(self, datetime_series):
random_order.sort_index(level=0, axis=1)
def test_sort_index_inplace(self, datetime_series):
+ datetime_series.index = datetime_series.index._with_freq(None)
# For GH#11402
rindex = list(datetime_series.index)
diff --git a/pandas/tests/series/test_datetime_values.py b/pandas/tests/series/test_datetime_values.py
index e903e850ec36c..0d7fd0529dc1f 100644
--- a/pandas/tests/series/test_datetime_values.py
+++ b/pandas/tests/series/test_datetime_values.py
@@ -233,6 +233,8 @@ def get_dir(s):
exp_values = pd.date_range(
"2015-01-01", "2016-01-01", freq="T", tz="UTC"
).tz_convert("America/Chicago")
+ # freq not preserved by tz_localize above
+ exp_values = exp_values._with_freq(None)
expected = Series(exp_values, name="xxx")
tm.assert_series_equal(s, expected)
diff --git a/pandas/tests/series/test_io.py b/pandas/tests/series/test_io.py
index 510c11a51ca38..708118e950686 100644
--- a/pandas/tests/series/test_io.py
+++ b/pandas/tests/series/test_io.py
@@ -25,6 +25,8 @@ def read_csv(self, path, **kwargs):
return out
def test_from_csv(self, datetime_series, string_series):
+ # freq doesnt round-trip
+ datetime_series.index = datetime_series.index._with_freq(None)
with tm.ensure_clean() as path:
datetime_series.to_csv(path, header=False)
| Getting ready to check matching freq in assert_index_equal | https://api.github.com/repos/pandas-dev/pandas/pulls/33781 | 2020-04-25T01:15:24Z | 2020-04-26T19:23:05Z | 2020-04-26T19:23:05Z | 2020-04-26T19:27:20Z |
BUG: freq not retained on apply_index | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index cd1cb0b64f74a..e8fdaf0ae5d49 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -462,6 +462,7 @@ Datetimelike
- Bug in :meth:`DatetimeIndex.to_period` not infering the frequency when called with no arguments (:issue:`33358`)
- Bug in :meth:`DatetimeIndex.tz_localize` incorrectly retaining ``freq`` in some cases where the original freq is no longer valid (:issue:`30511`)
- Bug in :meth:`DatetimeIndex.intersection` losing ``freq`` and timezone in some cases (:issue:`33604`)
+- Bug in :class:`DatetimeIndex` addition and subtraction with some types of :class:`DateOffset` objects incorrectly retaining an invalid ``freq`` attribute (:issue:`33779`)
Timedelta
^^^^^^^^^
diff --git a/pandas/tests/tseries/offsets/test_yqm_offsets.py b/pandas/tests/tseries/offsets/test_yqm_offsets.py
index 79a0e0f2c25eb..13cab9be46d37 100644
--- a/pandas/tests/tseries/offsets/test_yqm_offsets.py
+++ b/pandas/tests/tseries/offsets/test_yqm_offsets.py
@@ -64,6 +64,7 @@ def test_apply_index(cls, n):
ser = pd.Series(rng)
res = rng + offset
+ assert res.freq is None # not retained
res_v2 = offset.apply_index(rng)
assert (res == res_v2).all()
assert res[0] == rng[0] + offset
diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py
index 8ba10f56f163c..b419d5ccc10b4 100644
--- a/pandas/tseries/offsets.py
+++ b/pandas/tseries/offsets.py
@@ -1147,9 +1147,7 @@ def apply(self, other):
@apply_index_wraps
def apply_index(self, i):
shifted = liboffsets.shift_months(i.asi8, self.n, self._day_opt)
- # TODO: going through __new__ raises on call to _validate_frequency;
- # are we passing incorrect freq?
- return type(i)._simple_new(shifted, freq=i.freq, dtype=i.dtype)
+ return type(i)._simple_new(shifted, dtype=i.dtype)
class MonthEnd(MonthOffset):
@@ -1868,11 +1866,7 @@ def apply_index(self, dtindex):
shifted = liboffsets.shift_quarters(
dtindex.asi8, self.n, self.startingMonth, self._day_opt
)
- # TODO: going through __new__ raises on call to _validate_frequency;
- # are we passing incorrect freq?
- return type(dtindex)._simple_new(
- shifted, freq=dtindex.freq, dtype=dtindex.dtype
- )
+ return type(dtindex)._simple_new(shifted, dtype=dtindex.dtype)
class BQuarterEnd(QuarterOffset):
@@ -1954,11 +1948,7 @@ def apply_index(self, dtindex):
shifted = liboffsets.shift_quarters(
dtindex.asi8, self.n, self.month, self._day_opt, modby=12
)
- # TODO: going through __new__ raises on call to _validate_frequency;
- # are we passing incorrect freq?
- return type(dtindex)._simple_new(
- shifted, freq=dtindex.freq, dtype=dtindex.dtype
- )
+ return type(dtindex)._simple_new(shifted, dtype=dtindex.dtype)
def is_on_offset(self, dt: datetime) -> bool:
if self.normalize and not _is_normalized(dt):
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/33779 | 2020-04-24T20:41:39Z | 2020-04-24T23:23:26Z | 2020-04-24T23:23:26Z | 2020-04-24T23:28:13Z |
CLN: avoid getattr(obj, "values", obj) | diff --git a/pandas/_libs/hashtable_func_helper.pxi.in b/pandas/_libs/hashtable_func_helper.pxi.in
index 6e5509a5570e8..c63f368dfae43 100644
--- a/pandas/_libs/hashtable_func_helper.pxi.in
+++ b/pandas/_libs/hashtable_func_helper.pxi.in
@@ -125,7 +125,7 @@ cpdef value_count_{{dtype}}({{c_type}}[:] values, bint dropna):
{{if dtype == 'object'}}
def duplicated_{{dtype}}(ndarray[{{dtype}}] values, object keep='first'):
{{else}}
-def duplicated_{{dtype}}({{c_type}}[:] values, object keep='first'):
+def duplicated_{{dtype}}(const {{c_type}}[:] values, object keep='first'):
{{endif}}
cdef:
int ret = 0
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index e6967630b97ac..eca1733b61a52 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -49,6 +49,7 @@
ABCExtensionArray,
ABCIndex,
ABCIndexClass,
+ ABCMultiIndex,
ABCSeries,
)
from pandas.core.dtypes.missing import isna, na_value_for_dtype
@@ -89,6 +90,10 @@ def _ensure_data(values, dtype=None):
values : ndarray
pandas_dtype : str or dtype
"""
+ if not isinstance(values, ABCMultiIndex):
+ # extract_array would raise
+ values = extract_array(values, extract_numpy=True)
+
# we check some simple dtypes first
if is_object_dtype(dtype):
return ensure_object(np.asarray(values)), "object"
@@ -151,7 +156,6 @@ def _ensure_data(values, dtype=None):
elif is_categorical_dtype(values) and (
is_categorical_dtype(dtype) or dtype is None
):
- values = getattr(values, "values", values)
values = values.codes
dtype = "category"
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 220b70ff71b28..66faca29670cb 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -648,7 +648,6 @@ def fillna(self, value=None, method=None, limit=None):
)
raise TypeError(msg)
- value = getattr(value, "_values", value)
self._check_closed_matches(value, name="value")
left = self.left.fillna(value=value.left)
diff --git a/pandas/core/computation/expressions.py b/pandas/core/computation/expressions.py
index 7f93472c766d7..d9cd2c7be0093 100644
--- a/pandas/core/computation/expressions.py
+++ b/pandas/core/computation/expressions.py
@@ -102,8 +102,8 @@ def _evaluate_numexpr(op, op_str, a, b):
# we were originally called by a reversed op method
a, b = b, a
- a_value = getattr(a, "values", a)
- b_value = getattr(b, "values", b)
+ a_value = a
+ b_value = b
result = ne.evaluate(
f"a_value {op_str} b_value",
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index 3b14921528890..05400f63db972 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -37,6 +37,7 @@
from pandas.core.base import DataError, PandasObject, SelectionMixin, ShallowMixin
import pandas.core.common as com
+from pandas.core.construction import extract_array
from pandas.core.indexes.api import Index, ensure_index
from pandas.core.util.numba_ import NUMBA_FUNC_CACHE
from pandas.core.window.common import (
@@ -252,7 +253,7 @@ def __iter__(self):
def _prep_values(self, values: Optional[np.ndarray] = None) -> np.ndarray:
"""Convert input to numpy arrays for Cython routines"""
if values is None:
- values = getattr(self._selected_obj, "values", self._selected_obj)
+ values = extract_array(self._selected_obj, extract_numpy=True)
# GH #12373 : rolling functions error on float32 data
# make sure the data is coerced to float64
| xref #27167
@mroeschke can you pls double-check me on the change in window.rolling | https://api.github.com/repos/pandas-dev/pandas/pulls/33776 | 2020-04-24T18:45:06Z | 2020-04-25T20:48:05Z | 2020-04-25T20:48:05Z | 2020-04-25T21:03:58Z |
BUG: Changing way of applying numpy functions on Series | diff --git a/pandas/core/series.py b/pandas/core/series.py
index 74dcdaee327da..ce2fa6ceb6f50 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -3872,7 +3872,7 @@ def transform(self, func, axis=0, *args, **kwargs):
self._get_axis_number(axis)
return super().transform(func, *args, **kwargs)
- def apply(self, func, convert_dtype=True, args=(), **kwds):
+ def apply(self, func, convert_dtype=True, force_mapping=False, args=(), **kwds):
"""
Invoke function on values of Series.
@@ -3886,6 +3886,9 @@ def apply(self, func, convert_dtype=True, args=(), **kwds):
convert_dtype : bool, default True
Try to find better dtype for elementwise function results. If
False, leave as dtype=object.
+ force_mapping : bool, default False
+ If set to True, forces func to be called on each element separately.
+ Useful when using numpy functions.
args : tuple
Positional arguments passed to func after the series value.
**kwds
@@ -3992,9 +3995,8 @@ def f(x):
f = func
with np.errstate(all="ignore"):
- if isinstance(f, np.ufunc):
+ if not force_mapping and isinstance(f, np.ufunc):
return f(self)
-
# row-wise access
if is_extension_array_dtype(self.dtype) and hasattr(self._values, "map"):
# GH#23179 some EAs do not have `map`
diff --git a/pandas/tests/series/test_apply.py b/pandas/tests/series/test_apply.py
index 589f8933efa96..3ea35e748d526 100644
--- a/pandas/tests/series/test_apply.py
+++ b/pandas/tests/series/test_apply.py
@@ -813,3 +813,11 @@ def test_apply_to_timedelta(self):
b = Series(list_of_strings).apply(pd.to_timedelta) # noqa
# Can't compare until apply on a Series gives the correct dtype
# assert_series_equal(a, b)
+
+ def test_apply_to_numpy_func_with_force_mapping(self):
+ s = pd.Series([np.array([0.1, 0.2], dtype=float)])
+ expected = pd.Series(
+ [np.array([0.09983341664682815, 0.19866933079506122], dtype=float)]
+ )
+ result = s.apply(np.sin, force_mapping=True)
+ tm.assert_series_equal(result, expected)
| - [x] closes #33492
- [x] tests added and passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] numpy functions on Series are called like other functions | https://api.github.com/repos/pandas-dev/pandas/pulls/33775 | 2020-04-24T18:41:29Z | 2020-06-09T22:49:54Z | null | 2020-06-09T22:49:54Z |
REF: misplaced sort_index tests | diff --git a/pandas/tests/frame/methods/test_sort_index.py b/pandas/tests/frame/methods/test_sort_index.py
index 2c25e1f3740a3..b8eb3494353a9 100644
--- a/pandas/tests/frame/methods/test_sort_index.py
+++ b/pandas/tests/frame/methods/test_sort_index.py
@@ -2,11 +2,156 @@
import pytest
import pandas as pd
-from pandas import CategoricalDtype, DataFrame, IntervalIndex, MultiIndex, Series
+from pandas import CategoricalDtype, DataFrame, Index, IntervalIndex, MultiIndex, Series
import pandas._testing as tm
class TestDataFrameSortIndex:
+ def test_sort_index_and_reconstruction_doc_example(self):
+ # doc example
+ df = DataFrame(
+ {"value": [1, 2, 3, 4]},
+ index=MultiIndex(
+ levels=[["a", "b"], ["bb", "aa"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]]
+ ),
+ )
+ assert df.index.is_lexsorted()
+ assert not df.index.is_monotonic
+
+ # sort it
+ expected = DataFrame(
+ {"value": [2, 1, 4, 3]},
+ index=MultiIndex(
+ levels=[["a", "b"], ["aa", "bb"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]]
+ ),
+ )
+ result = df.sort_index()
+ assert result.index.is_lexsorted()
+ assert result.index.is_monotonic
+
+ tm.assert_frame_equal(result, expected)
+
+ # reconstruct
+ result = df.sort_index().copy()
+ result.index = result.index._sort_levels_monotonic()
+ assert result.index.is_lexsorted()
+ assert result.index.is_monotonic
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_sort_index_non_existent_label_multiindex(self):
+ # GH#12261
+ df = DataFrame(0, columns=[], index=MultiIndex.from_product([[], []]))
+ df.loc["b", "2"] = 1
+ df.loc["a", "3"] = 1
+ result = df.sort_index().index.is_monotonic
+ assert result is True
+
+ def test_sort_index_reorder_on_ops(self):
+ # GH#15687
+ df = DataFrame(
+ np.random.randn(8, 2),
+ index=MultiIndex.from_product(
+ [["a", "b"], ["big", "small"], ["red", "blu"]],
+ names=["letter", "size", "color"],
+ ),
+ columns=["near", "far"],
+ )
+ df = df.sort_index()
+
+ def my_func(group):
+ group.index = ["newz", "newa"]
+ return group
+
+ result = df.groupby(level=["letter", "size"]).apply(my_func).sort_index()
+ expected = MultiIndex.from_product(
+ [["a", "b"], ["big", "small"], ["newa", "newz"]],
+ names=["letter", "size", None],
+ )
+
+ tm.assert_index_equal(result.index, expected)
+
+ def test_sort_index_nan_multiindex(self):
+ # GH#14784
+ # incorrect sorting w.r.t. nans
+ tuples = [[12, 13], [np.nan, np.nan], [np.nan, 3], [1, 2]]
+ mi = MultiIndex.from_tuples(tuples)
+
+ df = DataFrame(np.arange(16).reshape(4, 4), index=mi, columns=list("ABCD"))
+ s = Series(np.arange(4), index=mi)
+
+ df2 = DataFrame(
+ {
+ "date": pd.DatetimeIndex(
+ [
+ "20121002",
+ "20121007",
+ "20130130",
+ "20130202",
+ "20130305",
+ "20121002",
+ "20121207",
+ "20130130",
+ "20130202",
+ "20130305",
+ "20130202",
+ "20130305",
+ ]
+ ),
+ "user_id": [1, 1, 1, 1, 1, 3, 3, 3, 5, 5, 5, 5],
+ "whole_cost": [
+ 1790,
+ np.nan,
+ 280,
+ 259,
+ np.nan,
+ 623,
+ 90,
+ 312,
+ np.nan,
+ 301,
+ 359,
+ 801,
+ ],
+ "cost": [12, 15, 10, 24, 39, 1, 0, np.nan, 45, 34, 1, 12],
+ }
+ ).set_index(["date", "user_id"])
+
+ # sorting frame, default nan position is last
+ result = df.sort_index()
+ expected = df.iloc[[3, 0, 2, 1], :]
+ tm.assert_frame_equal(result, expected)
+
+ # sorting frame, nan position last
+ result = df.sort_index(na_position="last")
+ expected = df.iloc[[3, 0, 2, 1], :]
+ tm.assert_frame_equal(result, expected)
+
+ # sorting frame, nan position first
+ result = df.sort_index(na_position="first")
+ expected = df.iloc[[1, 2, 3, 0], :]
+ tm.assert_frame_equal(result, expected)
+
+ # sorting frame with removed rows
+ result = df2.dropna().sort_index()
+ expected = df2.sort_index().dropna()
+ tm.assert_frame_equal(result, expected)
+
+ # sorting series, default nan position is last
+ result = s.sort_index()
+ expected = s.iloc[[3, 0, 2, 1]]
+ tm.assert_series_equal(result, expected)
+
+ # sorting series, nan position last
+ result = s.sort_index(na_position="last")
+ expected = s.iloc[[3, 0, 2, 1]]
+ tm.assert_series_equal(result, expected)
+
+ # sorting series, nan position first
+ result = s.sort_index(na_position="first")
+ expected = s.iloc[[1, 2, 3, 0]]
+ tm.assert_series_equal(result, expected)
+
def test_sort_index_nan(self):
# GH#3917
@@ -318,3 +463,196 @@ def test_sort_index_ignore_index_multi_index(
tm.assert_frame_equal(result_df, expected_df)
tm.assert_frame_equal(df, DataFrame(original_dict, index=mi))
+
+ def test_sort_index_categorical_multiindex(self):
+ # GH#15058
+ df = DataFrame(
+ {
+ "a": range(6),
+ "l1": pd.Categorical(
+ ["a", "a", "b", "b", "c", "c"],
+ categories=["c", "a", "b"],
+ ordered=True,
+ ),
+ "l2": [0, 1, 0, 1, 0, 1],
+ }
+ )
+ result = df.set_index(["l1", "l2"]).sort_index()
+ expected = DataFrame(
+ [4, 5, 0, 1, 2, 3],
+ columns=["a"],
+ index=MultiIndex(
+ levels=[
+ pd.CategoricalIndex(
+ ["c", "a", "b"],
+ categories=["c", "a", "b"],
+ ordered=True,
+ name="l1",
+ dtype="category",
+ ),
+ [0, 1],
+ ],
+ codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]],
+ names=["l1", "l2"],
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_sort_index_and_reconstruction(self):
+
+ # GH#15622
+ # lexsortedness should be identical
+ # across MultiIndex construction methods
+
+ df = DataFrame([[1, 1], [2, 2]], index=list("ab"))
+ expected = DataFrame(
+ [[1, 1], [2, 2], [1, 1], [2, 2]],
+ index=MultiIndex.from_tuples(
+ [(0.5, "a"), (0.5, "b"), (0.8, "a"), (0.8, "b")]
+ ),
+ )
+ assert expected.index.is_lexsorted()
+
+ result = DataFrame(
+ [[1, 1], [2, 2], [1, 1], [2, 2]],
+ index=MultiIndex.from_product([[0.5, 0.8], list("ab")]),
+ )
+ result = result.sort_index()
+ assert result.index.is_lexsorted()
+ assert result.index.is_monotonic
+
+ tm.assert_frame_equal(result, expected)
+
+ result = DataFrame(
+ [[1, 1], [2, 2], [1, 1], [2, 2]],
+ index=MultiIndex(
+ levels=[[0.5, 0.8], ["a", "b"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]]
+ ),
+ )
+ result = result.sort_index()
+ assert result.index.is_lexsorted()
+
+ tm.assert_frame_equal(result, expected)
+
+ concatted = pd.concat([df, df], keys=[0.8, 0.5])
+ result = concatted.sort_index()
+
+ assert result.index.is_lexsorted()
+ assert result.index.is_monotonic
+
+ tm.assert_frame_equal(result, expected)
+
+ # GH#14015
+ df = DataFrame(
+ [[1, 2], [6, 7]],
+ columns=MultiIndex.from_tuples(
+ [(0, "20160811 12:00:00"), (0, "20160809 12:00:00")],
+ names=["l1", "Date"],
+ ),
+ )
+
+ df.columns.set_levels(
+ pd.to_datetime(df.columns.levels[1]), level=1, inplace=True
+ )
+ assert not df.columns.is_lexsorted()
+ assert not df.columns.is_monotonic
+ result = df.sort_index(axis=1)
+ assert result.columns.is_lexsorted()
+ assert result.columns.is_monotonic
+ result = df.sort_index(axis=1, level=1)
+ assert result.columns.is_lexsorted()
+ assert result.columns.is_monotonic
+
+ # TODO: better name, de-duplicate with test_sort_index_level above
+ def test_sort_index_level2(self):
+ mi = MultiIndex(
+ levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]],
+ codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
+ names=["first", "second"],
+ )
+ frame = DataFrame(
+ np.random.randn(10, 3),
+ index=mi,
+ columns=Index(["A", "B", "C"], name="exp"),
+ )
+
+ df = frame.copy()
+ df.index = np.arange(len(df))
+
+ # axis=1
+
+ # series
+ a_sorted = frame["A"].sort_index(level=0)
+
+ # preserve names
+ assert a_sorted.index.names == frame.index.names
+
+ # inplace
+ rs = frame.copy()
+ rs.sort_index(level=0, inplace=True)
+ tm.assert_frame_equal(rs, frame.sort_index(level=0))
+
+ def test_sort_index_level_large_cardinality(self):
+
+ # GH#2684 (int64)
+ index = MultiIndex.from_arrays([np.arange(4000)] * 3)
+ df = DataFrame(np.random.randn(4000), index=index, dtype=np.int64)
+
+ # it works!
+ result = df.sort_index(level=0)
+ assert result.index.lexsort_depth == 3
+
+ # GH#2684 (int32)
+ index = MultiIndex.from_arrays([np.arange(4000)] * 3)
+ df = DataFrame(np.random.randn(4000), index=index, dtype=np.int32)
+
+ # it works!
+ result = df.sort_index(level=0)
+ assert (result.dtypes.values == df.dtypes.values).all()
+ assert result.index.lexsort_depth == 3
+
+ def test_sort_index_level_by_name(self):
+ mi = MultiIndex(
+ levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]],
+ codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
+ names=["first", "second"],
+ )
+ frame = DataFrame(
+ np.random.randn(10, 3),
+ index=mi,
+ columns=Index(["A", "B", "C"], name="exp"),
+ )
+
+ frame.index.names = ["first", "second"]
+ result = frame.sort_index(level="second")
+ expected = frame.sort_index(level=1)
+ tm.assert_frame_equal(result, expected)
+
+ def test_sort_index_level_mixed(self):
+ mi = MultiIndex(
+ levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]],
+ codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]],
+ names=["first", "second"],
+ )
+ frame = DataFrame(
+ np.random.randn(10, 3),
+ index=mi,
+ columns=Index(["A", "B", "C"], name="exp"),
+ )
+
+ sorted_before = frame.sort_index(level=1)
+
+ df = frame.copy()
+ df["foo"] = "bar"
+ sorted_after = df.sort_index(level=1)
+ tm.assert_frame_equal(sorted_before, sorted_after.drop(["foo"], axis=1))
+
+ dft = frame.T
+ sorted_before = dft.sort_index(level=1, axis=1)
+ dft["foo", "three"] = "bar"
+
+ sorted_after = dft.sort_index(level=1, axis=1)
+ tm.assert_frame_equal(
+ sorted_before.drop([("foo", "three")], axis=1),
+ sorted_after.drop([("foo", "three")], axis=1),
+ )
diff --git a/pandas/tests/series/methods/test_sort_index.py b/pandas/tests/series/methods/test_sort_index.py
index 2d4fdfd5a3950..18a3322ce94d8 100644
--- a/pandas/tests/series/methods/test_sort_index.py
+++ b/pandas/tests/series/methods/test_sort_index.py
@@ -170,3 +170,26 @@ def test_sort_index_ignore_index(
tm.assert_series_equal(result_ser, expected)
tm.assert_series_equal(ser, Series(original_list))
+
+ def test_sort_index_ascending_list(self):
+ # GH#16934
+
+ # Set up a Series with a three level MultiIndex
+ arrays = [
+ ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
+ ["one", "two", "one", "two", "one", "two", "one", "two"],
+ [4, 3, 2, 1, 4, 3, 2, 1],
+ ]
+ tuples = zip(*arrays)
+ mi = MultiIndex.from_tuples(tuples, names=["first", "second", "third"])
+ ser = Series(range(8), index=mi)
+
+ # Sort with boolean ascending
+ result = ser.sort_index(level=["third", "first"], ascending=False)
+ expected = ser.iloc[[4, 0, 5, 1, 6, 2, 7, 3]]
+ tm.assert_series_equal(result, expected)
+
+ # Sort with list of boolean ascending
+ result = ser.sort_index(level=["third", "first"], ascending=[False, True])
+ expected = ser.iloc[[0, 4, 1, 5, 2, 6, 3, 7]]
+ tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py
index dd0bac683c35c..884c169cdeed6 100644
--- a/pandas/tests/test_multilevel.py
+++ b/pandas/tests/test_multilevel.py
@@ -1802,229 +1802,6 @@ def test_sorting_repr_8017(self):
result = result.sort_index(axis=1)
tm.assert_frame_equal(result, expected)
- def test_sort_index_level(self):
- df = self.frame.copy()
- df.index = np.arange(len(df))
-
- # axis=1
-
- # series
- a_sorted = self.frame["A"].sort_index(level=0)
-
- # preserve names
- assert a_sorted.index.names == self.frame.index.names
-
- # inplace
- rs = self.frame.copy()
- rs.sort_index(level=0, inplace=True)
- tm.assert_frame_equal(rs, self.frame.sort_index(level=0))
-
- def test_sort_index_level_large_cardinality(self):
-
- # #2684 (int64)
- index = MultiIndex.from_arrays([np.arange(4000)] * 3)
- df = DataFrame(np.random.randn(4000), index=index, dtype=np.int64)
-
- # it works!
- result = df.sort_index(level=0)
- assert result.index.lexsort_depth == 3
-
- # #2684 (int32)
- index = MultiIndex.from_arrays([np.arange(4000)] * 3)
- df = DataFrame(np.random.randn(4000), index=index, dtype=np.int32)
-
- # it works!
- result = df.sort_index(level=0)
- assert (result.dtypes.values == df.dtypes.values).all()
- assert result.index.lexsort_depth == 3
-
- def test_sort_index_level_by_name(self):
- self.frame.index.names = ["first", "second"]
- result = self.frame.sort_index(level="second")
- expected = self.frame.sort_index(level=1)
- tm.assert_frame_equal(result, expected)
-
- def test_sort_index_level_mixed(self):
- sorted_before = self.frame.sort_index(level=1)
-
- df = self.frame.copy()
- df["foo"] = "bar"
- sorted_after = df.sort_index(level=1)
- tm.assert_frame_equal(sorted_before, sorted_after.drop(["foo"], axis=1))
-
- dft = self.frame.T
- sorted_before = dft.sort_index(level=1, axis=1)
- dft["foo", "three"] = "bar"
-
- sorted_after = dft.sort_index(level=1, axis=1)
- tm.assert_frame_equal(
- sorted_before.drop([("foo", "three")], axis=1),
- sorted_after.drop([("foo", "three")], axis=1),
- )
-
- def test_sort_index_categorical_multiindex(self):
- # GH 15058
- df = DataFrame(
- {
- "a": range(6),
- "l1": pd.Categorical(
- ["a", "a", "b", "b", "c", "c"],
- categories=["c", "a", "b"],
- ordered=True,
- ),
- "l2": [0, 1, 0, 1, 0, 1],
- }
- )
- result = df.set_index(["l1", "l2"]).sort_index()
- expected = DataFrame(
- [4, 5, 0, 1, 2, 3],
- columns=["a"],
- index=MultiIndex(
- levels=[
- pd.CategoricalIndex(
- ["c", "a", "b"],
- categories=["c", "a", "b"],
- ordered=True,
- name="l1",
- dtype="category",
- ),
- [0, 1],
- ],
- codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]],
- names=["l1", "l2"],
- ),
- )
- tm.assert_frame_equal(result, expected)
-
- def test_sort_index_and_reconstruction(self):
-
- # 15622
- # lexsortedness should be identical
- # across MultiIndex construction methods
-
- df = DataFrame([[1, 1], [2, 2]], index=list("ab"))
- expected = DataFrame(
- [[1, 1], [2, 2], [1, 1], [2, 2]],
- index=MultiIndex.from_tuples(
- [(0.5, "a"), (0.5, "b"), (0.8, "a"), (0.8, "b")]
- ),
- )
- assert expected.index.is_lexsorted()
-
- result = DataFrame(
- [[1, 1], [2, 2], [1, 1], [2, 2]],
- index=MultiIndex.from_product([[0.5, 0.8], list("ab")]),
- )
- result = result.sort_index()
- assert result.index.is_lexsorted()
- assert result.index.is_monotonic
-
- tm.assert_frame_equal(result, expected)
-
- result = DataFrame(
- [[1, 1], [2, 2], [1, 1], [2, 2]],
- index=MultiIndex(
- levels=[[0.5, 0.8], ["a", "b"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]]
- ),
- )
- result = result.sort_index()
- assert result.index.is_lexsorted()
-
- tm.assert_frame_equal(result, expected)
-
- concatted = pd.concat([df, df], keys=[0.8, 0.5])
- result = concatted.sort_index()
-
- assert result.index.is_lexsorted()
- assert result.index.is_monotonic
-
- tm.assert_frame_equal(result, expected)
-
- # 14015
- df = DataFrame(
- [[1, 2], [6, 7]],
- columns=MultiIndex.from_tuples(
- [(0, "20160811 12:00:00"), (0, "20160809 12:00:00")],
- names=["l1", "Date"],
- ),
- )
-
- df.columns.set_levels(
- pd.to_datetime(df.columns.levels[1]), level=1, inplace=True
- )
- assert not df.columns.is_lexsorted()
- assert not df.columns.is_monotonic
- result = df.sort_index(axis=1)
- assert result.columns.is_lexsorted()
- assert result.columns.is_monotonic
- result = df.sort_index(axis=1, level=1)
- assert result.columns.is_lexsorted()
- assert result.columns.is_monotonic
-
- def test_sort_index_and_reconstruction_doc_example(self):
- # doc example
- df = DataFrame(
- {"value": [1, 2, 3, 4]},
- index=MultiIndex(
- levels=[["a", "b"], ["bb", "aa"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]]
- ),
- )
- assert df.index.is_lexsorted()
- assert not df.index.is_monotonic
-
- # sort it
- expected = DataFrame(
- {"value": [2, 1, 4, 3]},
- index=MultiIndex(
- levels=[["a", "b"], ["aa", "bb"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]]
- ),
- )
- result = df.sort_index()
- assert result.index.is_lexsorted()
- assert result.index.is_monotonic
-
- tm.assert_frame_equal(result, expected)
-
- # reconstruct
- result = df.sort_index().copy()
- result.index = result.index._sort_levels_monotonic()
- assert result.index.is_lexsorted()
- assert result.index.is_monotonic
-
- tm.assert_frame_equal(result, expected)
-
- def test_sort_index_non_existent_label_multiindex(self):
- # GH 12261
- df = DataFrame(0, columns=[], index=pd.MultiIndex.from_product([[], []]))
- df.loc["b", "2"] = 1
- df.loc["a", "3"] = 1
- result = df.sort_index().index.is_monotonic
- assert result is True
-
- def test_sort_index_reorder_on_ops(self):
- # 15687
- df = DataFrame(
- np.random.randn(8, 2),
- index=MultiIndex.from_product(
- [["a", "b"], ["big", "small"], ["red", "blu"]],
- names=["letter", "size", "color"],
- ),
- columns=["near", "far"],
- )
- df = df.sort_index()
-
- def my_func(group):
- group.index = ["newz", "newa"]
- return group
-
- result = df.groupby(level=["letter", "size"]).apply(my_func).sort_index()
- expected = MultiIndex.from_product(
- [["a", "b"], ["big", "small"], ["newa", "newz"]],
- names=["letter", "size", None],
- )
-
- tm.assert_index_equal(result.index, expected)
-
def test_sort_non_lexsorted(self):
# degenerate case where we sort but don't
# have a satisfying result :<
@@ -2051,110 +1828,6 @@ def test_sort_non_lexsorted(self):
result = sorted.loc[pd.IndexSlice["B":"C", "a":"c"], :]
tm.assert_frame_equal(result, expected)
- def test_sort_index_nan(self):
- # GH 14784
- # incorrect sorting w.r.t. nans
- tuples = [[12, 13], [np.nan, np.nan], [np.nan, 3], [1, 2]]
- mi = MultiIndex.from_tuples(tuples)
-
- df = DataFrame(np.arange(16).reshape(4, 4), index=mi, columns=list("ABCD"))
- s = Series(np.arange(4), index=mi)
-
- df2 = DataFrame(
- {
- "date": pd.to_datetime(
- [
- "20121002",
- "20121007",
- "20130130",
- "20130202",
- "20130305",
- "20121002",
- "20121207",
- "20130130",
- "20130202",
- "20130305",
- "20130202",
- "20130305",
- ]
- ),
- "user_id": [1, 1, 1, 1, 1, 3, 3, 3, 5, 5, 5, 5],
- "whole_cost": [
- 1790,
- np.nan,
- 280,
- 259,
- np.nan,
- 623,
- 90,
- 312,
- np.nan,
- 301,
- 359,
- 801,
- ],
- "cost": [12, 15, 10, 24, 39, 1, 0, np.nan, 45, 34, 1, 12],
- }
- ).set_index(["date", "user_id"])
-
- # sorting frame, default nan position is last
- result = df.sort_index()
- expected = df.iloc[[3, 0, 2, 1], :]
- tm.assert_frame_equal(result, expected)
-
- # sorting frame, nan position last
- result = df.sort_index(na_position="last")
- expected = df.iloc[[3, 0, 2, 1], :]
- tm.assert_frame_equal(result, expected)
-
- # sorting frame, nan position first
- result = df.sort_index(na_position="first")
- expected = df.iloc[[1, 2, 3, 0], :]
- tm.assert_frame_equal(result, expected)
-
- # sorting frame with removed rows
- result = df2.dropna().sort_index()
- expected = df2.sort_index().dropna()
- tm.assert_frame_equal(result, expected)
-
- # sorting series, default nan position is last
- result = s.sort_index()
- expected = s.iloc[[3, 0, 2, 1]]
- tm.assert_series_equal(result, expected)
-
- # sorting series, nan position last
- result = s.sort_index(na_position="last")
- expected = s.iloc[[3, 0, 2, 1]]
- tm.assert_series_equal(result, expected)
-
- # sorting series, nan position first
- result = s.sort_index(na_position="first")
- expected = s.iloc[[1, 2, 3, 0]]
- tm.assert_series_equal(result, expected)
-
- def test_sort_ascending_list(self):
- # GH: 16934
-
- # Set up a Series with a three level MultiIndex
- arrays = [
- ["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"],
- ["one", "two", "one", "two", "one", "two", "one", "two"],
- [4, 3, 2, 1, 4, 3, 2, 1],
- ]
- tuples = zip(*arrays)
- mi = MultiIndex.from_tuples(tuples, names=["first", "second", "third"])
- s = Series(range(8), index=mi)
-
- # Sort with boolean ascending
- result = s.sort_index(level=["third", "first"], ascending=False)
- expected = s.iloc[[4, 0, 5, 1, 6, 2, 7, 3]]
- tm.assert_series_equal(result, expected)
-
- # Sort with list of boolean ascending
- result = s.sort_index(level=["third", "first"], ascending=[False, True])
- expected = s.iloc[[0, 4, 1, 5, 2, 6, 3, 7]]
- tm.assert_series_equal(result, expected)
-
@pytest.mark.parametrize(
"keys, expected",
[
| https://api.github.com/repos/pandas-dev/pandas/pulls/33774 | 2020-04-24T18:18:03Z | 2020-04-24T21:33:30Z | 2020-04-24T21:33:30Z | 2020-04-24T22:19:20Z | |
TST: more accurate freq attr in `expected`s | diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py
index a8e9ad9ff7cc9..79fcb5e9478c3 100644
--- a/pandas/tests/arithmetic/test_datetime64.py
+++ b/pandas/tests/arithmetic/test_datetime64.py
@@ -2052,6 +2052,7 @@ def test_dti_add_tdi(self, tz_naive_fixture):
dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
tdi = pd.timedelta_range("0 days", periods=10)
expected = pd.date_range("2017-01-01", periods=10, tz=tz)
+ expected._set_freq(None)
# add with TimdeltaIndex
result = dti + tdi
@@ -2073,6 +2074,7 @@ def test_dti_iadd_tdi(self, tz_naive_fixture):
dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
tdi = pd.timedelta_range("0 days", periods=10)
expected = pd.date_range("2017-01-01", periods=10, tz=tz)
+ expected._set_freq(None)
# iadd with TimdeltaIndex
result = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
@@ -2098,6 +2100,7 @@ def test_dti_sub_tdi(self, tz_naive_fixture):
dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
tdi = pd.timedelta_range("0 days", periods=10)
expected = pd.date_range("2017-01-01", periods=10, tz=tz, freq="-1D")
+ expected = expected._with_freq(None)
# sub with TimedeltaIndex
result = dti - tdi
@@ -2121,6 +2124,7 @@ def test_dti_isub_tdi(self, tz_naive_fixture):
dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
tdi = pd.timedelta_range("0 days", periods=10)
expected = pd.date_range("2017-01-01", periods=10, tz=tz, freq="-1D")
+ expected = expected._with_freq(None)
# isub with TimedeltaIndex
result = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py
index 202e30287881f..0675ba874846b 100644
--- a/pandas/tests/arithmetic/test_numeric.py
+++ b/pandas/tests/arithmetic/test_numeric.py
@@ -165,7 +165,7 @@ def test_numeric_arr_mul_tdscalar(self, scalar_td, numeric_idx, box):
# GH#19333
index = numeric_idx
- expected = pd.timedelta_range("0 days", "4 days")
+ expected = pd.TimedeltaIndex([pd.Timedelta(days=n) for n in range(5)])
index = tm.box_expected(index, box)
expected = tm.box_expected(expected, box)
@@ -974,7 +974,7 @@ def check(series, other):
tm.assert_almost_equal(np.asarray(result), expected)
assert result.name == series.name
- tm.assert_index_equal(result.index, series.index)
+ tm.assert_index_equal(result.index, series.index._with_freq(None))
tser = tm.makeTimeSeries().rename("ts")
check(tser, tser * 2)
diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py
index 8387e4d708662..3ffdc87ff84c8 100644
--- a/pandas/tests/arithmetic/test_timedelta64.py
+++ b/pandas/tests/arithmetic/test_timedelta64.py
@@ -403,9 +403,7 @@ def _check(result, expected):
_check(result, expected)
result = dti_tz - td
- expected = DatetimeIndex(
- ["20121231", "20130101", "20130102"], tz="US/Eastern", freq="D"
- )
+ expected = DatetimeIndex(["20121231", "20130101", "20130102"], tz="US/Eastern")
tm.assert_index_equal(result, expected)
def test_dti_tdi_numeric_ops(self):
@@ -515,7 +513,13 @@ def test_timedelta(self, freq):
result2 = DatetimeIndex(s - np.timedelta64(100000000))
result3 = rng - np.timedelta64(100000000)
result4 = DatetimeIndex(s - pd.offsets.Hour(1))
+
+ assert result1.freq == rng.freq
+ result1 = result1._with_freq(None)
tm.assert_index_equal(result1, result4)
+
+ assert result3.freq == rng.freq
+ result3 = result3._with_freq(None)
tm.assert_index_equal(result2, result3)
def test_tda_add_sub_index(self):
diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
index c0e1eeb8f4eec..957ca138498d9 100644
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -266,6 +266,8 @@ def test_ensure_copied_data(self, indices):
result = index_type(indices.values, copy=True, **init_kwargs)
if is_datetime64tz_dtype(indices.dtype):
result = result.tz_localize("UTC").tz_convert(indices.tz)
+ if isinstance(indices, (DatetimeIndex, TimedeltaIndex)):
+ indices._set_freq(None)
tm.assert_index_equal(indices, result)
diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py
index e109c7a4f1c8d..08706dce7e1e0 100644
--- a/pandas/tests/indexes/datetimes/test_datetime.py
+++ b/pandas/tests/indexes/datetimes/test_datetime.py
@@ -368,7 +368,8 @@ def test_factorize_tz(self, tz_naive_fixture):
for obj in [idx, pd.Series(idx)]:
arr, res = obj.factorize()
tm.assert_numpy_array_equal(arr, exp_arr)
- tm.assert_index_equal(res, base)
+ expected = base._with_freq(None)
+ tm.assert_index_equal(res, expected)
def test_factorize_dst(self):
# GH 13750
diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py
index c55b0481c1041..f0fe5e9b293fc 100644
--- a/pandas/tests/indexes/datetimes/test_ops.py
+++ b/pandas/tests/indexes/datetimes/test_ops.py
@@ -134,11 +134,14 @@ def test_value_counts_unique(self, tz_naive_fixture):
exp_idx = pd.date_range("2011-01-01 18:00", freq="-1H", periods=10, tz=tz)
expected = Series(range(10, 0, -1), index=exp_idx, dtype="int64")
+ expected.index._set_freq(None)
for obj in [idx, Series(idx)]:
+
tm.assert_series_equal(obj.value_counts(), expected)
expected = pd.date_range("2011-01-01 09:00", freq="H", periods=10, tz=tz)
+ expected = expected._with_freq(None)
tm.assert_index_equal(idx.unique(), expected)
idx = DatetimeIndex(
@@ -274,7 +277,8 @@ def test_drop_duplicates_metadata(self, freq_sample):
idx_dup = idx.append(idx)
assert idx_dup.freq is None # freq is reset
result = idx_dup.drop_duplicates()
- tm.assert_index_equal(idx, result)
+ expected = idx._with_freq(None)
+ tm.assert_index_equal(result, expected)
assert result.freq is None
@pytest.mark.parametrize(
diff --git a/pandas/tests/indexes/datetimes/test_setops.py b/pandas/tests/indexes/datetimes/test_setops.py
index 7182d05b77be3..df6e2dac72f95 100644
--- a/pandas/tests/indexes/datetimes/test_setops.py
+++ b/pandas/tests/indexes/datetimes/test_setops.py
@@ -285,16 +285,17 @@ def test_intersection_empty(self, tz_aware_fixture, freq):
assert result.freq == rng.freq
# no overlap GH#33604
+ check_freq = freq != "T" # We don't preserve freq on non-anchored offsets
result = rng[:3].intersection(rng[-3:])
tm.assert_index_equal(result, rng[:0])
- if freq != "T":
+ if check_freq:
# We don't preserve freq on non-anchored offsets
assert result.freq == rng.freq
# swapped left and right
result = rng[-3:].intersection(rng[:3])
tm.assert_index_equal(result, rng[:0])
- if freq != "T":
+ if check_freq:
# We don't preserve freq on non-anchored offsets
assert result.freq == rng.freq
diff --git a/pandas/tests/indexes/datetimes/test_timezones.py b/pandas/tests/indexes/datetimes/test_timezones.py
index 8628ce7ade212..ea68e8759c123 100644
--- a/pandas/tests/indexes/datetimes/test_timezones.py
+++ b/pandas/tests/indexes/datetimes/test_timezones.py
@@ -271,6 +271,7 @@ def test_tz_convert_roundtrip(self, tz_aware_fixture):
tm.assert_index_equal(reset, expected)
assert reset.tzinfo is None
expected = converted.tz_convert("UTC").tz_localize(None)
+ expected = expected._with_freq("infer")
tm.assert_index_equal(reset, expected)
def test_dti_tz_convert_tzlocal(self):
@@ -352,8 +353,9 @@ def test_dti_tz_localize_ambiguous_infer(self, tz):
]
di = DatetimeIndex(times)
localized = di.tz_localize(tz, ambiguous="infer")
- tm.assert_index_equal(dr, localized)
- tm.assert_index_equal(dr, DatetimeIndex(times, tz=tz, ambiguous="infer"))
+ expected = dr._with_freq(None)
+ tm.assert_index_equal(expected, localized)
+ tm.assert_index_equal(expected, DatetimeIndex(times, tz=tz, ambiguous="infer"))
# When there is no dst transition, nothing special happens
dr = date_range(datetime(2011, 6, 1, 0), periods=10, freq=pd.offsets.Hour())
@@ -458,7 +460,8 @@ def test_dti_tz_localize_roundtrip(self, tz_aware_fixture):
localized.tz_localize(tz)
reset = localized.tz_localize(None)
assert reset.tzinfo is None
- tm.assert_index_equal(reset, idx)
+ expected = idx._with_freq(None)
+ tm.assert_index_equal(reset, expected)
def test_dti_tz_localize_naive(self):
rng = date_range("1/1/2011", periods=100, freq="H")
@@ -466,7 +469,7 @@ def test_dti_tz_localize_naive(self):
conv = rng.tz_localize("US/Pacific")
exp = date_range("1/1/2011", periods=100, freq="H", tz="US/Pacific")
- tm.assert_index_equal(conv, exp)
+ tm.assert_index_equal(conv, exp._with_freq(None))
def test_dti_tz_localize_tzlocal(self):
# GH#13583
@@ -526,8 +529,9 @@ def test_dti_tz_localize_ambiguous_flags(self, tz):
di = DatetimeIndex(times)
is_dst = [1, 1, 0, 0, 0]
localized = di.tz_localize(tz, ambiguous=is_dst)
- tm.assert_index_equal(dr, localized)
- tm.assert_index_equal(dr, DatetimeIndex(times, tz=tz, ambiguous=is_dst))
+ expected = dr._with_freq(None)
+ tm.assert_index_equal(expected, localized)
+ tm.assert_index_equal(expected, DatetimeIndex(times, tz=tz, ambiguous=is_dst))
localized = di.tz_localize(tz, ambiguous=np.array(is_dst))
tm.assert_index_equal(dr, localized)
@@ -703,9 +707,9 @@ def test_dti_tz_localize_nonexistent_shift_invalid(self, offset, tz_type):
def test_normalize_tz(self):
rng = date_range("1/1/2000 9:30", periods=10, freq="D", tz="US/Eastern")
- result = rng.normalize()
+ result = rng.normalize() # does not preserve freq
expected = date_range("1/1/2000", periods=10, freq="D", tz="US/Eastern")
- tm.assert_index_equal(result, expected)
+ tm.assert_index_equal(result, expected._with_freq(None))
assert result.is_normalized
assert not rng.is_normalized
@@ -720,9 +724,9 @@ def test_normalize_tz(self):
assert not rng.is_normalized
rng = date_range("1/1/2000 9:30", periods=10, freq="D", tz=tzlocal())
- result = rng.normalize()
+ result = rng.normalize() # does not preserve freq
expected = date_range("1/1/2000", periods=10, freq="D", tz=tzlocal())
- tm.assert_index_equal(result, expected)
+ tm.assert_index_equal(result, expected._with_freq(None))
assert result.is_normalized
assert not rng.is_normalized
@@ -746,6 +750,7 @@ def test_normalize_tz_local(self, timezone):
result = rng.normalize()
expected = date_range("1/1/2000", periods=10, freq="D", tz=tzlocal())
+ expected = expected._with_freq(None)
tm.assert_index_equal(result, expected)
assert result.is_normalized
@@ -777,10 +782,8 @@ def test_dti_constructor_with_fixed_tz(self):
@pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"])
def test_dti_convert_datetime_list(self, tzstr):
dr = date_range("2012-06-02", periods=10, tz=tzstr, name="foo")
- dr2 = DatetimeIndex(list(dr), name="foo")
+ dr2 = DatetimeIndex(list(dr), name="foo", freq="D")
tm.assert_index_equal(dr, dr2)
- assert dr.tz == dr2.tz
- assert dr2.name == "foo"
def test_dti_construction_univalent(self):
rng = date_range("03/12/2012 00:00", periods=10, freq="W-FRI", tz="US/Eastern")
@@ -803,6 +806,7 @@ def test_dti_tz_constructors(self, tzstr):
idx1 = to_datetime(arr).tz_localize(tzstr)
idx2 = pd.date_range(start="2005-11-10 08:00:00", freq="H", periods=2, tz=tzstr)
+ idx2 = idx2._with_freq(None) # the others all have freq=None
idx3 = DatetimeIndex(arr, tz=tzstr)
idx4 = DatetimeIndex(np.array(arr), tz=tzstr)
@@ -913,7 +917,7 @@ def test_date_range_localize(self):
rng3 = date_range("3/11/2012 03:00", periods=15, freq="H")
rng3 = rng3.tz_localize("US/Eastern")
- tm.assert_index_equal(rng, rng3)
+ tm.assert_index_equal(rng._with_freq(None), rng3)
# DST transition time
val = rng[0]
@@ -926,7 +930,9 @@ def test_date_range_localize(self):
# Right before the DST transition
rng = date_range("3/11/2012 00:00", periods=2, freq="H", tz="US/Eastern")
- rng2 = DatetimeIndex(["3/11/2012 00:00", "3/11/2012 01:00"], tz="US/Eastern")
+ rng2 = DatetimeIndex(
+ ["3/11/2012 00:00", "3/11/2012 01:00"], tz="US/Eastern", freq="H"
+ )
tm.assert_index_equal(rng, rng2)
exp = Timestamp("3/11/2012 00:00", tz="US/Eastern")
assert exp.hour == 0
diff --git a/pandas/tests/indexes/timedeltas/test_ops.py b/pandas/tests/indexes/timedeltas/test_ops.py
index aa1bf997fc66b..0e5abe2f5ccd1 100644
--- a/pandas/tests/indexes/timedeltas/test_ops.py
+++ b/pandas/tests/indexes/timedeltas/test_ops.py
@@ -144,7 +144,8 @@ def test_drop_duplicates_metadata(self, freq_sample):
idx_dup = idx.append(idx)
assert idx_dup.freq is None # freq is reset
result = idx_dup.drop_duplicates()
- tm.assert_index_equal(idx, result)
+ expected = idx._with_freq(None)
+ tm.assert_index_equal(expected, result)
assert result.freq is None
@pytest.mark.parametrize(
diff --git a/pandas/tests/indexing/test_datetime.py b/pandas/tests/indexing/test_datetime.py
index c8c2d1ed587cf..17ca23055f6e0 100644
--- a/pandas/tests/indexing/test_datetime.py
+++ b/pandas/tests/indexing/test_datetime.py
@@ -145,7 +145,11 @@ def test_indexing_with_datetimeindex_tz(self):
for sel in (index, list(index)):
# getitem
- tm.assert_series_equal(ser[sel], ser)
+ result = ser[sel]
+ expected = ser
+ if sel is not index:
+ expected.index = expected.index._with_freq(None)
+ tm.assert_series_equal(result, expected)
# setitem
result = ser.copy()
@@ -154,7 +158,8 @@ def test_indexing_with_datetimeindex_tz(self):
tm.assert_series_equal(result, expected)
# .loc getitem
- tm.assert_series_equal(ser.loc[sel], ser)
+ result = ser.loc[sel]
+ tm.assert_series_equal(result, ser)
# .loc setitem
result = ser.copy()
@@ -226,6 +231,7 @@ def test_series_partial_set_datetime(self):
result = ser.loc[[Timestamp("2011-01-01"), Timestamp("2011-01-02")]]
exp = Series([0.1, 0.2], index=idx, name="s")
+ exp.index = exp.index._with_freq(None)
tm.assert_series_equal(result, exp, check_index_type=True)
keys = [
diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py
index 2e691c6fd76d8..6c259db33cf7c 100644
--- a/pandas/tests/indexing/test_partial.py
+++ b/pandas/tests/indexing/test_partial.py
@@ -119,7 +119,7 @@ def test_partial_setting(self):
)
expected = pd.concat(
- [df_orig, DataFrame({"A": 7}, index=[dates[-1] + dates.freq])], sort=True
+ [df_orig, DataFrame({"A": 7}, index=dates[-1:] + dates.freq)], sort=True
)
df = df_orig.copy()
df.loc[dates[-1] + dates.freq, "A"] = 7
diff --git a/pandas/tests/series/methods/test_sort_index.py b/pandas/tests/series/methods/test_sort_index.py
index 2d4fdfd5a3950..47aa72e298685 100644
--- a/pandas/tests/series/methods/test_sort_index.py
+++ b/pandas/tests/series/methods/test_sort_index.py
@@ -55,16 +55,18 @@ def test_sort_index_inplace(self, datetime_series):
result = random_order.sort_index(ascending=False, inplace=True)
assert result is None
- tm.assert_series_equal(
- random_order, datetime_series.reindex(datetime_series.index[::-1])
- )
+ expected = datetime_series.reindex(datetime_series.index[::-1])
+ expected.index = expected.index._with_freq(None)
+ tm.assert_series_equal(random_order, expected)
# ascending
random_order = datetime_series.reindex(rindex)
result = random_order.sort_index(ascending=True, inplace=True)
assert result is None
- tm.assert_series_equal(random_order, datetime_series)
+ expected = datetime_series.copy()
+ expected.index = expected.index._with_freq(None)
+ tm.assert_series_equal(random_order, expected)
def test_sort_index_level(self):
mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list("ABC"))
diff --git a/pandas/tests/series/methods/test_to_dict.py b/pandas/tests/series/methods/test_to_dict.py
index 2fbf3e8d39cf3..47badb0a1bb52 100644
--- a/pandas/tests/series/methods/test_to_dict.py
+++ b/pandas/tests/series/methods/test_to_dict.py
@@ -12,9 +12,11 @@ class TestSeriesToDict:
)
def test_to_dict(self, mapping, datetime_series):
# GH#16122
- tm.assert_series_equal(
- Series(datetime_series.to_dict(mapping), name="ts"), datetime_series
- )
+ result = Series(datetime_series.to_dict(mapping), name="ts")
+ expected = datetime_series.copy()
+ expected.index = expected.index._with_freq(None)
+ tm.assert_series_equal(result, expected)
+
from_method = Series(datetime_series.to_dict(collections.Counter))
from_constructor = Series(collections.Counter(datetime_series.items()))
tm.assert_series_equal(from_method, from_constructor)
diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py
index dd0bac683c35c..f113d47ec7340 100644
--- a/pandas/tests/test_multilevel.py
+++ b/pandas/tests/test_multilevel.py
@@ -1505,6 +1505,7 @@ def test_set_index_datetime(self):
tz="US/Eastern",
)
idx3 = pd.date_range("2011-01-01 09:00", periods=6, tz="Asia/Tokyo")
+ idx3._set_freq(None)
df = df.set_index(idx1)
df = df.set_index(idx2, append=True)
| preparing to add a freq check to assert_index_equal | https://api.github.com/repos/pandas-dev/pandas/pulls/33773 | 2020-04-24T17:58:25Z | 2020-04-24T22:00:42Z | 2020-04-24T22:00:42Z | 2020-04-24T22:17:44Z |
BUG: DataFrame.truncate() handles decreasing order(#33756) | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 495dcc5700241..e67ec02737f57 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -9196,7 +9196,14 @@ def truncate(
raise ValueError(f"Truncate: {after} must be after {before}")
slicer = [slice(None, None)] * self._AXIS_LEN
- slicer[axis] = slice(before, after)
+
+ # GH33756
+ # Inverse before/after if ax is in decreasing order.
+ if ax.is_monotonic_increasing:
+ slicer[axis] = slice(before, after)
+ else:
+ slicer[axis] = slice(after, before)
+
result = self.loc[tuple(slicer)]
if isinstance(ax, MultiIndex):
diff --git a/pandas/tests/frame/methods/test_truncate.py b/pandas/tests/frame/methods/test_truncate.py
index ad86ee1266874..65d50d1940b16 100644
--- a/pandas/tests/frame/methods/test_truncate.py
+++ b/pandas/tests/frame/methods/test_truncate.py
@@ -87,3 +87,45 @@ def test_truncate_nonsortedindex(self):
msg = "truncate requires a sorted index"
with pytest.raises(ValueError, match=msg):
df.truncate(before=2, after=20, axis=1)
+
+ def test_truncate_descendingorderindex(self):
+ # GH#33756
+
+ df = pd.DataFrame({"A": ["a", "b", "c", "d", "e"]}, index=[9, 6, 5, 4, 1])
+
+ start = 4
+ end = 6
+
+ start_missing = 3
+ end_missing = 7
+
+ # neither specified
+ truncated = df.truncate()
+ tm.assert_frame_equal(truncated, df)
+
+ # start specified
+ expected = df[:4]
+
+ truncated = df.truncate(before=start)
+ tm.assert_frame_equal(truncated, expected)
+
+ truncated = df.truncate(before=start_missing)
+ tm.assert_frame_equal(truncated, expected)
+
+ # end specified
+ expected = df[1:]
+
+ truncated = df.truncate(after=end)
+ tm.assert_frame_equal(truncated, expected)
+
+ truncated = df.truncate(after=end_missing)
+ tm.assert_frame_equal(truncated, expected)
+
+ # both specified
+ expected = df[1:4]
+
+ truncated = df.truncate(before=start, after=end)
+ tm.assert_frame_equal(truncated, expected)
+
+ truncated = df.truncate(before=start_missing, after=end_missing)
+ tm.assert_frame_equal(truncated, expected)
| - [x] closes #33756
- [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/33772 | 2020-04-24T17:29:02Z | 2020-04-24T17:31:59Z | null | 2020-04-24T17:31:59Z |
[#33770] bug fix to prevent ExtensionArrays from crashing Series.__repr__() | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 823bfc75e4304..7b5f1fb03dd48 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -733,8 +733,8 @@ Sparse
ExtensionArray
^^^^^^^^^^^^^^
-- Fixed bug where :meth:`Series.value_counts` would raise on empty input of ``Int64`` dtype (:issue:`33317`)
--
+- Fixed bug where :meth:`Serires.value_counts` would raise on empty input of ``Int64`` dtype (:issue:`33317`)
+- Fixed bug that caused :meth:`Series.__repr__()` to crash for extension types whose elements are multidimensional arrays (:issue:`33770`).
Other
diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py
index 59542a8da535e..c7eb3eeedcadf 100644
--- a/pandas/io/formats/format.py
+++ b/pandas/io/formats/format.py
@@ -1228,7 +1228,11 @@ def _format(x):
vals = extract_array(self.values, extract_numpy=True)
- is_float_type = lib.map_infer(vals, is_float) & notna(vals)
+ is_float_type = (
+ lib.map_infer(vals, is_float)
+ # vals may have 2 or more dimensions
+ & np.all(notna(vals), axis=tuple(range(1, len(vals.shape))))
+ )
leading_space = self.leading_space
if leading_space is None:
leading_space = is_float_type.any()
diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py
index f3c3344992942..c1850826926d8 100644
--- a/pandas/tests/io/formats/test_format.py
+++ b/pandas/tests/io/formats/test_format.py
@@ -2810,6 +2810,63 @@ def test_to_string_multindex_header(self):
assert res == exp
+class TestGenericArrayFormatter:
+ def test_1d_array(self):
+ # GenericArrayFormatter is used on types for which there isn't a dedicated
+ # formatter. np.bool is one of those types.
+ obj = fmt.GenericArrayFormatter(np.array([True, False]))
+ res = obj.get_result()
+ assert len(res) == 2
+ # Results should be right-justified.
+ assert res[0] == " True"
+ assert res[1] == " False"
+
+ def test_2d_array(self):
+ obj = fmt.GenericArrayFormatter(np.array([[True, False], [False, True]]))
+ res = obj.get_result()
+ assert len(res) == 2
+ assert res[0] == " [True, False]"
+ assert res[1] == " [False, True]"
+
+ def test_3d_array(self):
+ obj = fmt.GenericArrayFormatter(
+ np.array([[[True, True], [False, False]], [[False, True], [True, False]]])
+ )
+ res = obj.get_result()
+ assert len(res) == 2
+ assert res[0] == " [[True, True], [False, False]]"
+ assert res[1] == " [[False, True], [True, False]]"
+
+ def test_2d_extension_type(self):
+ # GH 33770
+
+ # Define a stub extension type with just enough code to run Series.__repr__()
+ class DtypeStub(pd.api.extensions.ExtensionDtype):
+ @property
+ def type(self):
+ return np.ndarray
+
+ @property
+ def name(self):
+ return "DtypeStub"
+
+ class ExtTypeStub(pd.api.extensions.ExtensionArray):
+ def __len__(self):
+ return 2
+
+ def __getitem__(self, ix):
+ return [ix == 1, ix == 0]
+
+ @property
+ def dtype(self):
+ return DtypeStub()
+
+ series = pd.Series(ExtTypeStub())
+ res = repr(series) # This line crashed before #33770 was fixed.
+ expected = "0 [False True]\n" + "1 [ True False]\n" + "dtype: DtypeStub"
+ assert res == expected
+
+
def _three_digit_exp():
return f"{1.7e8:.4g}" == "1.7e+008"
| - [X] closes #33770
- [X] tests added / passed
- [X] passes `black pandas`
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [X] whatsnew entry
This pull request fixes a bug in `GenericArrayFormatter` that caused a crash when rendering arrays of arrays. This problem causes `Series.__repr__()` to fail with certain extension types; see #33770 for more information.
The root cause is this line:
``` python
1231 is_float_type = lib.map_infer(vals, is_float) & notna(vals)
```
The call to `notna()` here returns a 2D array if `vals` is a 2D array, while `lib.map_infer(vals, is_float)` returns a 1D array if `vals` is a 2D array.
In addition to fixing that line, this PR also adds tests for the issue. | https://api.github.com/repos/pandas-dev/pandas/pulls/33771 | 2020-04-24T17:23:45Z | 2020-05-01T20:36:04Z | 2020-05-01T20:36:03Z | 2020-05-01T20:36:04Z |
BUG: Adjust truncate for decreasing index | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index f1a219ad232de..e90030a6cffb1 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -565,6 +565,7 @@ Indexing
- Bug in :meth:`DatetimeIndex.insert` and :meth:`TimedeltaIndex.insert` causing index ``freq`` to be lost when setting an element into an empty :class:`Series` (:issue:33573`)
- Bug in :meth:`Series.__setitem__` with an :class:`IntervalIndex` and a list-like key of integers (:issue:`33473`)
- Bug in :meth:`Series.__getitem__` allowing missing labels with ``np.ndarray``, :class:`Index`, :class:`Series` indexers but not ``list``, these now all raise ``KeyError`` (:issue:`33646`)
+- Bug in :meth:`DataFrame.truncate` and :meth:`Series.truncate` where index was assumed to be monotone increasing (:issue:`33756`)
Missing
^^^^^^^
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index c761bd8cb465a..ed421718c400d 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -9196,6 +9196,9 @@ def truncate(
if before > after:
raise ValueError(f"Truncate: {after} must be after {before}")
+ if ax.is_monotonic_decreasing:
+ before, after = after, before
+
slicer = [slice(None, None)] * self._AXIS_LEN
slicer[axis] = slice(before, after)
result = self.loc[tuple(slicer)]
diff --git a/pandas/tests/frame/methods/test_truncate.py b/pandas/tests/frame/methods/test_truncate.py
index ad86ee1266874..768a5f22fb063 100644
--- a/pandas/tests/frame/methods/test_truncate.py
+++ b/pandas/tests/frame/methods/test_truncate.py
@@ -87,3 +87,20 @@ def test_truncate_nonsortedindex(self):
msg = "truncate requires a sorted index"
with pytest.raises(ValueError, match=msg):
df.truncate(before=2, after=20, axis=1)
+
+ @pytest.mark.parametrize(
+ "before, after, indices",
+ [(1, 2, [2, 1]), (None, 2, [2, 1, 0]), (1, None, [3, 2, 1])],
+ )
+ @pytest.mark.parametrize("klass", [pd.Int64Index, pd.DatetimeIndex])
+ def test_truncate_decreasing_index(self, before, after, indices, klass):
+ # https://github.com/pandas-dev/pandas/issues/33756
+ idx = klass([3, 2, 1, 0])
+ if klass is pd.DatetimeIndex:
+ before = pd.Timestamp(before) if before is not None else None
+ after = pd.Timestamp(after) if after is not None else None
+ indices = [pd.Timestamp(i) for i in indices]
+ values = pd.DataFrame(range(len(idx)), index=idx)
+ result = values.truncate(before=before, after=after)
+ expected = values.loc[indices]
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/series/methods/test_truncate.py b/pandas/tests/series/methods/test_truncate.py
index c97369b349f56..47947f0287494 100644
--- a/pandas/tests/series/methods/test_truncate.py
+++ b/pandas/tests/series/methods/test_truncate.py
@@ -80,6 +80,23 @@ def test_truncate_nonsortedindex(self):
with pytest.raises(ValueError, match=msg):
ts.sort_values(ascending=False).truncate(before="2011-11", after="2011-12")
+ @pytest.mark.parametrize(
+ "before, after, indices",
+ [(1, 2, [2, 1]), (None, 2, [2, 1, 0]), (1, None, [3, 2, 1])],
+ )
+ @pytest.mark.parametrize("klass", [pd.Int64Index, pd.DatetimeIndex])
+ def test_truncate_decreasing_index(self, before, after, indices, klass):
+ # https://github.com/pandas-dev/pandas/issues/33756
+ idx = klass([3, 2, 1, 0])
+ if klass is pd.DatetimeIndex:
+ before = pd.Timestamp(before) if before is not None else None
+ after = pd.Timestamp(after) if after is not None else None
+ indices = [pd.Timestamp(i) for i in indices]
+ values = pd.Series(range(len(idx)), index=idx)
+ result = values.truncate(before=before, after=after)
+ expected = values.loc[indices]
+ tm.assert_series_equal(result, expected)
+
def test_truncate_datetimeindex_tz(self):
# GH 9243
idx = date_range("4/1/2005", "4/30/2005", freq="D", tz="US/Pacific")
| - [x] closes #33756
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/33769 | 2020-04-24T17:08:07Z | 2020-04-26T21:04:16Z | 2020-04-26T21:04:16Z | 2020-04-26T21:47:37Z |
DOC: data_columns can take bool | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 495dcc5700241..ef058fd0aa074 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2359,7 +2359,7 @@ def to_hdf(
min_itemsize: Optional[Union[int, Dict[str, int]]] = None,
nan_rep=None,
dropna: Optional[bool_t] = None,
- data_columns: Optional[List[str]] = None,
+ data_columns: Optional[Union[bool_t, List[str]]] = None,
errors: str = "strict",
encoding: str = "UTF-8",
) -> None:
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 311d8d0d55341..5845202550326 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -230,7 +230,7 @@ def to_hdf(
min_itemsize: Optional[Union[int, Dict[str, int]]] = None,
nan_rep=None,
dropna: Optional[bool] = None,
- data_columns: Optional[List[str]] = None,
+ data_columns: Optional[Union[bool, List[str]]] = None,
errors: str = "strict",
encoding: str = "UTF-8",
):
| The ``data_columns`` argument of ``df.to_hdf`` can take ``True`` as an argument, meaning "all columns", yet the type hint is ``Optional[List[str]]``, triggering warnings in e.g. pyCharm.
- [ ] 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/33768 | 2020-04-24T16:37:52Z | 2020-04-24T18:08:24Z | 2020-04-24T18:08:24Z | 2022-04-30T19:47:45Z |
BUG: Fix missing tick labels on twinned axes | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index 18940b574b517..9a597c134a10a 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -331,6 +331,7 @@ Plotting
- Bug in :meth:`DataFrame.plot` was rotating xticklabels when ``subplots=True``, even if the x-axis wasn't an irregular time series (:issue:`29460`)
- Bug in :meth:`DataFrame.plot` where a marker letter in the ``style`` keyword sometimes causes a ``ValueError`` (:issue:`21003`)
+- Twinned axes were losing their tick labels which should only happen to all but the last row or column of 'externally' shared axes (:issue:`33819`)
Groupby/resample/rolling
^^^^^^^^^^^^^^^^^^^^^^^^
diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py
index c5b44f37150bb..aed0c360fc7ce 100644
--- a/pandas/plotting/_matplotlib/tools.py
+++ b/pandas/plotting/_matplotlib/tools.py
@@ -297,6 +297,56 @@ def _remove_labels_from_axis(axis: "Axis"):
axis.get_label().set_visible(False)
+def _has_externally_shared_axis(ax1: "matplotlib.axes", compare_axis: "str") -> bool:
+ """
+ Return whether an axis is externally shared.
+
+ Parameters
+ ----------
+ ax1 : matplotlib.axes
+ Axis to query.
+ compare_axis : str
+ `"x"` or `"y"` according to whether the X-axis or Y-axis is being
+ compared.
+
+ Returns
+ -------
+ bool
+ `True` if the axis is externally shared. Otherwise `False`.
+
+ Notes
+ -----
+ If two axes with different positions are sharing an axis, they can be
+ referred to as *externally* sharing the common axis.
+
+ If two axes sharing an axis also have the same position, they can be
+ referred to as *internally* sharing the common axis (a.k.a twinning).
+
+ _handle_shared_axes() is only interested in axes externally sharing an
+ axis, regardless of whether either of the axes is also internally sharing
+ with a third axis.
+ """
+ if compare_axis == "x":
+ axes = ax1.get_shared_x_axes()
+ elif compare_axis == "y":
+ axes = ax1.get_shared_y_axes()
+ else:
+ raise ValueError(
+ "_has_externally_shared_axis() needs 'x' or 'y' as a second parameter"
+ )
+
+ axes = axes.get_siblings(ax1)
+
+ # Retain ax1 and any of its siblings which aren't in the same position as it
+ ax1_points = ax1.get_position().get_points()
+
+ for ax2 in axes:
+ if not np.array_equal(ax1_points, ax2.get_position().get_points()):
+ return True
+
+ return False
+
+
def handle_shared_axes(
axarr: Iterable["Axes"],
nplots: int,
@@ -328,7 +378,7 @@ def handle_shared_axes(
# the last in the column, because below is no subplot/gap.
if not layout[row_num(ax) + 1, col_num(ax)]:
continue
- if sharex or len(ax.get_shared_x_axes().get_siblings(ax)) > 1:
+ if sharex or _has_externally_shared_axis(ax, "x"):
_remove_labels_from_axis(ax.xaxis)
except IndexError:
@@ -337,7 +387,7 @@ def handle_shared_axes(
for ax in axarr:
if ax.is_last_row():
continue
- if sharex or len(ax.get_shared_x_axes().get_siblings(ax)) > 1:
+ if sharex or _has_externally_shared_axis(ax, "x"):
_remove_labels_from_axis(ax.xaxis)
if ncols > 1:
@@ -347,7 +397,7 @@ def handle_shared_axes(
# have a subplot there, we can skip the layout test
if ax.is_first_col():
continue
- if sharey or len(ax.get_shared_y_axes().get_siblings(ax)) > 1:
+ if sharey or _has_externally_shared_axis(ax, "y"):
_remove_labels_from_axis(ax.yaxis)
diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py
index 0208ab3e0225b..2838bef2a10b0 100644
--- a/pandas/tests/plotting/test_misc.py
+++ b/pandas/tests/plotting/test_misc.py
@@ -433,3 +433,117 @@ def test_dictionary_color(self):
ax = df1.plot(kind="line", color=dic_color)
colors = [rect.get_color() for rect in ax.get_lines()[0:2]]
assert all(color == expected[index] for index, color in enumerate(colors))
+
+ @pytest.mark.slow
+ def test_has_externally_shared_axis_x_axis(self):
+ # GH33819
+ # Test _has_externally_shared_axis() works for x-axis
+ func = plotting._matplotlib.tools._has_externally_shared_axis
+
+ fig = self.plt.figure()
+ plots = fig.subplots(2, 4)
+
+ # Create *externally* shared axes for first and third columns
+ plots[0][0] = fig.add_subplot(231, sharex=plots[1][0])
+ plots[0][2] = fig.add_subplot(233, sharex=plots[1][2])
+
+ # Create *internally* shared axes for second and third columns
+ plots[0][1].twinx()
+ plots[0][2].twinx()
+
+ # First column is only externally shared
+ # Second column is only internally shared
+ # Third column is both
+ # Fourth column is neither
+ assert func(plots[0][0], "x")
+ assert not func(plots[0][1], "x")
+ assert func(plots[0][2], "x")
+ assert not func(plots[0][3], "x")
+
+ @pytest.mark.slow
+ def test_has_externally_shared_axis_y_axis(self):
+ # GH33819
+ # Test _has_externally_shared_axis() works for y-axis
+ func = plotting._matplotlib.tools._has_externally_shared_axis
+
+ fig = self.plt.figure()
+ plots = fig.subplots(4, 2)
+
+ # Create *externally* shared axes for first and third rows
+ plots[0][0] = fig.add_subplot(321, sharey=plots[0][1])
+ plots[2][0] = fig.add_subplot(325, sharey=plots[2][1])
+
+ # Create *internally* shared axes for second and third rows
+ plots[1][0].twiny()
+ plots[2][0].twiny()
+
+ # First row is only externally shared
+ # Second row is only internally shared
+ # Third row is both
+ # Fourth row is neither
+ assert func(plots[0][0], "y")
+ assert not func(plots[1][0], "y")
+ assert func(plots[2][0], "y")
+ assert not func(plots[3][0], "y")
+
+ @pytest.mark.slow
+ def test_has_externally_shared_axis_invalid_compare_axis(self):
+ # GH33819
+ # Test _has_externally_shared_axis() raises an exception when
+ # passed an invalid value as compare_axis parameter
+ func = plotting._matplotlib.tools._has_externally_shared_axis
+
+ fig = self.plt.figure()
+ plots = fig.subplots(4, 2)
+
+ # Create arbitrary axes
+ plots[0][0] = fig.add_subplot(321, sharey=plots[0][1])
+
+ # Check that an invalid compare_axis value triggers the expected exception
+ msg = "needs 'x' or 'y' as a second parameter"
+ with pytest.raises(ValueError, match=msg):
+ func(plots[0][0], "z")
+
+ @pytest.mark.slow
+ def test_externally_shared_axes(self):
+ # Example from GH33819
+ # Create data
+ df = DataFrame({"a": np.random.randn(1000), "b": np.random.randn(1000)})
+
+ # Create figure
+ fig = self.plt.figure()
+ plots = fig.subplots(2, 3)
+
+ # Create *externally* shared axes
+ plots[0][0] = fig.add_subplot(231, sharex=plots[1][0])
+ # note: no plots[0][1] that's the twin only case
+ plots[0][2] = fig.add_subplot(233, sharex=plots[1][2])
+
+ # Create *internally* shared axes
+ # note: no plots[0][0] that's the external only case
+ twin_ax1 = plots[0][1].twinx()
+ twin_ax2 = plots[0][2].twinx()
+
+ # Plot data to primary axes
+ df["a"].plot(ax=plots[0][0], title="External share only").set_xlabel(
+ "this label should never be visible"
+ )
+ df["a"].plot(ax=plots[1][0])
+
+ df["a"].plot(ax=plots[0][1], title="Internal share (twin) only").set_xlabel(
+ "this label should always be visible"
+ )
+ df["a"].plot(ax=plots[1][1])
+
+ df["a"].plot(ax=plots[0][2], title="Both").set_xlabel(
+ "this label should never be visible"
+ )
+ df["a"].plot(ax=plots[1][2])
+
+ # Plot data to twinned axes
+ df["b"].plot(ax=twin_ax1, color="green")
+ df["b"].plot(ax=twin_ax2, color="yellow")
+
+ assert not plots[0][0].xaxis.get_label().get_visible()
+ assert plots[0][1].xaxis.get_label().get_visible()
+ assert not plots[0][2].xaxis.get_label().get_visible()
| ## Background:
Multi-row and/or multi-column subplots can utilize shared axes.
An external share happens at axis creation when a sharex or sharey
parameter is specified.
An internal share, or twinning, occurs when an overlayed axis is created
by the Axes.twinx() or Axes.twiny() calls.
The two types of sharing can be distinguished after the fact in the
following manner. If two axes sharing an axis also have the same
position, they are not in an external axis share, they are twinned.
For externally shared axes Pandas automatically removes tick labels for
all but the last row and/or first column in
./pandas/plotting/_matplotlib/tools.py's function _handle_shared_axes().
## The problem:
_handle_shared_axes() should be interested in externally shared axes,
whether or not they are also twinned. It should, but doesn't, ignore
axes which are only twinned. Which means that twinned-only axes wrongly
lose their tick labels.
## The cure:
This commit introduces _has_externally_shared_axis() which identifies
externally shared axes and uses it to expand upon the existing use of
len(Axes.get_shared_{x,y}_axes().get_siblings(a{x,y})) in
_handle_shared_axes() which miss these cases.
## The demonstration test case:
Note especially the axis labels (and associated tick labels).
```python
#!/usr/bin/python3
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Create data
df = pd.DataFrame({'a': np.random.randn(1000),
'b': np.random.randn(1000)})
# Create figure
fig = plt.figure()
plots = fig.subplots(2, 3)
# Create *externally* shared axes
plots[0][0] = plt.subplot(231, sharex=plots[1][0])
# note: no plots[0][1] that's the twin only case
plots[0][2] = plt.subplot(233, sharex=plots[1][2])
# Create *internally* shared axes
# note: no plots[0][0] that's the external only case
twin_ax1 = plots[0][1].twinx()
twin_ax2 = plots[0][2].twinx()
# Plot data to primary axes
df['a'].plot(ax=plots[0][0], title="External share only").set_xlabel("this label should never be visible")
df['a'].plot(ax=plots[1][0])
df['a'].plot(ax=plots[0][1], title="Internal share (twin) only").set_xlabel("this label should always be visible")
df['a'].plot(ax=plots[1][1])
df['a'].plot(ax=plots[0][2], title="Both").set_xlabel("this label should never be visible")
df['a'].plot(ax=plots[1][2])
# Plot data to twinned axes
df['b'].plot(ax=twin_ax1, color='green')
df['b'].plot(ax=twin_ax2, color='yellow')
# Do it
plt.show()
```
See images produced by this code for problem and fixed cases at the bug report: #33819.
- [x] closes #33819
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/33767 | 2020-04-24T16:20:26Z | 2020-09-30T00:11:53Z | 2020-09-30T00:11:52Z | 2020-09-30T07:30:48Z |
REF: simplify _try_cast | diff --git a/pandas/core/construction.py b/pandas/core/construction.py
index d1b07585943ea..2f71f4f4ccc19 100644
--- a/pandas/core/construction.py
+++ b/pandas/core/construction.py
@@ -27,7 +27,6 @@
maybe_upcast,
)
from pandas.core.dtypes.common import (
- is_categorical_dtype,
is_datetime64_ns_dtype,
is_extension_array_dtype,
is_float_dtype,
@@ -37,7 +36,7 @@
is_object_dtype,
is_timedelta64_ns_dtype,
)
-from pandas.core.dtypes.dtypes import CategoricalDtype, ExtensionDtype, registry
+from pandas.core.dtypes.dtypes import ExtensionDtype, registry
from pandas.core.dtypes.generic import (
ABCExtensionArray,
ABCIndexClass,
@@ -529,13 +528,23 @@ def _try_cast(
if maybe_castable(arr) and not copy and dtype is None:
return arr
+ if isinstance(dtype, ExtensionDtype) and dtype.kind != "M":
+ # create an extension array from its dtype
+ # DatetimeTZ case needs to go through maybe_cast_to_datetime
+ array_type = dtype.construct_array_type()._from_sequence
+ subarr = array_type(arr, dtype=dtype, copy=copy)
+ return subarr
+
try:
# GH#15832: Check if we are requesting a numeric dype and
# that we can convert the data to the requested dtype.
if is_integer_dtype(dtype):
- subarr = maybe_cast_to_integer_array(arr, dtype)
+ # this will raise if we have e.g. floats
+ maybe_cast_to_integer_array(arr, dtype)
+ subarr = arr
+ else:
+ subarr = maybe_cast_to_datetime(arr, dtype)
- subarr = maybe_cast_to_datetime(arr, dtype)
# Take care in creating object arrays (but iterators are not
# supported):
if is_object_dtype(dtype) and (
@@ -549,19 +558,7 @@ def _try_cast(
# in case of out of bound datetime64 -> always raise
raise
except (ValueError, TypeError):
- if is_categorical_dtype(dtype):
- # We *do* allow casting to categorical, since we know
- # that Categorical is the only array type for 'category'.
- dtype = cast(CategoricalDtype, dtype)
- subarr = dtype.construct_array_type()(
- arr, dtype.categories, ordered=dtype.ordered
- )
- elif is_extension_array_dtype(dtype):
- # create an extension array from its dtype
- dtype = cast(ExtensionDtype, dtype)
- array_type = dtype.construct_array_type()._from_sequence
- subarr = array_type(arr, dtype=dtype, copy=copy)
- elif dtype is not None and raise_cast_failure:
+ if dtype is not None and raise_cast_failure:
raise
else:
subarr = np.array(arr, dtype=object, copy=copy)
| Part of a sequence of PRs aimed at sharing code between Series/Index/array | https://api.github.com/repos/pandas-dev/pandas/pulls/33764 | 2020-04-24T14:48:10Z | 2020-04-24T21:34:25Z | 2020-04-24T21:34:25Z | 2020-04-24T22:21:12Z |
TYP/CLN: rogue type comment not caught by code checks | diff --git a/pandas/compat/numpy/function.py b/pandas/compat/numpy/function.py
index ccc970fb453c2..260cc69187d38 100644
--- a/pandas/compat/numpy/function.py
+++ b/pandas/compat/numpy/function.py
@@ -157,7 +157,7 @@ def validate_argsort_with_ascending(ascending, args, kwargs):
return ascending
-CLIP_DEFAULTS = dict(out=None) # type Dict[str, Any]
+CLIP_DEFAULTS: Dict[str, Any] = dict(out=None)
validate_clip = CompatValidator(
CLIP_DEFAULTS, fname="clip", method="both", max_fname_arg_count=3
)
| https://api.github.com/repos/pandas-dev/pandas/pulls/33763 | 2020-04-24T14:38:53Z | 2020-04-24T15:26:48Z | 2020-04-24T15:26:48Z | 2020-04-24T15:38:30Z | |
Stratified sampling | 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.4.rst b/doc/source/whatsnew/v1.0.4.rst
new file mode 100644
index 0000000000000..365a9ed8c5ba8
--- /dev/null
+++ b/doc/source/whatsnew/v1.0.4.rst
@@ -0,0 +1,69 @@
+.. _whatsnew_104:
+
+What's new in 1.0.4 (??)
+------------------------
+
+These are the changes in pandas 1.0.4. See :ref:`release` for a full changelog
+including other versions of pandas.
+
+
+.. ---------------------------------------------------------------------------
+
+Enhancements
+~~~~~~~~~~~~
+
+.. _whatsnew_104.stratified_sample:
+
+Stratified Sampling in Pandas
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+We've added :meth:`~DataFrame.stratified_sample` for sampling a DataFrame object using strata.
+
+A stratified sample is used when it is desired to keep the same proportions of the variables in the original population when sampling.
+
+For example:
+
+.. code-block:: ipython
+
+ In [1]: df = pd.DataFrame({'gender': ['male', 'male', 'female', 'female', 'female',
+ ... 'female', 'female', 'female', 'male', 'male'],
+ ... 'age': [25, 26, 25, 26, 30, 25, 25, 30, 30, 25],
+ ... 'country': ['US', 'CAN', 'MEX', 'CAN', 'IN', 'CAN',
+ ... 'CAN', 'US', 'CAN', 'IN'],
+ ... 'income_K' : [100, 110, 99, 110, 110, 100, 100, 110,
+ ... 100, 99]}
+ )
+ In [2]: df.stratified_sample(strata=['age'], n=5, random_state=0, reset_index=True)
+ Out[2]:
+ gender age country income_K
+ 0 female 25 CAN 100
+ 1 male 25 US 100
+ 2 female 26 CAN 110
+ 3 male 30 CAN 100
+ 4 female 30 US 110
+
+We've also added :meth:`~DataFrame.stratified_sample_counts` to return the counts that would be generated by a stratified sampling.
+
+.. code-block:: ipython
+
+ In [1]: df = pd.DataFrame({'gender': ['male', 'male', 'female', 'female', 'female',
+ ... 'female', 'female', 'female', 'male', 'male'],
+ ... 'age': [25, 26, 25, 26, 30, 25, 25, 30, 30, 25],
+ ... 'country': ['US', 'CAN', 'MEX', 'CAN', 'IN', 'CAN',
+ ... 'CAN', 'US', 'CAN', 'IN'],
+ ... 'income_K' : [100, 110, 99, 110, 110, 100, 100, 110,
+ ... 100, 99]}
+ )
+ In [2]: df.stratified_sample_counts(strata=['age'], n=5)
+ Out[2]:
+ age size sample_size
+ 0 25 5 2
+ 1 26 2 1
+ 2 30 3 2
+
+
+.. _whatsnew_104.contributors:
+
+Contributors
+~~~~~~~~~~~~
+* Flavio Bossolan +
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 6a4f83427310e..db64602277f4d 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -4827,6 +4827,8 @@ def sample(
--------
numpy.random.choice: Generates a random sample from a given 1-D numpy
array.
+ DataFrame.stratified_sample: Return a random stratified sample from a data
+ frame using proportionate stratification.
Notes
-----
@@ -4971,6 +4973,375 @@ def sample(
locs = rs.choice(axis_length, size=n, replace=replace, p=weights)
return self.take(locs, axis=axis)
+ def stratified_sample(
+ self: FrameOrSeries,
+ strata=None,
+ n=None,
+ random_state=None,
+ reset_index=False
+ ) -> FrameOrSeries:
+ """
+ Return a random stratified sample using proportionate stratification.
+
+ A stratified sample is used when it is desired to keep the same proportions
+ of the variables in the original population.
+
+ .. versionadded:: 1.0.4
+
+ Parameters
+ ----------
+ strata: list, optional
+ List containing columns that will be used in the stratified sampling.
+ If not provided, all columns will be used.
+ n: int or float, optional
+ Sampling size to be returned. If int it must be between 1 and total
+ population size. If float it must be 0 < n < 1. If not informed,
+ a sampling size will be calculated using Cochran adjusted sampling
+ formula (see section 'Notes' for more details).
+ random_state : int, array-like, BitGenerator, np.random.RandomState, optional
+ If int, array-like, or BitGenerator (NumPy>=1.17), seed for
+ random number generator.
+ reset_index: bool, optional
+ If True, returned data frame will have its axis reset, otherwise it will
+ keep its original axis values for the chosen samples.
+
+ Returns
+ -------
+ Series or DataFrame
+ A new object of same type as caller containing `n` items randomly
+ sampled from the caller object following the given strata.
+
+ See Also
+ --------
+ DataFrame.stratified_sample_counts: Return total counts that a stratified
+ sample would return given a set of strata.
+ DataFrame.sample: Return a random sample of items from an axis of object.
+
+ Notes
+ -----
+ This method uses the proportionate stratification formula: n1 = (N1 / N) * n
+ where:
+ * n1 is the sample size of stratum 1
+ * N1 is the population size of stratum 1
+ * N is the total population size
+ * n is the sampling size
+
+ When the parameter 'n' is not specified, the function will return a calculated
+ sample based on the Cochran sample formula:
+ cochran_n = (Z ** 2 * p * q) / e ** 2
+ where:
+ * Z is the z-value. In this case we use 1.96 representing 95%
+ * p is the estimated proportion of the population which has an
+ attribute. In this case we use 0.5
+ * q is 1 - p
+ * e is the margin of error. In this case we use 0.05
+
+ This formula is adjusted if the calcuated size is greater or equal the
+ population size as follows:
+ adjusted_cochran = cochran_n / 1 + ((cochran_n - 1) / N)
+ where:
+ * cochran_n = result of the previous formula
+ * N is the population size
+
+ Examples
+ --------
+ >>> df = pd.DataFrame({'gender': ['male', 'male', 'female', 'female', 'female',
+ ... 'female', 'female', 'female', 'male', 'male'],
+ ... 'age': [25, 26, 25, 26, 30, 25, 25, 30, 30, 25],
+ ... 'country': ['US', 'CAN', 'MEX', 'CAN', 'IN', 'CAN',
+ ... 'CAN', 'US', 'CAN', 'IN'],
+ ... 'income_K' : [100, 110, 99, 110, 110, 100, 100, 110,
+ ... 100, 99]})
+
+ >>> df
+ gender age country income_K
+ 0 male 25 US 100
+ 1 male 26 CAN 110
+ 2 female 25 MEX 99
+ 3 female 26 CAN 110
+ 4 female 30 IN 110
+ 5 female 25 CAN 100
+ 6 female 25 CAN 100
+ 7 female 30 US 110
+ 8 male 30 CAN 100
+ 9 male 25 IN 99
+
+ A stratified random sample by gender returning only 5 samples:
+
+ >>> df.stratified_sample(strata=['gender'], n=5)
+ gender age country income_K
+ 3 female 26 CAN 110
+ 2 female 25 MEX 99
+ 4 female 30 IN 110
+ 1 male 26 CAN 110
+ 9 male 25 IN 99
+
+ The same idea, but reseting the index:
+
+ >>> df.stratified_sample(strata=['gender'], n=5, reset_index=True)
+ gender age country income_K
+ 0 female 25 CAN 100
+ 1 female 30 IN 110
+ 2 female 30 US 110
+ 3 male 30 CAN 100
+ 4 male 26 CAN 110
+
+ A stratified random samplig by gender and country returning 70% of the data
+ and setting a seed for reproducibility:
+
+ >>> df.stratified_sample(strata=['gender','country'],n=.7, random_state=0)
+ gender age country income_K
+ 6 female 25 CAN 100
+ 5 female 25 CAN 100
+ 4 female 30 IN 110
+ 2 female 25 MEX 99
+ 7 female 30 US 110
+ 8 male 30 CAN 100
+ 9 male 25 IN 99
+ 0 male 25 US 100
+ """
+ tmp_df = self.iloc[:]
+ population = len(tmp_df)
+
+ # parameter validation
+ if strata is None:
+ strata = list(tmp_df.columns)
+ elif not type(strata) is list:
+ raise ValueError(
+ "The strata must be a list with the variable names "
+ "to be used for each stratum."
+ )
+ else:
+ for i in strata:
+ if i not in tmp_df.columns:
+ raise ValueError(
+ f"The stratum '{i}' is not a valid column "
+ "name in the object."
+ )
+ else:
+ strata = [c for c in set(strata) if c in tmp_df.columns]
+
+ size = self._stratified_sample_size(population, n)
+ tmp_ = tmp_df[strata]
+ tmp_.insert(0, 'size', 1)
+ tmp_grpd = tmp_.groupby(strata).count().reset_index()
+ tmp_grpd['samp_size'] = round(size / population * tmp_grpd['size']).astype(int)
+ del(tmp_)
+
+ # controlling variable to create the dataframe or append to it
+ first = True
+ for i in range(len(tmp_grpd)):
+ # query generator for each iteration
+ qry = ''
+ for s in range(len(strata)):
+ stratum = strata[s]
+
+ if stratum not in tmp_df.columns:
+ raise ValueError(
+ "Strata must be a list with "
+ "data frame column names."
+ )
+
+ value = tmp_grpd.iloc[i][stratum]
+ n = tmp_grpd.iloc[i]['samp_size']
+
+ if type(value) == str:
+ value = "'" + str(value) + "'"
+
+ if s != len(strata) - 1:
+ qry = qry + stratum + ' == ' + str(value) + ' & '
+ else:
+ qry = qry + stratum + ' == ' + str(value)
+
+ # final dataframe
+ if first:
+ stratified_df = tmp_df.query(qry).sample(
+ n=n,
+ random_state=random_state
+ ).reset_index(drop=False)
+
+ first = False
+ else:
+ tmp_ = tmp_df.query(qry).sample(
+ n=n,
+ random_state=random_state
+ ).reset_index(drop=False)
+
+ stratified_df = stratified_df.append(tmp_, ignore_index=True)
+
+ if reset_index:
+ stratified_df = stratified_df.drop('index', axis=1)
+ else:
+ stratified_df.set_index('index', inplace=True)
+ stratified_df.index.name = None
+
+ return stratified_df
+
+ def stratified_sample_counts(
+ self: FrameOrSeries,
+ strata=None,
+ n=None
+ ) -> FrameOrSeries:
+ """
+ Return the population and stratified sample counts for comparison.
+
+ A stratified sample is used when it is desired to keep the same proportions
+ of the variables in the original population.
+
+ .. versionadded:: 1.0.4
+
+ Parameters
+ ----------
+ strata: list, optional
+ List containing columns that will be used in the stratified sampling.
+ If not provided, all columns will be used.
+ n: int or float, optional
+ Sampling size to be returned. If int it must be between 1 and total
+ population size. If float it must be 0 < n < 1. If not informed,
+ a sampling size will be calculated using Cochran adjusted sampling
+ formula (see section 'Notes' for more details).
+
+ Returns
+ -------
+ Series or DataFrame
+ Return a table containing the population counts and the sample counts.
+
+ See Also
+ --------
+ DataFrame.stratified_sample: Return a random stratified sample using
+ proportionate stratification.
+ DataFrame.sample: Return a random sample of items from an axis of object.
+
+ Notes
+ -----
+ This method uses the proportionate stratification formula: n1 = (N1 / N) * n
+ where:
+ * n1 is the sample size of stratum 1
+ * N1 is the population size of stratum 1
+ * N is the total population size
+ * n is the sampling size
+
+ When the parameter 'n' is not specified, the function will return a calculated
+ sample based on the Cochran sample formula:
+ cochran_n = (Z ** 2 * p * q) / e ** 2
+ where:
+ * Z is the z-value. In this case we use 1.96 representing 95%
+ * p is the estimated proportion of the population which has an
+ attribute. In this case we use 0.5
+ * q is 1 - p
+ * e is the margin of error. In this case we use 0.05
+
+ This formula is adjusted if the calcuated size is greater or equal the
+ population size as follows:
+ adjusted_cochran = cochran_n / 1 + ((cochran_n - 1) / N)
+ where:
+ * cochran_n = result of the previous formula
+ * N is the population size
+
+ Examples
+ --------
+ >>> df = pd.DataFrame({'gender': ['male', 'male', 'female', 'female', 'female',
+ ... 'female', 'female', 'female', 'male', 'male'],
+ ... 'age': [25, 26, 25, 26, 30, 25, 25, 30, 30, 25],
+ ... 'country': ['US', 'CAN', 'MEX', 'CAN', 'IN', 'CAN',
+ ... 'CAN', 'US', 'CAN', 'IN'],
+ ... 'income_K' : [100, 110, 99, 110, 110, 100, 100, 110,
+ ... 100, 99]})
+
+ >>> df
+ gender age country income_K
+ 0 male 25 US 100
+ 1 male 26 CAN 110
+ 2 female 25 MEX 99
+ 3 female 26 CAN 110
+ 4 female 30 IN 110
+ 5 female 25 CAN 100
+ 6 female 25 CAN 100
+ 7 female 30 US 110
+ 8 male 30 CAN 100
+ 9 male 25 IN 99
+
+ A stratified random sample counts by gender returning only 5 samples:
+
+ >>> df.stratified_sample_counts(strata=['gender'], n=5)
+
+ gender size samp_size
+ 0 female 6 3
+ 1 male 4 2
+
+ A stratified random samplig counts by gender and country returning 70%
+ of the data:
+
+ >>> df.stratified_sample_counts(strata=['gender', 'country'], n=.7)
+
+ gender country size samp_size
+ 0 female CAN 3 2
+ 1 female IN 1 1
+ 2 female MEX 1 1
+ 3 female US 1 1
+ 4 male CAN 2 1
+ 5 male IN 1 1
+ 6 male US 1 1
+
+ """
+ tmp_df = self.iloc[:]
+ population = len(tmp_df)
+
+ # parameter validation
+ if strata is None:
+ strata = list(tmp_df.columns)
+ elif not type(strata) is list:
+ raise ValueError(
+ "The strata must be a list with the variable names "
+ "to be used for each stratum."
+ )
+ else:
+ for i in strata:
+ if i not in tmp_df.columns:
+ raise ValueError(
+ f"The stratum '{i}' is not a valid column "
+ "name in the object."
+ )
+ else:
+ strata = [c for c in set(strata) if c in tmp_df.columns]
+
+ size = self._stratified_sample_size(population, n)
+ tmp = tmp_df[strata]
+ tmp.insert(0, 'size', 1)
+ tmp_grpd = tmp.groupby(strata).count().reset_index()
+ tmp_grpd['sample_size'] = round(
+ size / population * tmp_grpd['size']
+ ).astype(int)
+ return tmp_grpd
+
+ def _stratified_sample_size(
+ self: FrameOrSeries,
+ population,
+ size
+ ) -> FrameOrSeries:
+ """Calculates the stratified sample size."""
+
+ if size is None:
+ cochran_n = round(((1.96) ** 2 * 0.5 * 0.5) / 0.05 ** 2)
+ if population <= cochran_n:
+ # adjustment for smaller populations
+ n = round(cochran_n / (1 + ((cochran_n - 1) / population)))
+ else:
+ n = cochran_n
+ elif size >= 0 and size < 1:
+ n = round(population * size)
+ elif size < 0:
+ raise ValueError(
+ "Parameter 'n' must be an integer or a "
+ "proportion between 0 and 0.99."
+ )
+ elif size >= 1 and size <= population:
+ n = size
+ elif size > population:
+ raise ValueError('Cannot take a sample larger than the population.')
+
+ return n
+
_shared_docs[
"pipe"
] = r"""
diff --git a/pandas/tests/generic/methods/test_stratified_sample.py b/pandas/tests/generic/methods/test_stratified_sample.py
new file mode 100644
index 0000000000000..4988433c5e82a
--- /dev/null
+++ b/pandas/tests/generic/methods/test_stratified_sample.py
@@ -0,0 +1,41 @@
+import pandas as pd
+import pandas._testing as tm
+
+
+def test_stratified_sample():
+ df = pd.DataFrame({
+ 'gender': ['male', 'male', 'female', 'female', 'female',
+ 'female', 'female', 'female', 'male', 'male'],
+ 'age': [25, 26, 25, 26, 30, 25, 25, 30, 30, 25],
+ 'country': ['US', 'CAN', 'MEX', 'CAN', 'IN', 'CAN', 'CAN', 'US', 'CAN', 'IN'],
+ 'income_K' : [100, 110, 99, 110, 110, 100, 100, 110, 100, 99]
+ })
+
+ result = df.stratified_sample(strata=['age'], n=5, random_state=0, reset_index=True)
+ expected = pd.DataFrame({
+ 'gender': ['female', 'male', 'female', 'male', 'female'],
+ 'age': [25, 25, 26, 30, 30],
+ 'country': ['CAN', 'US', 'CAN', 'CAN', 'US'],
+ 'income_K' : [100, 100, 110, 100, 110]
+ })
+
+ tm.assert_frame_equal(result, expected)
+
+
+def test_stratified_sample_counts():
+ df = pd.DataFrame({
+ 'gender': ['male', 'male', 'female', 'female', 'female',
+ 'female', 'female', 'female', 'male', 'male'],
+ 'age': [25, 26, 25, 26, 30, 25, 25, 30, 30, 25],
+ 'country': ['US', 'CAN', 'MEX', 'CAN', 'IN', 'CAN', 'CAN', 'US', 'CAN', 'IN'],
+ 'income_K' : [100, 110, 99, 110, 110, 100, 100, 110, 100, 99]
+ })
+
+ result = df.stratified_sample_counts(strata=['age'], n=5)
+ expected = pd.DataFrame({
+ 'age': [25, 26, 30],
+ 'size': [5, 2, 3],
+ 'sample_size': [2, 1, 2]
+ })
+
+ tm.assert_frame_equal(result, expected)
| - [ ] Added new method stratified_sample
- [ ] 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/33762 | 2020-04-24T13:24:32Z | 2020-04-25T17:55:34Z | null | 2020-04-25T17:55:35Z |
REGR: fix DataFrame reduction with EA columns and numeric_only=True | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 7ad7e8f5a27b0..f8199524abbaf 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -571,6 +571,7 @@ 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`)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index f8cb99e2b2e75..3d563f48d32c9 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -8325,10 +8325,10 @@ def _get_data(axis_matters):
out_dtype = "bool" if filter_type == "bool" else None
def blk_func(values):
- if values.ndim == 1 and not isinstance(values, np.ndarray):
- # we can't pass axis=1
- return op(values, axis=0, skipna=skipna, **kwds)
- return op(values, axis=1, skipna=skipna, **kwds)
+ if isinstance(values, ExtensionArray):
+ return values._reduce(name, skipna=skipna, **kwds)
+ else:
+ return op(values, axis=1, skipna=skipna, **kwds)
# After possibly _get_data and transposing, we are now in the
# simple case where we can use BlockManager._reduce
diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py
index 75afc59382a75..f69c85c070ca4 100644
--- a/pandas/tests/frame/test_analytics.py
+++ b/pandas/tests/frame/test_analytics.py
@@ -896,9 +896,17 @@ def test_mean_datetimelike_numeric_only_false(self):
# mean of period is not allowed
df["D"] = pd.period_range("2016", periods=3, freq="A")
- with pytest.raises(TypeError, match="reduction operation 'mean' not allowed"):
+ with pytest.raises(TypeError, match="mean is not implemented for Period"):
df.mean(numeric_only=False)
+ def test_mean_extensionarray_numeric_only_true(self):
+ # https://github.com/pandas-dev/pandas/issues/33256
+ arr = np.random.randint(1000, size=(10, 5))
+ df = pd.DataFrame(arr, dtype="Int64")
+ result = df.mean(numeric_only=True)
+ expected = pd.DataFrame(arr).mean()
+ tm.assert_series_equal(result, expected)
+
def test_stats_mixed_type(self, float_string_frame):
# don't blow up
float_string_frame.std(1)
| Closes #33256
For the block-wise path in `DataFrame._reduce`, we ensure to use the EA reduction for blocks holding EAs, instead of passing the EA to the `op` function (which is typically the `nanops` nan function).
This needs https://github.com/pandas-dev/pandas/pull/33758 to be merged, since that PR fixes the test that is failing here. | https://api.github.com/repos/pandas-dev/pandas/pulls/33761 | 2020-04-24T09:39:35Z | 2020-05-01T18:19:12Z | 2020-05-01T18:19:11Z | 2020-05-26T09:36:02Z |
REGR: disallow mean of period column again | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 2d2f7bbf7092f..0eda80a78ee4f 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -100,7 +100,6 @@
is_list_like,
is_named_tuple,
is_object_dtype,
- is_period_dtype,
is_scalar,
is_sequence,
needs_i8_conversion,
@@ -8225,7 +8224,7 @@ def _reduce(
dtype_is_dt = np.array(
[
- is_datetime64_any_dtype(values.dtype) or is_period_dtype(values.dtype)
+ is_datetime64_any_dtype(values.dtype)
for values in self._iter_column_arrays()
],
dtype=bool,
@@ -8233,7 +8232,7 @@ def _reduce(
if numeric_only is None and name in ["mean", "median"] and dtype_is_dt.any():
warnings.warn(
"DataFrame.mean and DataFrame.median with numeric_only=None "
- "will include datetime64, datetime64tz, and PeriodDtype columns in a "
+ "will include datetime64 and datetime64tz columns in a "
"future version.",
FutureWarning,
stacklevel=3,
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index b9ff0a5959c01..32b05872ded3f 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -7,7 +7,7 @@
from pandas._config import get_option
-from pandas._libs import NaT, Period, Timedelta, Timestamp, iNaT, lib
+from pandas._libs import NaT, Timedelta, Timestamp, iNaT, lib
from pandas._typing import ArrayLike, Dtype, Scalar
from pandas.compat._optional import import_optional_dependency
@@ -353,14 +353,6 @@ def _wrap_results(result, dtype: Dtype, fill_value=None):
else:
result = result.astype("m8[ns]").view(dtype)
- elif isinstance(dtype, PeriodDtype):
- if is_float(result) and result.is_integer():
- result = int(result)
- if is_integer(result):
- result = Period._from_ordinal(result, freq=dtype.freq)
- else:
- raise NotImplementedError(type(result), result)
-
return result
@@ -516,6 +508,7 @@ def nansum(
return _wrap_results(the_sum, dtype)
+@disallow(PeriodDtype)
@bottleneck_switch()
def nanmean(values, axis=None, skipna=True, mask=None):
"""
@@ -547,7 +540,12 @@ def nanmean(values, axis=None, skipna=True, mask=None):
)
dtype_sum = dtype_max
dtype_count = np.float64
- if is_integer_dtype(dtype) or needs_i8_conversion(dtype):
+ # not using needs_i8_conversion because that includes period
+ if (
+ is_integer_dtype(dtype)
+ or is_datetime64_any_dtype(dtype)
+ or is_timedelta64_dtype(dtype)
+ ):
dtype_sum = np.float64
elif is_float_dtype(dtype):
dtype_sum = dtype
diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py
index 0255759513e28..75afc59382a75 100644
--- a/pandas/tests/frame/test_analytics.py
+++ b/pandas/tests/frame/test_analytics.py
@@ -885,16 +885,20 @@ def test_mean_datetimelike_numeric_only_false(self):
"A": np.arange(3),
"B": pd.date_range("2016-01-01", periods=3),
"C": pd.timedelta_range("1D", periods=3),
- "D": pd.period_range("2016", periods=3, freq="A"),
}
)
+ # datetime(tz) and timedelta work
result = df.mean(numeric_only=False)
- expected = pd.Series(
- {"A": 1, "B": df.loc[1, "B"], "C": df.loc[1, "C"], "D": df.loc[1, "D"]}
- )
+ expected = pd.Series({"A": 1, "B": df.loc[1, "B"], "C": df.loc[1, "C"]})
tm.assert_series_equal(result, expected)
+ # mean of period is not allowed
+ df["D"] = pd.period_range("2016", periods=3, freq="A")
+
+ with pytest.raises(TypeError, match="reduction operation 'mean' not allowed"):
+ df.mean(numeric_only=False)
+
def test_stats_mixed_type(self, float_string_frame):
# don't blow up
float_string_frame.std(1)
| This reverts parts of https://github.com/pandas-dev/pandas/pull/32426 and https://github.com/pandas-dev/pandas/pull/29941 (those are only on master, not yet released), to disallow taking the mean on a Period dtype column again. The mean for period is not supported on PeriodArray itself or for a Series of period dtype (on purpose, see discussion in https://github.com/pandas-dev/pandas/pull/24757 when mean for datetimelike was added), so for DataFrame columns it should also not work.
See also comment at https://github.com/pandas-dev/pandas/pull/32426#issuecomment-618872954
cc @jbrockmendel | https://api.github.com/repos/pandas-dev/pandas/pulls/33758 | 2020-04-24T09:20:59Z | 2020-04-24T21:35:45Z | 2020-04-24T21:35:45Z | 2020-04-25T11:46:15Z |
BUG: MonthOffset.name | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 495dcc5700241..3adae989af58a 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -104,6 +104,7 @@
from pandas.io.formats.format import DataFrameFormatter, format_percentiles
from pandas.io.formats.printing import pprint_thing
from pandas.tseries.frequencies import to_offset
+from pandas.tseries.offsets import Tick
if TYPE_CHECKING:
from pandas.core.resample import Resampler
@@ -8068,7 +8069,7 @@ def first(self: FrameOrSeries, offset) -> FrameOrSeries:
end_date = end = self.index[0] + offset
# Tick-like, e.g. 3 weeks
- if not offset.is_anchored() and hasattr(offset, "_inc"):
+ if isinstance(offset, Tick):
if end_date in self.index:
end = self.index.searchsorted(end_date, side="left")
return self.iloc[:end]
diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py
index 044dfa703c081..0a7eaa7b7be3e 100644
--- a/pandas/tests/tseries/offsets/test_offsets.py
+++ b/pandas/tests/tseries/offsets/test_offsets.py
@@ -4315,6 +4315,13 @@ def test_valid_month_attributes(kwd, month_classes):
cls(**{kwd: 3})
+def test_month_offset_name(month_classes):
+ # GH#33757 off.name with n != 1 should not raise AttributeError
+ obj = month_classes(1)
+ obj2 = month_classes(2)
+ assert obj2.name == obj.name
+
+
@pytest.mark.parametrize("kwd", sorted(liboffsets.relativedelta_kwds))
def test_valid_relativedelta_kwargs(kwd):
# Check that all the arguments specified in liboffsets.relativedelta_kwds
diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py
index 8ba10f56f163c..effd923cedd17 100644
--- a/pandas/tseries/offsets.py
+++ b/pandas/tseries/offsets.py
@@ -1125,14 +1125,6 @@ class MonthOffset(SingleConstructorOffset):
__init__ = BaseOffset.__init__
- @property
- def name(self) -> str:
- if self.is_anchored:
- return self.rule_code
- else:
- month = ccalendar.MONTH_ALIASES[self.n]
- return f"{self.code_rule}-{month}"
-
def is_on_offset(self, dt: datetime) -> bool:
if self.normalize and not _is_normalized(dt):
return False
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
`is_anchored` is being accessed indirectly (its not a property). As a result we never go down the other path, which would raise AttributeError since there is no `code_rule`. | https://api.github.com/repos/pandas-dev/pandas/pulls/33757 | 2020-04-24T02:38:17Z | 2020-04-25T00:30:01Z | 2020-04-25T00:30:01Z | 2020-04-25T00:39:36Z |
CI: Revert Cython Pin (take 2) | diff --git a/ci/deps/azure-37-numpydev.yaml b/ci/deps/azure-37-numpydev.yaml
index 17c3d318ce54d..29ebfe2639e32 100644
--- a/ci/deps/azure-37-numpydev.yaml
+++ b/ci/deps/azure-37-numpydev.yaml
@@ -14,8 +14,7 @@ dependencies:
- pytz
- pip
- pip:
- - cython==0.29.16
- # GH#33507 cython 3.0a1 is causing TypeErrors 2020-04-13
+ - cython>=0.29.16
- "git+git://github.com/dateutil/dateutil.git"
- "-f https://7933911d6844c6c53a7d-47bd50c35cd79bd838daf386af554a83.ssl.cf2.rackcdn.com"
- "--pre"
| - [x] closes #33507
reverts #33534
New Cython pre release available today - https://pypi.org/project/Cython/3.0a2/
cc @WillAyd
Update: 3.0a2 (no such luck - seems there is a regression which is being looked at)
https://mail.python.org/pipermail/cython-devel/2020-April/005340.html
https://github.com/cython/cython/issues/3544
Update now trying 3.0a3 | https://api.github.com/repos/pandas-dev/pandas/pulls/33755 | 2020-04-23T22:49:55Z | 2020-04-27T23:10:34Z | 2020-04-27T23:10:34Z | 2020-04-27T23:47:08Z |
CLN: Parametrize dtype inference tests | diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py
index 8c0580b7cf047..8b20f9ada8ff7 100644
--- a/pandas/tests/dtypes/test_inference.py
+++ b/pandas/tests/dtypes/test_inference.py
@@ -354,71 +354,69 @@ def test_is_recompilable_fails(ll):
class TestInference:
- def test_infer_dtype_bytes(self):
- compare = "bytes"
-
- # string array of bytes
- arr = np.array(list("abc"), dtype="S1")
- assert lib.infer_dtype(arr, skipna=True) == compare
+ @pytest.mark.parametrize(
+ "arr",
+ [
+ np.array(list("abc"), dtype="S1"),
+ np.array(list("abc"), dtype="S1").astype(object),
+ [b"a", np.nan, b"c"],
+ ],
+ )
+ def test_infer_dtype_bytes(self, arr):
+ result = lib.infer_dtype(arr, skipna=True)
+ assert result == "bytes"
- # object array of bytes
- arr = arr.astype(object)
- assert lib.infer_dtype(arr, skipna=True) == compare
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (float("inf"), True),
+ (np.inf, True),
+ (-np.inf, False),
+ (1, False),
+ ("a", False),
+ ],
+ )
+ def test_isposinf_scalar(self, value, expected):
+ # GH 11352
+ result = libmissing.isposinf_scalar(value)
+ assert result is expected
- # object array of bytes with missing values
- assert lib.infer_dtype([b"a", np.nan, b"c"], skipna=True) == compare
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (float("-inf"), True),
+ (-np.inf, True),
+ (np.inf, False),
+ (1, False),
+ ("a", False),
+ ],
+ )
+ def test_isneginf_scalar(self, value, expected):
+ result = libmissing.isneginf_scalar(value)
+ assert result is expected
- def test_isinf_scalar(self):
- # GH 11352
- assert libmissing.isposinf_scalar(float("inf"))
- assert libmissing.isposinf_scalar(np.inf)
- assert not libmissing.isposinf_scalar(-np.inf)
- assert not libmissing.isposinf_scalar(1)
- assert not libmissing.isposinf_scalar("a")
-
- assert libmissing.isneginf_scalar(float("-inf"))
- assert libmissing.isneginf_scalar(-np.inf)
- assert not libmissing.isneginf_scalar(np.inf)
- assert not libmissing.isneginf_scalar(1)
- assert not libmissing.isneginf_scalar("a")
-
- @pytest.mark.parametrize("maybe_int", [True, False])
+ @pytest.mark.parametrize("coerce_numeric", [True, False])
@pytest.mark.parametrize(
"infinity", ["inf", "inF", "iNf", "Inf", "iNF", "InF", "INf", "INF"]
)
- def test_maybe_convert_numeric_infinities(self, infinity, maybe_int):
+ @pytest.mark.parametrize("prefix", ["", "-", "+"])
+ def test_maybe_convert_numeric_infinities(self, coerce_numeric, infinity, prefix):
# see gh-13274
- na_values = {"", "NULL", "nan"}
-
- pos = np.array(["inf"], dtype=np.float64)
- neg = np.array(["-inf"], dtype=np.float64)
-
- msg = "Unable to parse string"
-
- out = lib.maybe_convert_numeric(
- np.array([infinity], dtype=object), na_values, maybe_int
- )
- tm.assert_numpy_array_equal(out, pos)
-
- out = lib.maybe_convert_numeric(
- np.array(["-" + infinity], dtype=object), na_values, maybe_int
- )
- tm.assert_numpy_array_equal(out, neg)
-
- out = lib.maybe_convert_numeric(
- np.array([infinity], dtype=object), na_values, maybe_int
- )
- tm.assert_numpy_array_equal(out, pos)
-
- out = lib.maybe_convert_numeric(
- np.array(["+" + infinity], dtype=object), na_values, maybe_int
+ result = lib.maybe_convert_numeric(
+ np.array([prefix + infinity], dtype=object),
+ na_values={"", "NULL", "nan"},
+ coerce_numeric=coerce_numeric,
)
- tm.assert_numpy_array_equal(out, pos)
+ expected = np.array([np.inf if prefix in ["", "+"] else -np.inf])
+ tm.assert_numpy_array_equal(result, expected)
- # too many characters
+ def test_maybe_convert_numeric_infinities_raises(self):
+ msg = "Unable to parse string"
with pytest.raises(ValueError, match=msg):
lib.maybe_convert_numeric(
- np.array(["foo_" + infinity], dtype=object), na_values, maybe_int
+ np.array(["foo_inf"], dtype=object),
+ na_values={"", "NULL", "nan"},
+ coerce_numeric=False,
)
def test_maybe_convert_numeric_post_floatify_nan(self, coerce):
| https://api.github.com/repos/pandas-dev/pandas/pulls/33753 | 2020-04-23T21:11:22Z | 2020-04-23T22:38:15Z | 2020-04-23T22:38:15Z | 2020-04-23T22:39:28Z | |
TST: pd.NA TypeError in drop_duplicates with object dtype | diff --git a/pandas/conftest.py b/pandas/conftest.py
index 70be6b5d9fcbc..0adbaf6a112cf 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -256,7 +256,9 @@ def nselect_method(request):
# ----------------------------------------------------------------
# Missing values & co.
# ----------------------------------------------------------------
-@pytest.fixture(params=[None, np.nan, pd.NaT, float("nan"), np.float("NaN"), pd.NA])
+@pytest.fixture(
+ params=[None, np.nan, pd.NaT, float("nan"), np.float("NaN"), pd.NA], ids=str
+)
def nulls_fixture(request):
"""
Fixture for each null type in pandas.
diff --git a/pandas/tests/frame/methods/test_drop_duplicates.py b/pandas/tests/frame/methods/test_drop_duplicates.py
index fd4bae26ade57..7c6391140e2bb 100644
--- a/pandas/tests/frame/methods/test_drop_duplicates.py
+++ b/pandas/tests/frame/methods/test_drop_duplicates.py
@@ -418,3 +418,10 @@ def test_drop_duplicates_ignore_index(
tm.assert_frame_equal(result_df, expected)
tm.assert_frame_equal(df, DataFrame(origin_dict))
+
+
+def test_drop_duplicates_null_in_object_column(nulls_fixture):
+ # https://github.com/pandas-dev/pandas/issues/32992
+ df = DataFrame([[1, nulls_fixture], [2, "a"]], dtype=object)
+ result = df.drop_duplicates()
+ tm.assert_frame_equal(result, df)
| - [ ] closes #32992
- [ ] 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/33751 | 2020-04-23T19:49:07Z | 2020-04-24T22:25:24Z | 2020-04-24T22:25:23Z | 2020-04-25T09:14:57Z |
CLN: Remove is_null_period | diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index bbb4d562b8971..a312fdc6cda22 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -67,7 +67,11 @@ cimport pandas._libs.util as util
from pandas._libs.util cimport is_nan, UINT64_MAX, INT64_MAX, INT64_MIN
from pandas._libs.tslib import array_to_datetime
-from pandas._libs.tslibs.nattype cimport NPY_NAT, c_NaT as NaT
+from pandas._libs.tslibs.nattype cimport (
+ NPY_NAT,
+ c_NaT as NaT,
+ checknull_with_nat,
+)
from pandas._libs.tslibs.conversion cimport convert_to_tsobject
from pandas._libs.tslibs.timedeltas cimport convert_to_timedelta64
from pandas._libs.tslibs.timezones cimport get_timezone, tz_compare
@@ -77,7 +81,6 @@ from pandas._libs.missing cimport (
isnaobj,
is_null_datetime64,
is_null_timedelta64,
- is_null_period,
C_NA,
)
@@ -1844,7 +1847,7 @@ cdef class PeriodValidator(TemporalValidator):
return util.is_period_object(value)
cdef inline bint is_valid_null(self, object value) except -1:
- return is_null_period(value)
+ return checknull_with_nat(value)
cpdef bint is_period_array(ndarray values):
diff --git a/pandas/_libs/missing.pxd b/pandas/_libs/missing.pxd
index 5ab42a736712f..b32492c1a83fc 100644
--- a/pandas/_libs/missing.pxd
+++ b/pandas/_libs/missing.pxd
@@ -6,7 +6,6 @@ cpdef ndarray[uint8_t] isnaobj(ndarray arr)
cdef bint is_null_datetime64(v)
cdef bint is_null_timedelta64(v)
-cdef bint is_null_period(v)
cdef class C_NAType:
pass
diff --git a/pandas/_libs/missing.pyx b/pandas/_libs/missing.pyx
index dacf454824190..490abdf473319 100644
--- a/pandas/_libs/missing.pyx
+++ b/pandas/_libs/missing.pyx
@@ -40,6 +40,7 @@ cpdef bint checknull(object val):
- NaT
- np.datetime64 representation of NaT
- np.timedelta64 representation of NaT
+ - NA
Parameters
----------
@@ -278,12 +279,6 @@ cdef inline bint is_null_timedelta64(v):
return False
-cdef inline bint is_null_period(v):
- # determine if we have a null for a Period (or integer versions),
- # excluding np.datetime64('nat') and np.timedelta64('nat')
- return checknull_with_nat(v)
-
-
# -----------------------------------------------------------------------------
# Implementation of NA singleton
| is_null_period seems only to be an alias for checknull_with_nat so I think it can be removed? | https://api.github.com/repos/pandas-dev/pandas/pulls/33750 | 2020-04-23T17:18:22Z | 2020-04-23T18:56:18Z | 2020-04-23T18:56:18Z | 2020-04-23T18:58:56Z |
BUG: Fix mixed datetime dtype inference | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 88bf0e005a221..16426e11c5a24 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -759,6 +759,7 @@ Datetimelike
- Bug in :meth:`DatetimeIndex.to_period` not infering the frequency when called with no arguments (:issue:`33358`)
- Bug in :meth:`DatetimeIndex.tz_localize` incorrectly retaining ``freq`` in some cases where the original freq is no longer valid (:issue:`30511`)
- Bug in :meth:`DatetimeIndex.intersection` losing ``freq`` and timezone in some cases (:issue:`33604`)
+- Bug in :meth:`DatetimeIndex.get_indexer` where incorrect output would be returned for mixed datetime-like targets (:issue:`33741`)
- Bug in :class:`DatetimeIndex` addition and subtraction with some types of :class:`DateOffset` objects incorrectly retaining an invalid ``freq`` attribute (:issue:`33779`)
- Bug in :class:`DatetimeIndex` where setting the ``freq`` attribute on an index could silently change the ``freq`` attribute on another index viewing the same data (:issue:`33552`)
- :meth:`DataFrame.min`/:meth:`DataFrame.max` not returning consistent result with :meth:`Series.min`/:meth:`Series.max` when called on objects initialized with empty :func:`pd.to_datetime`
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index 222b7af4e4b1c..ea97bab2198eb 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -1380,8 +1380,10 @@ def infer_dtype(value: object, skipna: bool = True) -> str:
return "mixed-integer"
elif PyDateTime_Check(val):
- if is_datetime_array(values):
+ if is_datetime_array(values, skipna=skipna):
return "datetime"
+ elif is_date_array(values, skipna=skipna):
+ return "date"
elif PyDate_Check(val):
if is_date_array(values, skipna=skipna):
@@ -1752,10 +1754,10 @@ cdef class DatetimeValidator(TemporalValidator):
return is_null_datetime64(value)
-cpdef bint is_datetime_array(ndarray values):
+cpdef bint is_datetime_array(ndarray values, bint skipna=True):
cdef:
DatetimeValidator validator = DatetimeValidator(len(values),
- skipna=True)
+ skipna=skipna)
return validator.validate(values)
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index fb266b4abba51..746fd140e48a1 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -4701,7 +4701,10 @@ def _maybe_promote(self, other: "Index"):
"""
if self.inferred_type == "date" and isinstance(other, ABCDatetimeIndex):
- return type(other)(self), other
+ try:
+ return type(other)(self), other
+ except OutOfBoundsDatetime:
+ return self, other
elif self.inferred_type == "timedelta" and isinstance(other, ABCTimedeltaIndex):
# TODO: we dont have tests that get here
return type(other)(self), other
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py
index 4c4a5547247fc..e97716f7a5e9c 100644
--- a/pandas/tests/dtypes/test_inference.py
+++ b/pandas/tests/dtypes/test_inference.py
@@ -1106,6 +1106,21 @@ def test_date(self):
result = lib.infer_dtype(dates, skipna=True)
assert result == "date"
+ @pytest.mark.parametrize(
+ "values",
+ [
+ [date(2020, 1, 1), pd.Timestamp("2020-01-01")],
+ [pd.Timestamp("2020-01-01"), date(2020, 1, 1)],
+ [date(2020, 1, 1), pd.NaT],
+ [pd.NaT, date(2020, 1, 1)],
+ ],
+ )
+ @pytest.mark.parametrize("skipna", [True, False])
+ def test_infer_dtype_date_order_invariant(self, values, skipna):
+ # https://github.com/pandas-dev/pandas/issues/33741
+ result = lib.infer_dtype(values, skipna=skipna)
+ assert result == "date"
+
def test_is_numeric_array(self):
assert lib.is_float_array(np.array([1, 2.0]))
diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py
index 097ee20534e4e..f08472fe72631 100644
--- a/pandas/tests/indexes/datetimes/test_indexing.py
+++ b/pandas/tests/indexes/datetimes/test_indexing.py
@@ -1,4 +1,4 @@
-from datetime import datetime, time, timedelta
+from datetime import date, datetime, time, timedelta
import numpy as np
import pytest
@@ -575,6 +575,38 @@ def test_get_indexer(self):
with pytest.raises(ValueError, match="abbreviation w/o a number"):
idx.get_indexer(idx[[0]], method="nearest", tolerance="foo")
+ @pytest.mark.parametrize(
+ "target",
+ [
+ [date(2020, 1, 1), pd.Timestamp("2020-01-02")],
+ [pd.Timestamp("2020-01-01"), date(2020, 1, 2)],
+ ],
+ )
+ def test_get_indexer_mixed_dtypes(self, target):
+ # https://github.com/pandas-dev/pandas/issues/33741
+ values = pd.DatetimeIndex(
+ [pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")]
+ )
+ result = values.get_indexer(target)
+ expected = np.array([0, 1], dtype=np.intp)
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "target, positions",
+ [
+ ([date(9999, 1, 1), pd.Timestamp("2020-01-01")], [-1, 0]),
+ ([pd.Timestamp("2020-01-01"), date(9999, 1, 1)], [0, -1]),
+ ([date(9999, 1, 1), date(9999, 1, 1)], [-1, -1]),
+ ],
+ )
+ def test_get_indexer_out_of_bounds_date(self, target, positions):
+ values = pd.DatetimeIndex(
+ [pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")]
+ )
+ result = values.get_indexer(target)
+ expected = np.array(positions, dtype=np.intp)
+ tm.assert_numpy_array_equal(result, expected)
+
class TestMaybeCastSliceBound:
def test_maybe_cast_slice_bounds_empty(self):
| - [x] closes #33741
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/33749 | 2020-04-23T17:16:03Z | 2020-06-01T00:28:41Z | 2020-06-01T00:28:41Z | 2020-06-01T00:29:55Z |
BUG: support skew function for custom BaseIndexer rolling windows | diff --git a/doc/source/user_guide/computation.rst b/doc/source/user_guide/computation.rst
index d7d025981f2f4..f9c07df956341 100644
--- a/doc/source/user_guide/computation.rst
+++ b/doc/source/user_guide/computation.rst
@@ -318,8 +318,8 @@ We provide a number of common statistical functions:
:meth:`~Rolling.kurt`, Sample kurtosis (4th moment)
:meth:`~Rolling.quantile`, Sample quantile (value at %)
:meth:`~Rolling.apply`, Generic apply
- :meth:`~Rolling.cov`, Unbiased covariance (binary)
- :meth:`~Rolling.corr`, Correlation (binary)
+ :meth:`~Rolling.cov`, Sample covariance (binary)
+ :meth:`~Rolling.corr`, Sample correlation (binary)
.. _computation.window_variance.caveats:
@@ -341,6 +341,8 @@ We provide a number of common statistical functions:
sample variance under the circumstances would result in a biased estimator
of the variable we are trying to determine.
+ The same caveats apply to using any supported statistical sample methods.
+
.. _stats.rolling_apply:
Rolling apply
@@ -870,12 +872,12 @@ Method summary
:meth:`~Expanding.max`, Maximum
:meth:`~Expanding.std`, Sample standard deviation
:meth:`~Expanding.var`, Sample variance
- :meth:`~Expanding.skew`, Unbiased skewness (3rd moment)
- :meth:`~Expanding.kurt`, Unbiased kurtosis (4th moment)
+ :meth:`~Expanding.skew`, Sample skewness (3rd moment)
+ :meth:`~Expanding.kurt`, Sample kurtosis (4th moment)
:meth:`~Expanding.quantile`, Sample quantile (value at %)
:meth:`~Expanding.apply`, Generic apply
- :meth:`~Expanding.cov`, Unbiased covariance (binary)
- :meth:`~Expanding.corr`, Correlation (binary)
+ :meth:`~Expanding.cov`, Sample covariance (binary)
+ :meth:`~Expanding.corr`, Sample correlation (binary)
.. note::
@@ -884,6 +886,8 @@ Method summary
windows. See :ref:`this section <computation.window_variance.caveats>` for more
information.
+ The same caveats apply to using any supported statistical sample methods.
+
.. currentmodule:: pandas
Aside from not having a ``window`` parameter, these functions have the same
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index e8fdaf0ae5d49..34f27c31febef 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -175,8 +175,8 @@ Other API changes
- Added :meth:`DataFrame.value_counts` (:issue:`5377`)
- :meth:`Groupby.groups` now returns an abbreviated representation when called on large dataframes (:issue:`1135`)
- ``loc`` lookups with an object-dtype :class:`Index` and an integer key will now raise ``KeyError`` instead of ``TypeError`` when key is missing (:issue:`31905`)
-- Using a :func:`pandas.api.indexers.BaseIndexer` with ``skew``, ``cov``, ``corr`` will now raise a ``NotImplementedError`` (:issue:`32865`)
-- Using a :func:`pandas.api.indexers.BaseIndexer` with ``count``, ``min``, ``max``, ``median`` will now return correct results for any monotonic :func:`pandas.api.indexers.BaseIndexer` descendant (:issue:`32865`)
+- Using a :func:`pandas.api.indexers.BaseIndexer` with ``cov``, ``corr`` will now raise a ``NotImplementedError`` (:issue:`32865`)
+- Using a :func:`pandas.api.indexers.BaseIndexer` with ``count``, ``min``, ``max``, ``median``, ``skew`` will now return correct results for any monotonic :func:`pandas.api.indexers.BaseIndexer` descendant (:issue:`32865`)
- Added a :func:`pandas.api.indexers.FixedForwardWindowIndexer` class to support forward-looking windows during ``rolling`` operations.
-
diff --git a/pandas/core/window/common.py b/pandas/core/window/common.py
index 8707893dc20cf..082c2f533f3de 100644
--- a/pandas/core/window/common.py
+++ b/pandas/core/window/common.py
@@ -337,6 +337,7 @@ def validate_baseindexer_support(func_name: Optional[str]) -> None:
"median",
"std",
"var",
+ "skew",
"kurt",
"quantile",
}
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index 3b14921528890..cdd61edba57ce 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -471,13 +471,13 @@ def _apply(
def calc(x):
x = np.concatenate((x, additional_nans))
- if not isinstance(window, BaseIndexer):
+ if not isinstance(self.window, BaseIndexer):
min_periods = calculate_min_periods(
window, self.min_periods, len(x), require_min_periods, floor
)
else:
min_periods = calculate_min_periods(
- self.min_periods or 1,
+ window_indexer.window_size,
self.min_periods,
len(x),
require_min_periods,
diff --git a/pandas/tests/window/test_base_indexer.py b/pandas/tests/window/test_base_indexer.py
index aee47a085eb9c..15e6a904dd11a 100644
--- a/pandas/tests/window/test_base_indexer.py
+++ b/pandas/tests/window/test_base_indexer.py
@@ -82,7 +82,7 @@ def get_window_bounds(self, num_values, min_periods, center, closed):
df.rolling(indexer, win_type="boxcar")
-@pytest.mark.parametrize("func", ["skew", "cov", "corr"])
+@pytest.mark.parametrize("func", ["cov", "corr"])
def test_notimplemented_functions(func):
# GH 32865
class CustomIndexer(BaseIndexer):
@@ -184,3 +184,29 @@ def test_rolling_forward_window(constructor, func, np_func, expected, np_kwargs)
result3 = getattr(rolling3, func)()
expected3 = constructor(rolling3.apply(lambda x: np_func(x, **np_kwargs)))
tm.assert_equal(result3, expected3)
+
+
+@pytest.mark.parametrize("constructor", [Series, DataFrame])
+def test_rolling_forward_skewness(constructor):
+ values = np.arange(10)
+ values[5] = 100.0
+
+ indexer = FixedForwardWindowIndexer(window_size=5)
+ rolling = constructor(values).rolling(window=indexer, min_periods=3)
+ result = rolling.skew()
+
+ expected = constructor(
+ [
+ 0.0,
+ 2.232396,
+ 2.229508,
+ 2.228340,
+ 2.229091,
+ 2.231989,
+ 0.0,
+ 0.0,
+ np.nan,
+ np.nan,
+ ]
+ )
+ tm.assert_equal(result, expected)
| - [X] xref #32865
- [X] 1 tests added / 1 passed
- [X] passes `black pandas`
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [X] whatsnew entry
## Scope of PR
This PR does a couple things to fix the performance of `skew`, and this also fixes the behavior of all the functions that have `require_min_periods` for small values of `min_periods`:
* clarify docs. Name all sample methods uniformly, add a note to the caveat that users should in general be careful about using sample methods with windows
* fix bug in `_apply` that made us never go into the `BaseIndexer` control flow branch
* fix bug in `_apply`: pass `window_indexer.window_size` into `calc_min_periods` instead of `min_periods or 1`. We want the custom indexer window size there, so it's not clear to me why we were passing `min_periods or 1` .
## Details
The algorithm itself is robust, but it defaults to sample skewness, which is why there was a difference between its output and `numpy`. To prevent misunderstandings, I clarified the docs a bit.
We were also passing a wrong value to `calc_min_periods`, and we weren't going into the proper if branch, because we were checking the type of `window` instead of `self.window`.
## Background on the wider issue
We currently don't support several rolling window functions when building a rolling window object using a custom class descended from `pandas.api.indexers.Baseindexer`. The implementations were written with backward-looking windows in mind, and this led to these functions breaking.
Currently, using these functions returns a `NotImplemented` error thanks to #33057, but ideally we want to update the implementations, so that they will work without a performance hit. This is what I aim to do over a series of PRs.
## Perf notes
No changes to algorithms.
| https://api.github.com/repos/pandas-dev/pandas/pulls/33745 | 2020-04-23T09:53:20Z | 2020-04-25T22:03:14Z | 2020-04-25T22:03:14Z | 2020-04-26T06:01:34Z |
PERF: fix #32976 slow group by for categorical columns | diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py
index 5ffda03fad80f..7c127b90c181c 100644
--- a/asv_bench/benchmarks/groupby.py
+++ b/asv_bench/benchmarks/groupby.py
@@ -6,6 +6,7 @@
from pandas import (
Categorical,
+ CategoricalDtype,
DataFrame,
MultiIndex,
Series,
@@ -473,6 +474,7 @@ def time_sum(self):
class Categories:
+ # benchmark grouping by categoricals
def setup(self):
N = 10 ** 5
arr = np.random.random(N)
@@ -510,6 +512,33 @@ def time_groupby_extra_cat_nosort(self):
self.df_extra_cat.groupby("a", sort=False)["b"].count()
+class CategoricalFrame:
+ # benchmark grouping with operations on categorical values (GH #32976)
+ param_names = ["groupby_type", "value_type", "agg_method"]
+ params = [(int,), (int, str), ("last", "head", "count")]
+
+ def setup(self, groupby_type, value_type, agg_method):
+ SIZE = 100000
+ GROUPS = 1000
+ CARDINALITY = 10
+ CAT = CategoricalDtype([value_type(i) for i in range(CARDINALITY)])
+ df = DataFrame(
+ {
+ "group": [
+ groupby_type(np.random.randint(0, GROUPS)) for i in range(SIZE)
+ ],
+ "cat": [np.random.choice(CAT.categories) for i in range(SIZE)],
+ }
+ )
+ self.df_cat_values = df.astype({"cat": CAT})
+
+ def time_groupby(self, groupby_type, value_type, agg_method):
+ getattr(self.df_cat_values.groupby("group"), agg_method)()
+
+ def time_groupby_ordered(self, groupby_type, value_type, agg_method):
+ getattr(self.df_cat_values.groupby("group", sort=True), agg_method)()
+
+
class Datelike:
# GH 14338
params = ["period_range", "date_range", "date_range_tz"]
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index b16ca0a80c5b4..122a4b76ff0be 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -40,6 +40,7 @@ Deprecations
Performance improvements
~~~~~~~~~~~~~~~~~~~~~~~~
+- Performance improvement in :meth:`DataFrame.groupby` when aggregating categorical data (:issue:`32976`)
-
-
@@ -132,6 +133,7 @@ Plotting
Groupby/resample/rolling
^^^^^^^^^^^^^^^^^^^^^^^^
+- :meth:`DataFrame.groupby` aggregations of categorical series will now return a :class:`Categorical` while preserving the codes and categories of the original series (:issue:`33739`)
-
-
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 3aaeef3b63760..d2e8f2023e7bc 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -40,6 +40,7 @@
from pandas.core.dtypes.missing import _maybe_fill, isna
import pandas.core.algorithms as algorithms
+from pandas.core.arrays.categorical import Categorical
from pandas.core.base import SelectionMixin
import pandas.core.common as com
from pandas.core.frame import DataFrame
@@ -356,6 +357,29 @@ def get_group_levels(self) -> List[Index]:
_name_functions = {"ohlc": ["open", "high", "low", "close"]}
+ _cat_method_blacklist = (
+ "add",
+ "median",
+ "prod",
+ "sem",
+ "cumsum",
+ "sum",
+ "cummin",
+ "mean",
+ "max",
+ "skew",
+ "cumprod",
+ "cummax",
+ "rank",
+ "pct_change",
+ "min",
+ "var",
+ "mad",
+ "describe",
+ "std",
+ "quantile",
+ )
+
def _is_builtin_func(self, arg):
"""
if we define a builtin function for this argument, return it,
@@ -460,7 +484,7 @@ def _cython_operation(
# categoricals are only 1d, so we
# are not setup for dim transforming
- if is_categorical_dtype(values.dtype) or is_sparse(values.dtype):
+ if is_sparse(values.dtype):
raise NotImplementedError(f"{values.dtype} dtype not supported")
elif is_datetime64_any_dtype(values.dtype):
if how in ["add", "prod", "cumsum", "cumprod"]:
@@ -481,6 +505,7 @@ def _cython_operation(
is_datetimelike = needs_i8_conversion(values.dtype)
is_numeric = is_numeric_dtype(values.dtype)
+ is_categorical = is_categorical_dtype(values)
if is_datetimelike:
values = values.view("int64")
@@ -496,6 +521,17 @@ def _cython_operation(
values = ensure_int_or_float(values)
elif is_numeric and not is_complex_dtype(values):
values = ensure_float64(values)
+ elif is_categorical:
+ if how in self._cat_method_blacklist:
+ raise NotImplementedError(
+ f"{values.dtype} dtype not supported for `how` argument {how}"
+ )
+ values, categories, ordered = (
+ values.codes.astype(np.int64),
+ values.categories,
+ values.ordered,
+ )
+ is_numeric = True
else:
values = values.astype(object)
@@ -572,6 +608,11 @@ def _cython_operation(
result = type(orig_values)(result.astype(np.int64), dtype=orig_values.dtype)
elif is_datetimelike and kind == "aggregate":
result = result.astype(orig_values.dtype)
+ elif is_categorical:
+ # re-create categories
+ result = Categorical.from_codes(
+ result, categories=categories, ordered=ordered,
+ )
if is_extension_array_dtype(orig_values.dtype):
result = maybe_cast_result(result=result, obj=orig_values, how=how)
diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py
index 0d447a70b540d..887e349fa51d5 100644
--- a/pandas/tests/groupby/test_categorical.py
+++ b/pandas/tests/groupby/test_categorical.py
@@ -1505,7 +1505,9 @@ def test_groupy_first_returned_categorical_instead_of_dataframe(func):
)
df_grouped = df.groupby("A")["B"]
result = getattr(df_grouped, func)()
- expected = pd.Series(["b"], index=pd.Index([1997], name="A"), name="B")
+ expected = pd.Series(
+ ["b"], index=pd.Index([1997], name="A"), name="B", dtype="category"
+ ).cat.as_ordered()
tm.assert_series_equal(result, expected)
@@ -1574,7 +1576,7 @@ def test_agg_cython_category_not_implemented_fallback():
result = df.groupby("col_num").col_cat.first()
expected = pd.Series(
[1, 2, 3], index=pd.Index([1, 2, 3], name="col_num"), name="col_cat"
- )
+ ).astype("category")
tm.assert_series_equal(result, expected)
result = df.groupby("col_num").agg({"col_cat": "first"})
| Aggregate categorical codes with fast cython aggregation for select `how` operations. Added new ASV benchmark copied from 32976 indicating > 99% improvement in performance for this case.
- [x] closes #32976
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/33739 | 2020-04-23T04:05:52Z | 2020-11-06T01:53:02Z | null | 2020-11-06T01:53:02Z |
TST: fix tests for asserting matching freq | diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
index fd23e95106ab0..c0e1eeb8f4eec 100644
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -393,6 +393,9 @@ def test_numpy_repeat(self):
@pytest.mark.parametrize("klass", [list, tuple, np.array, Series])
def test_where(self, klass):
i = self.create_index()
+ if isinstance(i, (pd.DatetimeIndex, pd.TimedeltaIndex)):
+ # where does not preserve freq
+ i._set_freq(None)
cond = [True] * len(i)
result = i.where(klass(cond))
diff --git a/pandas/tests/indexes/datetimelike.py b/pandas/tests/indexes/datetimelike.py
index 85d670e9dbffa..944358b1540b0 100644
--- a/pandas/tests/indexes/datetimelike.py
+++ b/pandas/tests/indexes/datetimelike.py
@@ -81,8 +81,8 @@ def test_map_dictlike(self, mapper):
expected = index + index.freq
# don't compare the freqs
- if isinstance(expected, pd.DatetimeIndex):
- expected._data.freq = None
+ if isinstance(expected, (pd.DatetimeIndex, pd.TimedeltaIndex)):
+ expected._set_freq(None)
result = index.map(mapper(expected, index))
tm.assert_index_equal(result, expected)
diff --git a/pandas/tests/indexes/datetimes/test_astype.py b/pandas/tests/indexes/datetimes/test_astype.py
index 34169a670c169..a299f03c5ebad 100644
--- a/pandas/tests/indexes/datetimes/test_astype.py
+++ b/pandas/tests/indexes/datetimes/test_astype.py
@@ -88,6 +88,7 @@ def test_astype_with_tz(self):
result = idx.astype("datetime64[ns, US/Eastern]")
expected = date_range("20170101 03:00:00", periods=4, tz="US/Eastern")
tm.assert_index_equal(result, expected)
+ assert result.freq == expected.freq
# GH 18951: tz-naive to tz-aware
idx = date_range("20170101", periods=4)
diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py
index 0247947ff19c5..a8e08bbe9a2e9 100644
--- a/pandas/tests/indexes/datetimes/test_constructors.py
+++ b/pandas/tests/indexes/datetimes/test_constructors.py
@@ -131,6 +131,7 @@ def test_construction_with_alt(self, kwargs, tz_aware_fixture):
def test_construction_with_alt_tz_localize(self, kwargs, tz_aware_fixture):
tz = tz_aware_fixture
i = pd.date_range("20130101", periods=5, freq="H", tz=tz)
+ i._set_freq(None)
kwargs = {key: attrgetter(val)(i) for key, val in kwargs.items()}
if "tz" in kwargs:
@@ -703,7 +704,9 @@ def test_constructor_start_end_with_tz(self, tz):
end = Timestamp("2013-01-02 06:00:00", tz="America/Los_Angeles")
result = date_range(freq="D", start=start, end=end, tz=tz)
expected = DatetimeIndex(
- ["2013-01-01 06:00:00", "2013-01-02 06:00:00"], tz="America/Los_Angeles"
+ ["2013-01-01 06:00:00", "2013-01-02 06:00:00"],
+ tz="America/Los_Angeles",
+ freq="D",
)
tm.assert_index_equal(result, expected)
# Especially assert that the timezone is consistent for pytz
diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py
index b8200bb686aad..6ddbe4a5ce0a5 100644
--- a/pandas/tests/indexes/datetimes/test_date_range.py
+++ b/pandas/tests/indexes/datetimes/test_date_range.py
@@ -218,7 +218,7 @@ def test_date_range_normalize(self):
rng = date_range(snap, periods=n, normalize=False, freq="2D")
offset = timedelta(2)
- values = DatetimeIndex([snap + i * offset for i in range(n)])
+ values = DatetimeIndex([snap + i * offset for i in range(n)], freq=offset)
tm.assert_index_equal(rng, values)
@@ -413,7 +413,7 @@ def test_construct_over_dst(self):
pre_dst,
pst_dst,
]
- expected = DatetimeIndex(expect_data)
+ expected = DatetimeIndex(expect_data, freq="H")
result = date_range(start="2010-11-7", periods=3, freq="H", tz="US/Pacific")
tm.assert_index_equal(result, expected)
@@ -427,7 +427,8 @@ def test_construct_with_different_start_end_string_format(self):
Timestamp("2013-01-01 00:00:00+09:00"),
Timestamp("2013-01-01 01:00:00+09:00"),
Timestamp("2013-01-01 02:00:00+09:00"),
- ]
+ ],
+ freq="H",
)
tm.assert_index_equal(result, expected)
@@ -442,7 +443,7 @@ def test_range_bug(self):
result = date_range("2011-1-1", "2012-1-31", freq=offset)
start = datetime(2011, 1, 1)
- expected = DatetimeIndex([start + i * offset for i in range(5)])
+ expected = DatetimeIndex([start + i * offset for i in range(5)], freq=offset)
tm.assert_index_equal(result, expected)
def test_range_tz_pytz(self):
@@ -861,6 +862,7 @@ def test_bdays_and_open_boundaries(self, closed):
bday_end = "2018-07-27" # Friday
expected = pd.date_range(bday_start, bday_end, freq="D")
tm.assert_index_equal(result, expected)
+ # Note: we do _not_ expect the freqs to match here
def test_bday_near_overflow(self):
# GH#24252 avoid doing unnecessary addition that _would_ overflow
@@ -910,15 +912,19 @@ def test_daterange_bug_456(self):
def test_cdaterange(self):
result = bdate_range("2013-05-01", periods=3, freq="C")
- expected = DatetimeIndex(["2013-05-01", "2013-05-02", "2013-05-03"])
+ expected = DatetimeIndex(["2013-05-01", "2013-05-02", "2013-05-03"], freq="C")
tm.assert_index_equal(result, expected)
+ assert result.freq == expected.freq
def test_cdaterange_weekmask(self):
result = bdate_range(
"2013-05-01", periods=3, freq="C", weekmask="Sun Mon Tue Wed Thu"
)
- expected = DatetimeIndex(["2013-05-01", "2013-05-02", "2013-05-05"])
+ expected = DatetimeIndex(
+ ["2013-05-01", "2013-05-02", "2013-05-05"], freq=result.freq
+ )
tm.assert_index_equal(result, expected)
+ assert result.freq == expected.freq
# raise with non-custom freq
msg = (
@@ -930,8 +936,11 @@ def test_cdaterange_weekmask(self):
def test_cdaterange_holidays(self):
result = bdate_range("2013-05-01", periods=3, freq="C", holidays=["2013-05-01"])
- expected = DatetimeIndex(["2013-05-02", "2013-05-03", "2013-05-06"])
+ expected = DatetimeIndex(
+ ["2013-05-02", "2013-05-03", "2013-05-06"], freq=result.freq
+ )
tm.assert_index_equal(result, expected)
+ assert result.freq == expected.freq
# raise with non-custom freq
msg = (
@@ -949,8 +958,11 @@ def test_cdaterange_weekmask_and_holidays(self):
weekmask="Sun Mon Tue Wed Thu",
holidays=["2013-05-01"],
)
- expected = DatetimeIndex(["2013-05-02", "2013-05-05", "2013-05-06"])
+ expected = DatetimeIndex(
+ ["2013-05-02", "2013-05-05", "2013-05-06"], freq=result.freq
+ )
tm.assert_index_equal(result, expected)
+ assert result.freq == expected.freq
# raise with non-custom freq
msg = (
diff --git a/pandas/tests/indexes/period/test_astype.py b/pandas/tests/indexes/period/test_astype.py
index b286191623ebb..fa1617bdfaa52 100644
--- a/pandas/tests/indexes/period/test_astype.py
+++ b/pandas/tests/indexes/period/test_astype.py
@@ -143,18 +143,24 @@ def test_astype_array_fallback(self):
def test_period_astype_to_timestamp(self):
pi = PeriodIndex(["2011-01", "2011-02", "2011-03"], freq="M")
- exp = DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"])
- tm.assert_index_equal(pi.astype("datetime64[ns]"), exp)
+ exp = DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"], freq="MS")
+ res = pi.astype("datetime64[ns]")
+ tm.assert_index_equal(res, exp)
+ assert res.freq == exp.freq
exp = DatetimeIndex(["2011-01-31", "2011-02-28", "2011-03-31"])
exp = exp + Timedelta(1, "D") - Timedelta(1, "ns")
- tm.assert_index_equal(pi.astype("datetime64[ns]", how="end"), exp)
+ res = pi.astype("datetime64[ns]", how="end")
+ tm.assert_index_equal(res, exp)
+ assert res.freq == exp.freq
exp = DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"], tz="US/Eastern")
res = pi.astype("datetime64[ns, US/Eastern]")
- tm.assert_index_equal(pi.astype("datetime64[ns, US/Eastern]"), exp)
+ tm.assert_index_equal(res, exp)
+ assert res.freq == exp.freq
exp = DatetimeIndex(["2011-01-31", "2011-02-28", "2011-03-31"], tz="US/Eastern")
exp = exp + Timedelta(1, "D") - Timedelta(1, "ns")
res = pi.astype("datetime64[ns, US/Eastern]", how="end")
tm.assert_index_equal(res, exp)
+ assert res.freq == exp.freq
diff --git a/pandas/tests/indexes/period/test_to_timestamp.py b/pandas/tests/indexes/period/test_to_timestamp.py
index a7846d1864d40..c2328872aee1b 100644
--- a/pandas/tests/indexes/period/test_to_timestamp.py
+++ b/pandas/tests/indexes/period/test_to_timestamp.py
@@ -60,8 +60,9 @@ def test_to_timestamp_quarterly_bug(self):
pindex = PeriodIndex(year=years, quarter=quarters)
stamps = pindex.to_timestamp("D", "end")
- expected = DatetimeIndex([x.to_timestamp("D", "end") for x in pindex], freq="Q")
+ expected = DatetimeIndex([x.to_timestamp("D", "end") for x in pindex])
tm.assert_index_equal(stamps, expected)
+ assert stamps.freq == expected.freq
def test_to_timestamp_pi_mult(self):
idx = PeriodIndex(["2011-01", "NaT", "2011-02"], freq="2M", name="idx")
| xref #33711, #33712 | https://api.github.com/repos/pandas-dev/pandas/pulls/33737 | 2020-04-23T02:59:52Z | 2020-04-23T18:55:56Z | 2020-04-23T18:55:56Z | 2020-04-23T18:56:34Z |
REF: use _wrap_joined_index in PeriodIndex.join | diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index 3a721d8c8c320..cf653a6875a9c 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -2,7 +2,7 @@
Base and utility classes for tseries type pandas objects.
"""
from datetime import datetime
-from typing import Any, List, Optional, Union
+from typing import Any, List, Optional, Union, cast
import numpy as np
@@ -583,6 +583,22 @@ def delete(self, loc):
arr = type(self._data)._simple_new(new_i8s, dtype=self.dtype, freq=freq)
return type(self)._simple_new(arr, name=self.name)
+ # --------------------------------------------------------------------
+ # Join/Set Methods
+
+ def _wrap_joined_index(self, joined: np.ndarray, other):
+ assert other.dtype == self.dtype, (other.dtype, self.dtype)
+ name = get_op_result_name(self, other)
+
+ if is_period_dtype(self.dtype):
+ freq = self.freq
+ else:
+ self = cast(DatetimeTimedeltaMixin, self)
+ freq = self.freq if self._can_fast_union(other) else None
+ new_data = type(self._data)._simple_new(joined, dtype=self.dtype, freq=freq)
+
+ return type(self)._simple_new(new_data, name=name)
+
class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index):
"""
@@ -878,15 +894,6 @@ def _is_convertible_to_index_for_join(cls, other: Index) -> bool:
return True
return False
- def _wrap_joined_index(self, joined: np.ndarray, other):
- assert other.dtype == self.dtype, (other.dtype, self.dtype)
- name = get_op_result_name(self, other)
-
- freq = self.freq if self._can_fast_union(other) else None
- new_data = type(self._data)._simple_new(joined, dtype=self.dtype, freq=freq)
-
- return type(self)._simple_new(new_data, name=name)
-
# --------------------------------------------------------------------
# List-Like Methods
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py
index 56cb9e29761a6..957c01c2dca96 100644
--- a/pandas/core/indexes/period.py
+++ b/pandas/core/indexes/period.py
@@ -628,6 +628,7 @@ def join(self, other, how="left", level=None, return_indexers=False, sort=False)
other, how=how, level=level, return_indexers=return_indexers, sort=sort
)
+ # _assert_can_do_setop ensures we have matching dtype
result = Int64Index.join(
self,
other,
@@ -636,11 +637,7 @@ def join(self, other, how="left", level=None, return_indexers=False, sort=False)
return_indexers=return_indexers,
sort=sort,
)
-
- if return_indexers:
- result, lidx, ridx = result
- return self._apply_meta(result), lidx, ridx
- return self._apply_meta(result)
+ return result
# ------------------------------------------------------------------------
# Set Operation Methods
@@ -719,13 +716,6 @@ def _union(self, other, sort):
# ------------------------------------------------------------------------
- def _apply_meta(self, rawarr) -> "PeriodIndex":
- if not isinstance(rawarr, PeriodIndex):
- if not isinstance(rawarr, PeriodArray):
- rawarr = PeriodArray(rawarr, freq=self.freq)
- rawarr = PeriodIndex._simple_new(rawarr, name=self.name)
- return rawarr
-
def memory_usage(self, deep=False):
result = super().memory_usage(deep=deep)
if hasattr(self, "_cache") and "_int64index" in self._cache:
| PeriodIndex defines _apply_meta, but that is made unnecessary by implementing _wrap_joined_index correctly. | https://api.github.com/repos/pandas-dev/pandas/pulls/33736 | 2020-04-23T02:51:33Z | 2020-04-23T17:13:46Z | 2020-04-23T17:13:46Z | 2020-04-23T17:54:22Z |
REF: implement test_astype | diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py
new file mode 100644
index 0000000000000..dc779562b662d
--- /dev/null
+++ b/pandas/tests/frame/methods/test_astype.py
@@ -0,0 +1,562 @@
+import re
+
+import numpy as np
+import pytest
+
+from pandas import (
+ Categorical,
+ CategoricalDtype,
+ DataFrame,
+ DatetimeTZDtype,
+ IntervalDtype,
+ NaT,
+ Series,
+ Timedelta,
+ Timestamp,
+ UInt64Index,
+ _np_version_under1p14,
+ concat,
+ date_range,
+ option_context,
+)
+import pandas._testing as tm
+from pandas.core.arrays import integer_array
+
+
+def _check_cast(df, v):
+ """
+ Check if all dtypes of df are equal to v
+ """
+ assert all(s.dtype.name == v for _, s in df.items())
+
+
+class TestAstype:
+ def test_astype_float(self, float_frame):
+ casted = float_frame.astype(int)
+ expected = DataFrame(
+ float_frame.values.astype(int),
+ index=float_frame.index,
+ columns=float_frame.columns,
+ )
+ tm.assert_frame_equal(casted, expected)
+
+ casted = float_frame.astype(np.int32)
+ expected = DataFrame(
+ float_frame.values.astype(np.int32),
+ index=float_frame.index,
+ columns=float_frame.columns,
+ )
+ tm.assert_frame_equal(casted, expected)
+
+ float_frame["foo"] = "5"
+ casted = float_frame.astype(int)
+ expected = DataFrame(
+ float_frame.values.astype(int),
+ index=float_frame.index,
+ columns=float_frame.columns,
+ )
+ tm.assert_frame_equal(casted, expected)
+
+ def test_astype_mixed_float(self, mixed_float_frame):
+ # mixed casting
+ casted = mixed_float_frame.reindex(columns=["A", "B"]).astype("float32")
+ _check_cast(casted, "float32")
+
+ casted = mixed_float_frame.reindex(columns=["A", "B"]).astype("float16")
+ _check_cast(casted, "float16")
+
+ def test_astype_mixed_type(self, mixed_type_frame):
+ # mixed casting
+ mn = mixed_type_frame._get_numeric_data().copy()
+ mn["little_float"] = np.array(12345.0, dtype="float16")
+ mn["big_float"] = np.array(123456789101112.0, dtype="float64")
+
+ casted = mn.astype("float64")
+ _check_cast(casted, "float64")
+
+ casted = mn.astype("int64")
+ _check_cast(casted, "int64")
+
+ casted = mn.reindex(columns=["little_float"]).astype("float16")
+ _check_cast(casted, "float16")
+
+ casted = mn.astype("float32")
+ _check_cast(casted, "float32")
+
+ casted = mn.astype("int32")
+ _check_cast(casted, "int32")
+
+ # to object
+ casted = mn.astype("O")
+ _check_cast(casted, "object")
+
+ def test_astype_with_exclude_string(self, float_frame):
+ df = float_frame.copy()
+ expected = float_frame.astype(int)
+ df["string"] = "foo"
+ casted = df.astype(int, errors="ignore")
+
+ expected["string"] = "foo"
+ tm.assert_frame_equal(casted, expected)
+
+ df = float_frame.copy()
+ expected = float_frame.astype(np.int32)
+ df["string"] = "foo"
+ casted = df.astype(np.int32, errors="ignore")
+
+ expected["string"] = "foo"
+ tm.assert_frame_equal(casted, expected)
+
+ def test_astype_with_view_float(self, float_frame):
+
+ # this is the only real reason to do it this way
+ tf = np.round(float_frame).astype(np.int32)
+ casted = tf.astype(np.float32, copy=False)
+
+ # TODO(wesm): verification?
+ tf = float_frame.astype(np.float64)
+ casted = tf.astype(np.int64, copy=False) # noqa
+
+ def test_astype_with_view_mixed_float(self, mixed_float_frame):
+
+ tf = mixed_float_frame.reindex(columns=["A", "B", "C"])
+
+ casted = tf.astype(np.int64)
+ casted = tf.astype(np.float32) # noqa
+
+ @pytest.mark.parametrize("dtype", [np.int32, np.int64])
+ @pytest.mark.parametrize("val", [np.nan, np.inf])
+ def test_astype_cast_nan_inf_int(self, val, dtype):
+ # see GH#14265
+ #
+ # Check NaN and inf --> raise error when converting to int.
+ msg = "Cannot convert non-finite values \\(NA or inf\\) to integer"
+ df = DataFrame([val])
+
+ with pytest.raises(ValueError, match=msg):
+ df.astype(dtype)
+
+ def test_astype_str(self):
+ # see GH#9757
+ a = Series(date_range("2010-01-04", periods=5))
+ b = Series(date_range("3/6/2012 00:00", periods=5, tz="US/Eastern"))
+ c = Series([Timedelta(x, unit="d") for x in range(5)])
+ d = Series(range(5))
+ e = Series([0.0, 0.2, 0.4, 0.6, 0.8])
+
+ df = DataFrame({"a": a, "b": b, "c": c, "d": d, "e": e})
+
+ # Datetime-like
+ result = df.astype(str)
+
+ expected = DataFrame(
+ {
+ "a": list(map(str, map(lambda x: Timestamp(x)._date_repr, a._values))),
+ "b": list(map(str, map(Timestamp, b._values))),
+ "c": list(map(lambda x: Timedelta(x)._repr_base(), c._values)),
+ "d": list(map(str, d._values)),
+ "e": list(map(str, e._values)),
+ }
+ )
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_astype_str_float(self):
+ # see GH#11302
+ result = DataFrame([np.NaN]).astype(str)
+ expected = DataFrame(["nan"])
+
+ tm.assert_frame_equal(result, expected)
+ result = DataFrame([1.12345678901234567890]).astype(str)
+
+ # < 1.14 truncates
+ # >= 1.14 preserves the full repr
+ val = "1.12345678901" if _np_version_under1p14 else "1.1234567890123457"
+ expected = DataFrame([val])
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("dtype_class", [dict, Series])
+ def test_astype_dict_like(self, dtype_class):
+ # GH7271 & GH16717
+ a = Series(date_range("2010-01-04", periods=5))
+ b = Series(range(5))
+ c = Series([0.0, 0.2, 0.4, 0.6, 0.8])
+ d = Series(["1.0", "2", "3.14", "4", "5.4"])
+ df = DataFrame({"a": a, "b": b, "c": c, "d": d})
+ original = df.copy(deep=True)
+
+ # change type of a subset of columns
+ dt1 = dtype_class({"b": "str", "d": "float32"})
+ result = df.astype(dt1)
+ expected = DataFrame(
+ {
+ "a": a,
+ "b": Series(["0", "1", "2", "3", "4"]),
+ "c": c,
+ "d": Series([1.0, 2.0, 3.14, 4.0, 5.4], dtype="float32"),
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+ tm.assert_frame_equal(df, original)
+
+ dt2 = dtype_class({"b": np.float32, "c": "float32", "d": np.float64})
+ result = df.astype(dt2)
+ expected = DataFrame(
+ {
+ "a": a,
+ "b": Series([0.0, 1.0, 2.0, 3.0, 4.0], dtype="float32"),
+ "c": Series([0.0, 0.2, 0.4, 0.6, 0.8], dtype="float32"),
+ "d": Series([1.0, 2.0, 3.14, 4.0, 5.4], dtype="float64"),
+ }
+ )
+ tm.assert_frame_equal(result, expected)
+ tm.assert_frame_equal(df, original)
+
+ # change all columns
+ dt3 = dtype_class({"a": str, "b": str, "c": str, "d": str})
+ tm.assert_frame_equal(df.astype(dt3), df.astype(str))
+ tm.assert_frame_equal(df, original)
+
+ # error should be raised when using something other than column labels
+ # in the keys of the dtype dict
+ dt4 = dtype_class({"b": str, 2: str})
+ dt5 = dtype_class({"e": str})
+ msg = "Only a column name can be used for the key in a dtype mappings argument"
+ with pytest.raises(KeyError, match=msg):
+ df.astype(dt4)
+ with pytest.raises(KeyError, match=msg):
+ df.astype(dt5)
+ tm.assert_frame_equal(df, original)
+
+ # if the dtypes provided are the same as the original dtypes, the
+ # resulting DataFrame should be the same as the original DataFrame
+ dt6 = dtype_class({col: df[col].dtype for col in df.columns})
+ equiv = df.astype(dt6)
+ tm.assert_frame_equal(df, equiv)
+ tm.assert_frame_equal(df, original)
+
+ # GH#16717
+ # if dtypes provided is empty, the resulting DataFrame
+ # should be the same as the original DataFrame
+ dt7 = dtype_class({}) if dtype_class is dict else dtype_class({}, dtype=object)
+ equiv = df.astype(dt7)
+ tm.assert_frame_equal(df, equiv)
+ tm.assert_frame_equal(df, original)
+
+ def test_astype_duplicate_col(self):
+ a1 = Series([1, 2, 3, 4, 5], name="a")
+ b = Series([0.1, 0.2, 0.4, 0.6, 0.8], name="b")
+ a2 = Series([0, 1, 2, 3, 4], name="a")
+ df = concat([a1, b, a2], axis=1)
+
+ result = df.astype(str)
+ a1_str = Series(["1", "2", "3", "4", "5"], dtype="str", name="a")
+ b_str = Series(["0.1", "0.2", "0.4", "0.6", "0.8"], dtype=str, name="b")
+ a2_str = Series(["0", "1", "2", "3", "4"], dtype="str", name="a")
+ expected = concat([a1_str, b_str, a2_str], axis=1)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.astype({"a": "str"})
+ expected = concat([a1_str, b, a2_str], axis=1)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "dtype",
+ [
+ "category",
+ CategoricalDtype(),
+ CategoricalDtype(ordered=True),
+ CategoricalDtype(ordered=False),
+ CategoricalDtype(categories=list("abcdef")),
+ CategoricalDtype(categories=list("edba"), ordered=False),
+ CategoricalDtype(categories=list("edcb"), ordered=True),
+ ],
+ ids=repr,
+ )
+ def test_astype_categorical(self, dtype):
+ # GH#18099
+ d = {"A": list("abbc"), "B": list("bccd"), "C": list("cdde")}
+ df = DataFrame(d)
+ result = df.astype(dtype)
+ expected = DataFrame({k: Categorical(d[k], dtype=dtype) for k in d})
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("cls", [CategoricalDtype, DatetimeTZDtype, IntervalDtype])
+ def test_astype_categoricaldtype_class_raises(self, cls):
+ df = DataFrame({"A": ["a", "a", "b", "c"]})
+ xpr = f"Expected an instance of {cls.__name__}"
+ with pytest.raises(TypeError, match=xpr):
+ df.astype({"A": cls})
+
+ with pytest.raises(TypeError, match=xpr):
+ df["A"].astype(cls)
+
+ @pytest.mark.parametrize("dtype", ["Int64", "Int32", "Int16"])
+ def test_astype_extension_dtypes(self, dtype):
+ # GH#22578
+ df = DataFrame([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], columns=["a", "b"])
+
+ expected1 = DataFrame(
+ {
+ "a": integer_array([1, 3, 5], dtype=dtype),
+ "b": integer_array([2, 4, 6], dtype=dtype),
+ }
+ )
+ tm.assert_frame_equal(df.astype(dtype), expected1)
+ tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1)
+ tm.assert_frame_equal(df.astype(dtype).astype("float64"), df)
+
+ df = DataFrame([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], columns=["a", "b"])
+ df["b"] = df["b"].astype(dtype)
+ expected2 = DataFrame(
+ {"a": [1.0, 3.0, 5.0], "b": integer_array([2, 4, 6], dtype=dtype)}
+ )
+ tm.assert_frame_equal(df, expected2)
+
+ tm.assert_frame_equal(df.astype(dtype), expected1)
+ tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1)
+
+ @pytest.mark.parametrize("dtype", ["Int64", "Int32", "Int16"])
+ def test_astype_extension_dtypes_1d(self, dtype):
+ # GH#22578
+ df = DataFrame({"a": [1.0, 2.0, 3.0]})
+
+ expected1 = DataFrame({"a": integer_array([1, 2, 3], dtype=dtype)})
+ tm.assert_frame_equal(df.astype(dtype), expected1)
+ tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1)
+
+ df = DataFrame({"a": [1.0, 2.0, 3.0]})
+ df["a"] = df["a"].astype(dtype)
+ expected2 = DataFrame({"a": integer_array([1, 2, 3], dtype=dtype)})
+ tm.assert_frame_equal(df, expected2)
+
+ tm.assert_frame_equal(df.astype(dtype), expected1)
+ tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1)
+
+ @pytest.mark.parametrize("dtype", ["category", "Int64"])
+ def test_astype_extension_dtypes_duplicate_col(self, dtype):
+ # GH#24704
+ a1 = Series([0, np.nan, 4], name="a")
+ a2 = Series([np.nan, 3, 5], name="a")
+ df = concat([a1, a2], axis=1)
+
+ result = df.astype(dtype)
+ expected = concat([a1.astype(dtype), a2.astype(dtype)], axis=1)
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "dtype", [{100: "float64", 200: "uint64"}, "category", "float64"]
+ )
+ def test_astype_column_metadata(self, dtype):
+ # GH#19920
+ columns = UInt64Index([100, 200, 300], name="foo")
+ df = DataFrame(np.arange(15).reshape(5, 3), columns=columns)
+ df = df.astype(dtype)
+ tm.assert_index_equal(df.columns, columns)
+
+ @pytest.mark.parametrize("dtype", ["M8", "m8"])
+ @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"])
+ def test_astype_from_datetimelike_to_object(self, dtype, unit):
+ # tests astype to object dtype
+ # GH#19223 / GH#12425
+ dtype = f"{dtype}[{unit}]"
+ arr = np.array([[1, 2, 3]], dtype=dtype)
+ df = DataFrame(arr)
+ result = df.astype(object)
+ assert (result.dtypes == object).all()
+
+ if dtype.startswith("M8"):
+ assert result.iloc[0, 0] == Timestamp(1, unit=unit)
+ else:
+ assert result.iloc[0, 0] == Timedelta(1, unit=unit)
+
+ @pytest.mark.parametrize("arr_dtype", [np.int64, np.float64])
+ @pytest.mark.parametrize("dtype", ["M8", "m8"])
+ @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"])
+ def test_astype_to_datetimelike_unit(self, arr_dtype, dtype, unit):
+ # tests all units from numeric origination
+ # GH#19223 / GH#12425
+ dtype = f"{dtype}[{unit}]"
+ arr = np.array([[1, 2, 3]], dtype=arr_dtype)
+ df = DataFrame(arr)
+ result = df.astype(dtype)
+ expected = DataFrame(arr.astype(dtype))
+
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"])
+ def test_astype_to_datetime_unit(self, unit):
+ # tests all units from datetime origination
+ # GH#19223
+ dtype = f"M8[{unit}]"
+ arr = np.array([[1, 2, 3]], dtype=dtype)
+ df = DataFrame(arr)
+ result = df.astype(dtype)
+ expected = DataFrame(arr.astype(dtype))
+
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("unit", ["ns"])
+ def test_astype_to_timedelta_unit_ns(self, unit):
+ # preserver the timedelta conversion
+ # GH#19223
+ dtype = f"m8[{unit}]"
+ arr = np.array([[1, 2, 3]], dtype=dtype)
+ df = DataFrame(arr)
+ result = df.astype(dtype)
+ expected = DataFrame(arr.astype(dtype))
+
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("unit", ["us", "ms", "s", "h", "m", "D"])
+ def test_astype_to_timedelta_unit(self, unit):
+ # coerce to float
+ # GH#19223
+ dtype = f"m8[{unit}]"
+ arr = np.array([[1, 2, 3]], dtype=dtype)
+ df = DataFrame(arr)
+ result = df.astype(dtype)
+ expected = DataFrame(df.values.astype(dtype).astype(float))
+
+ tm.assert_frame_equal(result, expected)
+
+ @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"])
+ def test_astype_to_incorrect_datetimelike(self, unit):
+ # trying to astype a m to a M, or vice-versa
+ # GH#19224
+ dtype = f"M8[{unit}]"
+ other = f"m8[{unit}]"
+
+ df = DataFrame(np.array([[1, 2, 3]], dtype=dtype))
+ msg = (
+ fr"cannot astype a datetimelike from \[datetime64\[ns\]\] to "
+ fr"\[timedelta64\[{unit}\]\]"
+ )
+ with pytest.raises(TypeError, match=msg):
+ df.astype(other)
+
+ msg = (
+ fr"cannot astype a timedelta from \[timedelta64\[ns\]\] to "
+ fr"\[datetime64\[{unit}\]\]"
+ )
+ df = DataFrame(np.array([[1, 2, 3]], dtype=other))
+ with pytest.raises(TypeError, match=msg):
+ df.astype(dtype)
+
+ def test_astype_arg_for_errors(self):
+ # GH#14878
+
+ df = DataFrame([1, 2, 3])
+
+ msg = (
+ "Expected value of kwarg 'errors' to be one of "
+ "['raise', 'ignore']. Supplied value is 'True'"
+ )
+ with pytest.raises(ValueError, match=re.escape(msg)):
+ df.astype(np.float64, errors=True)
+
+ df.astype(np.int8, errors="ignore")
+
+ def test_astype_arg_for_errors_dictlist(self):
+ # GH#25905
+ df = DataFrame(
+ [
+ {"a": "1", "b": "16.5%", "c": "test"},
+ {"a": "2.2", "b": "15.3", "c": "another_test"},
+ ]
+ )
+ expected = DataFrame(
+ [
+ {"a": 1.0, "b": "16.5%", "c": "test"},
+ {"a": 2.2, "b": "15.3", "c": "another_test"},
+ ]
+ )
+ type_dict = {"a": "float64", "b": "float64", "c": "object"}
+
+ result = df.astype(dtype=type_dict, errors="ignore")
+
+ tm.assert_frame_equal(result, expected)
+
+ def test_astype_dt64tz(self, timezone_frame):
+ # astype
+ expected = np.array(
+ [
+ [
+ Timestamp("2013-01-01 00:00:00"),
+ Timestamp("2013-01-02 00:00:00"),
+ Timestamp("2013-01-03 00:00:00"),
+ ],
+ [
+ Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern"),
+ NaT,
+ Timestamp("2013-01-03 00:00:00-0500", tz="US/Eastern"),
+ ],
+ [
+ Timestamp("2013-01-01 00:00:00+0100", tz="CET"),
+ NaT,
+ Timestamp("2013-01-03 00:00:00+0100", tz="CET"),
+ ],
+ ],
+ dtype=object,
+ ).T
+ expected = DataFrame(
+ expected,
+ index=timezone_frame.index,
+ columns=timezone_frame.columns,
+ dtype=object,
+ )
+ result = timezone_frame.astype(object)
+ tm.assert_frame_equal(result, expected)
+
+ result = timezone_frame.astype("datetime64[ns]")
+ expected = DataFrame(
+ {
+ "A": date_range("20130101", periods=3),
+ "B": (
+ date_range("20130101", periods=3, tz="US/Eastern")
+ .tz_convert("UTC")
+ .tz_localize(None)
+ ),
+ "C": (
+ date_range("20130101", periods=3, tz="CET")
+ .tz_convert("UTC")
+ .tz_localize(None)
+ ),
+ }
+ )
+ expected.iloc[1, 1] = NaT
+ expected.iloc[1, 2] = NaT
+ tm.assert_frame_equal(result, expected)
+
+ def test_astype_dt64tz_to_str(self, timezone_frame):
+ # str formatting
+ result = timezone_frame.astype(str)
+ expected = DataFrame(
+ [
+ [
+ "2013-01-01",
+ "2013-01-01 00:00:00-05:00",
+ "2013-01-01 00:00:00+01:00",
+ ],
+ ["2013-01-02", "NaT", "NaT"],
+ [
+ "2013-01-03",
+ "2013-01-03 00:00:00-05:00",
+ "2013-01-03 00:00:00+01:00",
+ ],
+ ],
+ columns=timezone_frame.columns,
+ )
+ tm.assert_frame_equal(result, expected)
+
+ with option_context("display.max_columns", 20):
+ result = str(timezone_frame)
+ assert (
+ "0 2013-01-01 2013-01-01 00:00:00-05:00 2013-01-01 00:00:00+01:00"
+ ) in result
+ assert (
+ "1 2013-01-02 NaT NaT"
+ ) in result
+ assert (
+ "2 2013-01-03 2013-01-03 00:00:00-05:00 2013-01-03 00:00:00+01:00"
+ ) in result
diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py
index 27ebee4aaaccf..9d0c221923cda 100644
--- a/pandas/tests/frame/test_dtypes.py
+++ b/pandas/tests/frame/test_dtypes.py
@@ -1,26 +1,14 @@
from collections import OrderedDict
from datetime import timedelta
-import re
import numpy as np
import pytest
-from pandas.core.dtypes.dtypes import CategoricalDtype, DatetimeTZDtype, IntervalDtype
+from pandas.core.dtypes.dtypes import DatetimeTZDtype
import pandas as pd
-from pandas import (
- Categorical,
- DataFrame,
- Series,
- Timedelta,
- Timestamp,
- _np_version_under1p14,
- concat,
- date_range,
- option_context,
-)
+from pandas import DataFrame, Series, Timestamp, date_range, option_context
import pandas._testing as tm
-from pandas.core.arrays import integer_array
def _check_cast(df, v):
@@ -126,266 +114,6 @@ def test_dtypes_gh8722(self, float_string_frame):
result = df.dtypes
tm.assert_series_equal(result, Series({0: np.dtype("int64")}))
- def test_astype_float(self, float_frame):
- casted = float_frame.astype(int)
- expected = DataFrame(
- float_frame.values.astype(int),
- index=float_frame.index,
- columns=float_frame.columns,
- )
- tm.assert_frame_equal(casted, expected)
-
- casted = float_frame.astype(np.int32)
- expected = DataFrame(
- float_frame.values.astype(np.int32),
- index=float_frame.index,
- columns=float_frame.columns,
- )
- tm.assert_frame_equal(casted, expected)
-
- float_frame["foo"] = "5"
- casted = float_frame.astype(int)
- expected = DataFrame(
- float_frame.values.astype(int),
- index=float_frame.index,
- columns=float_frame.columns,
- )
- tm.assert_frame_equal(casted, expected)
-
- def test_astype_mixed_float(self, mixed_float_frame):
- # mixed casting
- casted = mixed_float_frame.reindex(columns=["A", "B"]).astype("float32")
- _check_cast(casted, "float32")
-
- casted = mixed_float_frame.reindex(columns=["A", "B"]).astype("float16")
- _check_cast(casted, "float16")
-
- def test_astype_mixed_type(self, mixed_type_frame):
- # mixed casting
- mn = mixed_type_frame._get_numeric_data().copy()
- mn["little_float"] = np.array(12345.0, dtype="float16")
- mn["big_float"] = np.array(123456789101112.0, dtype="float64")
-
- casted = mn.astype("float64")
- _check_cast(casted, "float64")
-
- casted = mn.astype("int64")
- _check_cast(casted, "int64")
-
- casted = mn.reindex(columns=["little_float"]).astype("float16")
- _check_cast(casted, "float16")
-
- casted = mn.astype("float32")
- _check_cast(casted, "float32")
-
- casted = mn.astype("int32")
- _check_cast(casted, "int32")
-
- # to object
- casted = mn.astype("O")
- _check_cast(casted, "object")
-
- def test_astype_with_exclude_string(self, float_frame):
- df = float_frame.copy()
- expected = float_frame.astype(int)
- df["string"] = "foo"
- casted = df.astype(int, errors="ignore")
-
- expected["string"] = "foo"
- tm.assert_frame_equal(casted, expected)
-
- df = float_frame.copy()
- expected = float_frame.astype(np.int32)
- df["string"] = "foo"
- casted = df.astype(np.int32, errors="ignore")
-
- expected["string"] = "foo"
- tm.assert_frame_equal(casted, expected)
-
- def test_astype_with_view_float(self, float_frame):
-
- # this is the only real reason to do it this way
- tf = np.round(float_frame).astype(np.int32)
- casted = tf.astype(np.float32, copy=False)
-
- # TODO(wesm): verification?
- tf = float_frame.astype(np.float64)
- casted = tf.astype(np.int64, copy=False) # noqa
-
- def test_astype_with_view_mixed_float(self, mixed_float_frame):
-
- tf = mixed_float_frame.reindex(columns=["A", "B", "C"])
-
- casted = tf.astype(np.int64)
- casted = tf.astype(np.float32) # noqa
-
- @pytest.mark.parametrize("dtype", [np.int32, np.int64])
- @pytest.mark.parametrize("val", [np.nan, np.inf])
- def test_astype_cast_nan_inf_int(self, val, dtype):
- # see gh-14265
- #
- # Check NaN and inf --> raise error when converting to int.
- msg = "Cannot convert non-finite values \\(NA or inf\\) to integer"
- df = DataFrame([val])
-
- with pytest.raises(ValueError, match=msg):
- df.astype(dtype)
-
- def test_astype_str(self):
- # see gh-9757
- a = Series(date_range("2010-01-04", periods=5))
- b = Series(date_range("3/6/2012 00:00", periods=5, tz="US/Eastern"))
- c = Series([Timedelta(x, unit="d") for x in range(5)])
- d = Series(range(5))
- e = Series([0.0, 0.2, 0.4, 0.6, 0.8])
-
- df = DataFrame({"a": a, "b": b, "c": c, "d": d, "e": e})
-
- # Datetime-like
- result = df.astype(str)
-
- expected = DataFrame(
- {
- "a": list(map(str, map(lambda x: Timestamp(x)._date_repr, a._values))),
- "b": list(map(str, map(Timestamp, b._values))),
- "c": list(map(lambda x: Timedelta(x)._repr_base(), c._values)),
- "d": list(map(str, d._values)),
- "e": list(map(str, e._values)),
- }
- )
-
- tm.assert_frame_equal(result, expected)
-
- def test_astype_str_float(self):
- # see gh-11302
- result = DataFrame([np.NaN]).astype(str)
- expected = DataFrame(["nan"])
-
- tm.assert_frame_equal(result, expected)
- result = DataFrame([1.12345678901234567890]).astype(str)
-
- # < 1.14 truncates
- # >= 1.14 preserves the full repr
- val = "1.12345678901" if _np_version_under1p14 else "1.1234567890123457"
- expected = DataFrame([val])
- tm.assert_frame_equal(result, expected)
-
- @pytest.mark.parametrize("dtype_class", [dict, Series])
- def test_astype_dict_like(self, dtype_class):
- # GH7271 & GH16717
- a = Series(date_range("2010-01-04", periods=5))
- b = Series(range(5))
- c = Series([0.0, 0.2, 0.4, 0.6, 0.8])
- d = Series(["1.0", "2", "3.14", "4", "5.4"])
- df = DataFrame({"a": a, "b": b, "c": c, "d": d})
- original = df.copy(deep=True)
-
- # change type of a subset of columns
- dt1 = dtype_class({"b": "str", "d": "float32"})
- result = df.astype(dt1)
- expected = DataFrame(
- {
- "a": a,
- "b": Series(["0", "1", "2", "3", "4"]),
- "c": c,
- "d": Series([1.0, 2.0, 3.14, 4.0, 5.4], dtype="float32"),
- }
- )
- tm.assert_frame_equal(result, expected)
- tm.assert_frame_equal(df, original)
-
- dt2 = dtype_class({"b": np.float32, "c": "float32", "d": np.float64})
- result = df.astype(dt2)
- expected = DataFrame(
- {
- "a": a,
- "b": Series([0.0, 1.0, 2.0, 3.0, 4.0], dtype="float32"),
- "c": Series([0.0, 0.2, 0.4, 0.6, 0.8], dtype="float32"),
- "d": Series([1.0, 2.0, 3.14, 4.0, 5.4], dtype="float64"),
- }
- )
- tm.assert_frame_equal(result, expected)
- tm.assert_frame_equal(df, original)
-
- # change all columns
- dt3 = dtype_class({"a": str, "b": str, "c": str, "d": str})
- tm.assert_frame_equal(df.astype(dt3), df.astype(str))
- tm.assert_frame_equal(df, original)
-
- # error should be raised when using something other than column labels
- # in the keys of the dtype dict
- dt4 = dtype_class({"b": str, 2: str})
- dt5 = dtype_class({"e": str})
- msg = "Only a column name can be used for the key in a dtype mappings argument"
- with pytest.raises(KeyError, match=msg):
- df.astype(dt4)
- with pytest.raises(KeyError, match=msg):
- df.astype(dt5)
- tm.assert_frame_equal(df, original)
-
- # if the dtypes provided are the same as the original dtypes, the
- # resulting DataFrame should be the same as the original DataFrame
- dt6 = dtype_class({col: df[col].dtype for col in df.columns})
- equiv = df.astype(dt6)
- tm.assert_frame_equal(df, equiv)
- tm.assert_frame_equal(df, original)
-
- # GH 16717
- # if dtypes provided is empty, the resulting DataFrame
- # should be the same as the original DataFrame
- dt7 = dtype_class({}) if dtype_class is dict else dtype_class({}, dtype=object)
- equiv = df.astype(dt7)
- tm.assert_frame_equal(df, equiv)
- tm.assert_frame_equal(df, original)
-
- def test_astype_duplicate_col(self):
- a1 = Series([1, 2, 3, 4, 5], name="a")
- b = Series([0.1, 0.2, 0.4, 0.6, 0.8], name="b")
- a2 = Series([0, 1, 2, 3, 4], name="a")
- df = concat([a1, b, a2], axis=1)
-
- result = df.astype(str)
- a1_str = Series(["1", "2", "3", "4", "5"], dtype="str", name="a")
- b_str = Series(["0.1", "0.2", "0.4", "0.6", "0.8"], dtype=str, name="b")
- a2_str = Series(["0", "1", "2", "3", "4"], dtype="str", name="a")
- expected = concat([a1_str, b_str, a2_str], axis=1)
- tm.assert_frame_equal(result, expected)
-
- result = df.astype({"a": "str"})
- expected = concat([a1_str, b, a2_str], axis=1)
- tm.assert_frame_equal(result, expected)
-
- @pytest.mark.parametrize(
- "dtype",
- [
- "category",
- CategoricalDtype(),
- CategoricalDtype(ordered=True),
- CategoricalDtype(ordered=False),
- CategoricalDtype(categories=list("abcdef")),
- CategoricalDtype(categories=list("edba"), ordered=False),
- CategoricalDtype(categories=list("edcb"), ordered=True),
- ],
- ids=repr,
- )
- def test_astype_categorical(self, dtype):
- # GH 18099
- d = {"A": list("abbc"), "B": list("bccd"), "C": list("cdde")}
- df = DataFrame(d)
- result = df.astype(dtype)
- expected = DataFrame({k: Categorical(d[k], dtype=dtype) for k in d})
- tm.assert_frame_equal(result, expected)
-
- @pytest.mark.parametrize("cls", [CategoricalDtype, DatetimeTZDtype, IntervalDtype])
- def test_astype_categoricaldtype_class_raises(self, cls):
- df = DataFrame({"A": ["a", "a", "b", "c"]})
- xpr = f"Expected an instance of {cls.__name__}"
- with pytest.raises(TypeError, match=xpr):
- df.astype({"A": cls})
-
- with pytest.raises(TypeError, match=xpr):
- df["A"].astype(cls)
-
def test_singlerow_slice_categoricaldtype_gives_series(self):
# GH29521
df = pd.DataFrame({"x": pd.Categorical("a b c d e".split())})
@@ -395,158 +123,6 @@ def test_singlerow_slice_categoricaldtype_gives_series(self):
tm.assert_series_equal(result, expected)
- @pytest.mark.parametrize("dtype", ["Int64", "Int32", "Int16"])
- def test_astype_extension_dtypes(self, dtype):
- # GH 22578
- df = pd.DataFrame([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], columns=["a", "b"])
-
- expected1 = pd.DataFrame(
- {
- "a": integer_array([1, 3, 5], dtype=dtype),
- "b": integer_array([2, 4, 6], dtype=dtype),
- }
- )
- tm.assert_frame_equal(df.astype(dtype), expected1)
- tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1)
- tm.assert_frame_equal(df.astype(dtype).astype("float64"), df)
-
- df = pd.DataFrame([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], columns=["a", "b"])
- df["b"] = df["b"].astype(dtype)
- expected2 = pd.DataFrame(
- {"a": [1.0, 3.0, 5.0], "b": integer_array([2, 4, 6], dtype=dtype)}
- )
- tm.assert_frame_equal(df, expected2)
-
- tm.assert_frame_equal(df.astype(dtype), expected1)
- tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1)
-
- @pytest.mark.parametrize("dtype", ["Int64", "Int32", "Int16"])
- def test_astype_extension_dtypes_1d(self, dtype):
- # GH 22578
- df = pd.DataFrame({"a": [1.0, 2.0, 3.0]})
-
- expected1 = pd.DataFrame({"a": integer_array([1, 2, 3], dtype=dtype)})
- tm.assert_frame_equal(df.astype(dtype), expected1)
- tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1)
-
- df = pd.DataFrame({"a": [1.0, 2.0, 3.0]})
- df["a"] = df["a"].astype(dtype)
- expected2 = pd.DataFrame({"a": integer_array([1, 2, 3], dtype=dtype)})
- tm.assert_frame_equal(df, expected2)
-
- tm.assert_frame_equal(df.astype(dtype), expected1)
- tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1)
-
- @pytest.mark.parametrize("dtype", ["category", "Int64"])
- def test_astype_extension_dtypes_duplicate_col(self, dtype):
- # GH 24704
- a1 = Series([0, np.nan, 4], name="a")
- a2 = Series([np.nan, 3, 5], name="a")
- df = concat([a1, a2], axis=1)
-
- result = df.astype(dtype)
- expected = concat([a1.astype(dtype), a2.astype(dtype)], axis=1)
- tm.assert_frame_equal(result, expected)
-
- @pytest.mark.parametrize(
- "dtype", [{100: "float64", 200: "uint64"}, "category", "float64"]
- )
- def test_astype_column_metadata(self, dtype):
- # GH 19920
- columns = pd.UInt64Index([100, 200, 300], name="foo")
- df = DataFrame(np.arange(15).reshape(5, 3), columns=columns)
- df = df.astype(dtype)
- tm.assert_index_equal(df.columns, columns)
-
- @pytest.mark.parametrize("dtype", ["M8", "m8"])
- @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"])
- def test_astype_from_datetimelike_to_object(self, dtype, unit):
- # tests astype to object dtype
- # gh-19223 / gh-12425
- dtype = f"{dtype}[{unit}]"
- arr = np.array([[1, 2, 3]], dtype=dtype)
- df = DataFrame(arr)
- result = df.astype(object)
- assert (result.dtypes == object).all()
-
- if dtype.startswith("M8"):
- assert result.iloc[0, 0] == pd.to_datetime(1, unit=unit)
- else:
- assert result.iloc[0, 0] == pd.to_timedelta(1, unit=unit)
-
- @pytest.mark.parametrize("arr_dtype", [np.int64, np.float64])
- @pytest.mark.parametrize("dtype", ["M8", "m8"])
- @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"])
- def test_astype_to_datetimelike_unit(self, arr_dtype, dtype, unit):
- # tests all units from numeric origination
- # gh-19223 / gh-12425
- dtype = f"{dtype}[{unit}]"
- arr = np.array([[1, 2, 3]], dtype=arr_dtype)
- df = DataFrame(arr)
- result = df.astype(dtype)
- expected = DataFrame(arr.astype(dtype))
-
- tm.assert_frame_equal(result, expected)
-
- @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"])
- def test_astype_to_datetime_unit(self, unit):
- # tests all units from datetime origination
- # gh-19223
- dtype = f"M8[{unit}]"
- arr = np.array([[1, 2, 3]], dtype=dtype)
- df = DataFrame(arr)
- result = df.astype(dtype)
- expected = DataFrame(arr.astype(dtype))
-
- tm.assert_frame_equal(result, expected)
-
- @pytest.mark.parametrize("unit", ["ns"])
- def test_astype_to_timedelta_unit_ns(self, unit):
- # preserver the timedelta conversion
- # gh-19223
- dtype = f"m8[{unit}]"
- arr = np.array([[1, 2, 3]], dtype=dtype)
- df = DataFrame(arr)
- result = df.astype(dtype)
- expected = DataFrame(arr.astype(dtype))
-
- tm.assert_frame_equal(result, expected)
-
- @pytest.mark.parametrize("unit", ["us", "ms", "s", "h", "m", "D"])
- def test_astype_to_timedelta_unit(self, unit):
- # coerce to float
- # gh-19223
- dtype = f"m8[{unit}]"
- arr = np.array([[1, 2, 3]], dtype=dtype)
- df = DataFrame(arr)
- result = df.astype(dtype)
- expected = DataFrame(df.values.astype(dtype).astype(float))
-
- tm.assert_frame_equal(result, expected)
-
- @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"])
- def test_astype_to_incorrect_datetimelike(self, unit):
- # trying to astype a m to a M, or vice-versa
- # gh-19224
- dtype = f"M8[{unit}]"
- other = f"m8[{unit}]"
-
- df = DataFrame(np.array([[1, 2, 3]], dtype=dtype))
- msg = (
- fr"cannot astype a datetimelike from \[datetime64\[ns\]\] to "
- fr"\[timedelta64\[{unit}\]\]"
- )
- with pytest.raises(TypeError, match=msg):
- df.astype(other)
-
- msg = (
- fr"cannot astype a timedelta from \[timedelta64\[ns\]\] to "
- fr"\[datetime64\[{unit}\]\]"
- )
- df = DataFrame(np.array([[1, 2, 3]], dtype=other))
- with pytest.raises(TypeError, match=msg):
- df.astype(dtype)
-
def test_timedeltas(self):
df = DataFrame(
dict(
@@ -586,40 +162,6 @@ def test_timedeltas(self):
)
tm.assert_series_equal(result, expected)
- def test_arg_for_errors_in_astype(self):
- # issue #14878
-
- df = DataFrame([1, 2, 3])
-
- msg = (
- "Expected value of kwarg 'errors' to be one of "
- "['raise', 'ignore']. Supplied value is 'True'"
- )
- with pytest.raises(ValueError, match=re.escape(msg)):
- df.astype(np.float64, errors=True)
-
- df.astype(np.int8, errors="ignore")
-
- def test_arg_for_errors_in_astype_dictlist(self):
- # GH-25905
- df = pd.DataFrame(
- [
- {"a": "1", "b": "16.5%", "c": "test"},
- {"a": "2.2", "b": "15.3", "c": "another_test"},
- ]
- )
- expected = pd.DataFrame(
- [
- {"a": 1.0, "b": "16.5%", "c": "test"},
- {"a": 2.2, "b": "15.3", "c": "another_test"},
- ]
- )
- type_dict = {"a": "float64", "b": "float64", "c": "object"}
-
- result = df.astype(dtype=type_dict, errors="ignore")
-
- tm.assert_frame_equal(result, expected)
-
@pytest.mark.parametrize(
"input_vals",
[
@@ -785,87 +327,3 @@ def test_interleave(self, timezone_frame):
dtype=object,
).T
tm.assert_numpy_array_equal(result, expected)
-
- def test_astype(self, timezone_frame):
- # astype
- expected = np.array(
- [
- [
- Timestamp("2013-01-01 00:00:00"),
- Timestamp("2013-01-02 00:00:00"),
- Timestamp("2013-01-03 00:00:00"),
- ],
- [
- Timestamp("2013-01-01 00:00:00-0500", tz="US/Eastern"),
- pd.NaT,
- Timestamp("2013-01-03 00:00:00-0500", tz="US/Eastern"),
- ],
- [
- Timestamp("2013-01-01 00:00:00+0100", tz="CET"),
- pd.NaT,
- Timestamp("2013-01-03 00:00:00+0100", tz="CET"),
- ],
- ],
- dtype=object,
- ).T
- expected = DataFrame(
- expected,
- index=timezone_frame.index,
- columns=timezone_frame.columns,
- dtype=object,
- )
- result = timezone_frame.astype(object)
- tm.assert_frame_equal(result, expected)
-
- result = timezone_frame.astype("datetime64[ns]")
- expected = DataFrame(
- {
- "A": date_range("20130101", periods=3),
- "B": (
- date_range("20130101", periods=3, tz="US/Eastern")
- .tz_convert("UTC")
- .tz_localize(None)
- ),
- "C": (
- date_range("20130101", periods=3, tz="CET")
- .tz_convert("UTC")
- .tz_localize(None)
- ),
- }
- )
- expected.iloc[1, 1] = pd.NaT
- expected.iloc[1, 2] = pd.NaT
- tm.assert_frame_equal(result, expected)
-
- def test_astype_str(self, timezone_frame):
- # str formatting
- result = timezone_frame.astype(str)
- expected = DataFrame(
- [
- [
- "2013-01-01",
- "2013-01-01 00:00:00-05:00",
- "2013-01-01 00:00:00+01:00",
- ],
- ["2013-01-02", "NaT", "NaT"],
- [
- "2013-01-03",
- "2013-01-03 00:00:00-05:00",
- "2013-01-03 00:00:00+01:00",
- ],
- ],
- columns=timezone_frame.columns,
- )
- tm.assert_frame_equal(result, expected)
-
- with option_context("display.max_columns", 20):
- result = str(timezone_frame)
- assert (
- "0 2013-01-01 2013-01-01 00:00:00-05:00 2013-01-01 00:00:00+01:00"
- ) in result
- assert (
- "1 2013-01-02 NaT NaT"
- ) in result
- assert (
- "2 2013-01-03 2013-01-03 00:00:00-05:00 2013-01-03 00:00:00+01:00"
- ) in result
diff --git a/pandas/tests/indexes/categorical/test_astype.py b/pandas/tests/indexes/categorical/test_astype.py
new file mode 100644
index 0000000000000..a4a0cb1978325
--- /dev/null
+++ b/pandas/tests/indexes/categorical/test_astype.py
@@ -0,0 +1,66 @@
+import numpy as np
+import pytest
+
+from pandas import Categorical, CategoricalDtype, CategoricalIndex, Index, IntervalIndex
+import pandas._testing as tm
+
+
+class TestAstype:
+ def test_astype(self):
+ ci = CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False)
+
+ result = ci.astype(object)
+ tm.assert_index_equal(result, Index(np.array(ci)))
+
+ # this IS equal, but not the same class
+ assert result.equals(ci)
+ assert isinstance(result, Index)
+ assert not isinstance(result, CategoricalIndex)
+
+ # interval
+ ii = IntervalIndex.from_arrays(left=[-0.001, 2.0], right=[2, 4], closed="right")
+
+ ci = CategoricalIndex(
+ Categorical.from_codes([0, 1, -1], categories=ii, ordered=True)
+ )
+
+ result = ci.astype("interval")
+ expected = ii.take([0, 1, -1])
+ tm.assert_index_equal(result, expected)
+
+ result = IntervalIndex(result.values)
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("name", [None, "foo"])
+ @pytest.mark.parametrize("dtype_ordered", [True, False])
+ @pytest.mark.parametrize("index_ordered", [True, False])
+ def test_astype_category(self, name, dtype_ordered, index_ordered):
+ # GH#18630
+ index = CategoricalIndex(
+ list("aabbca"), categories=list("cab"), ordered=index_ordered
+ )
+ if name:
+ index = index.rename(name)
+
+ # standard categories
+ dtype = CategoricalDtype(ordered=dtype_ordered)
+ result = index.astype(dtype)
+ expected = CategoricalIndex(
+ index.tolist(),
+ name=name,
+ categories=index.categories,
+ ordered=dtype_ordered,
+ )
+ tm.assert_index_equal(result, expected)
+
+ # non-standard categories
+ dtype = CategoricalDtype(index.unique().tolist()[:-1], dtype_ordered)
+ result = index.astype(dtype)
+ expected = CategoricalIndex(index.tolist(), name=name, dtype=dtype)
+ tm.assert_index_equal(result, expected)
+
+ if dtype_ordered is False:
+ # dtype='category' can't specify ordered, so only test once
+ result = index.astype("category")
+ expected = index
+ tm.assert_index_equal(result, expected)
diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py
index 83fe21fd20bfe..9765c77c6b60c 100644
--- a/pandas/tests/indexes/categorical/test_category.py
+++ b/pandas/tests/indexes/categorical/test_category.py
@@ -3,10 +3,8 @@
from pandas._libs import index as libindex
-from pandas.core.dtypes.dtypes import CategoricalDtype
-
import pandas as pd
-from pandas import Categorical, IntervalIndex
+from pandas import Categorical
import pandas._testing as tm
from pandas.core.indexes.api import CategoricalIndex, Index
@@ -196,63 +194,6 @@ def test_delete(self):
# Either depending on NumPy version
ci.delete(10)
- def test_astype(self):
-
- ci = self.create_index()
- result = ci.astype(object)
- tm.assert_index_equal(result, Index(np.array(ci)))
-
- # this IS equal, but not the same class
- assert result.equals(ci)
- assert isinstance(result, Index)
- assert not isinstance(result, CategoricalIndex)
-
- # interval
- ii = IntervalIndex.from_arrays(left=[-0.001, 2.0], right=[2, 4], closed="right")
-
- ci = CategoricalIndex(
- Categorical.from_codes([0, 1, -1], categories=ii, ordered=True)
- )
-
- result = ci.astype("interval")
- expected = ii.take([0, 1, -1])
- tm.assert_index_equal(result, expected)
-
- result = IntervalIndex(result.values)
- tm.assert_index_equal(result, expected)
-
- @pytest.mark.parametrize("name", [None, "foo"])
- @pytest.mark.parametrize("dtype_ordered", [True, False])
- @pytest.mark.parametrize("index_ordered", [True, False])
- def test_astype_category(self, name, dtype_ordered, index_ordered):
- # GH 18630
- index = self.create_index(ordered=index_ordered)
- if name:
- index = index.rename(name)
-
- # standard categories
- dtype = CategoricalDtype(ordered=dtype_ordered)
- result = index.astype(dtype)
- expected = CategoricalIndex(
- index.tolist(),
- name=name,
- categories=index.categories,
- ordered=dtype_ordered,
- )
- tm.assert_index_equal(result, expected)
-
- # non-standard categories
- dtype = CategoricalDtype(index.unique().tolist()[:-1], dtype_ordered)
- result = index.astype(dtype)
- expected = CategoricalIndex(index.tolist(), name=name, dtype=dtype)
- tm.assert_index_equal(result, expected)
-
- if dtype_ordered is False:
- # dtype='category' can't specify ordered, so only test once
- result = index.astype("category")
- expected = index
- tm.assert_index_equal(result, expected)
-
@pytest.mark.parametrize(
"data, non_lexsorted_data",
[[[1, 2, 3], [9, 0, 1, 2, 3]], [list("abc"), list("fabcd")]],
diff --git a/pandas/tests/indexes/datetimes/test_astype.py b/pandas/tests/indexes/datetimes/test_astype.py
index 34169a670c169..7001dba442d16 100644
--- a/pandas/tests/indexes/datetimes/test_astype.py
+++ b/pandas/tests/indexes/datetimes/test_astype.py
@@ -12,7 +12,6 @@
Int64Index,
NaT,
PeriodIndex,
- Series,
Timestamp,
date_range,
)
@@ -65,37 +64,21 @@ def test_astype_with_tz(self):
)
tm.assert_index_equal(result, expected)
- # BUG#10442 : testing astype(str) is correct for Series/DatetimeIndex
- result = pd.Series(pd.date_range("2012-01-01", periods=3)).astype(str)
- expected = pd.Series(["2012-01-01", "2012-01-02", "2012-01-03"], dtype=object)
- tm.assert_series_equal(result, expected)
-
- result = Series(pd.date_range("2012-01-01", periods=3, tz="US/Eastern")).astype(
- str
- )
- expected = Series(
- [
- "2012-01-01 00:00:00-05:00",
- "2012-01-02 00:00:00-05:00",
- "2012-01-03 00:00:00-05:00",
- ],
- dtype=object,
- )
- tm.assert_series_equal(result, expected)
-
+ def test_astype_tzaware_to_tzaware(self):
# GH 18951: tz-aware to tz-aware
idx = date_range("20170101", periods=4, tz="US/Pacific")
result = idx.astype("datetime64[ns, US/Eastern]")
expected = date_range("20170101 03:00:00", periods=4, tz="US/Eastern")
tm.assert_index_equal(result, expected)
+ def test_astype_tznaive_to_tzaware(self):
# GH 18951: tz-naive to tz-aware
idx = date_range("20170101", periods=4)
result = idx.astype("datetime64[ns, US/Eastern]")
expected = date_range("20170101", periods=4, tz="US/Eastern")
tm.assert_index_equal(result, expected)
- def test_astype_str_compat(self):
+ def test_astype_str_nat(self):
# GH 13149, GH 13209
# verify that we are returning NaT as a string (and not unicode)
@@ -106,7 +89,8 @@ def test_astype_str_compat(self):
def test_astype_str(self):
# test astype string - #10442
- result = date_range("2012-01-01", periods=4, name="test_name").astype(str)
+ dti = date_range("2012-01-01", periods=4, name="test_name")
+ result = dti.astype(str)
expected = Index(
["2012-01-01", "2012-01-02", "2012-01-03", "2012-01-04"],
name="test_name",
@@ -114,10 +98,10 @@ def test_astype_str(self):
)
tm.assert_index_equal(result, expected)
+ def test_astype_str_tz_and_name(self):
# test astype string with tz and name
- result = date_range(
- "2012-01-01", periods=3, name="test_name", tz="US/Eastern"
- ).astype(str)
+ dti = date_range("2012-01-01", periods=3, name="test_name", tz="US/Eastern")
+ result = dti.astype(str)
expected = Index(
[
"2012-01-01 00:00:00-05:00",
@@ -129,10 +113,10 @@ def test_astype_str(self):
)
tm.assert_index_equal(result, expected)
+ def test_astype_str_freq_and_name(self):
# test astype string with freqH and name
- result = date_range("1/1/2011", periods=3, freq="H", name="test_name").astype(
- str
- )
+ dti = date_range("1/1/2011", periods=3, freq="H", name="test_name")
+ result = dti.astype(str)
expected = Index(
["2011-01-01 00:00:00", "2011-01-01 01:00:00", "2011-01-01 02:00:00"],
name="test_name",
@@ -140,10 +124,12 @@ def test_astype_str(self):
)
tm.assert_index_equal(result, expected)
+ def test_astype_str_freq_and_tz(self):
# test astype string with freqH and timezone
- result = date_range(
+ dti = date_range(
"3/6/2012 00:00", periods=2, freq="H", tz="Europe/London", name="test_name"
- ).astype(str)
+ )
+ result = dti.astype(str)
expected = Index(
["2012-03-06 00:00:00+00:00", "2012-03-06 01:00:00+00:00"],
dtype=object,
diff --git a/pandas/tests/indexes/numeric/test_astype.py b/pandas/tests/indexes/numeric/test_astype.py
new file mode 100644
index 0000000000000..1771f4336df67
--- /dev/null
+++ b/pandas/tests/indexes/numeric/test_astype.py
@@ -0,0 +1,83 @@
+import re
+
+import numpy as np
+import pytest
+
+from pandas.core.dtypes.common import pandas_dtype
+
+from pandas import Float64Index, Index, Int64Index
+import pandas._testing as tm
+
+
+class TestAstype:
+ def test_astype_float64_to_object(self):
+ float_index = Float64Index([0.0, 2.5, 5.0, 7.5, 10.0])
+ result = float_index.astype(object)
+ assert result.equals(float_index)
+ assert float_index.equals(result)
+ assert isinstance(result, Index) and not isinstance(result, Float64Index)
+
+ def test_astype_float64_mixed_to_object(self):
+ # mixed int-float
+ idx = Float64Index([1.5, 2, 3, 4, 5])
+ idx.name = "foo"
+ result = idx.astype(object)
+ assert result.equals(idx)
+ assert idx.equals(result)
+ assert isinstance(result, Index) and not isinstance(result, Float64Index)
+
+ @pytest.mark.parametrize("dtype", ["int16", "int32", "int64"])
+ def test_astype_float64_to_int_dtype(self, dtype):
+ # GH#12881
+ # a float astype int
+ idx = Float64Index([0, 1, 2])
+ result = idx.astype(dtype)
+ expected = Int64Index([0, 1, 2])
+ tm.assert_index_equal(result, expected)
+
+ idx = Float64Index([0, 1.1, 2])
+ result = idx.astype(dtype)
+ expected = Int64Index([0, 1, 2])
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("dtype", ["float32", "float64"])
+ def test_astype_float64_to_float_dtype(self, dtype):
+ # GH#12881
+ # a float astype int
+ idx = Float64Index([0, 1, 2])
+ result = idx.astype(dtype)
+ expected = idx
+ tm.assert_index_equal(result, expected)
+
+ idx = Float64Index([0, 1.1, 2])
+ result = idx.astype(dtype)
+ expected = Index(idx.values.astype(dtype))
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"])
+ def test_cannot_cast_to_datetimelike(self, dtype):
+ idx = Float64Index([0, 1.1, 2])
+
+ msg = (
+ f"Cannot convert Float64Index to dtype {pandas_dtype(dtype)}; "
+ f"integer values are required for conversion"
+ )
+ with pytest.raises(TypeError, match=re.escape(msg)):
+ idx.astype(dtype)
+
+ @pytest.mark.parametrize("dtype", [int, "int16", "int32", "int64"])
+ @pytest.mark.parametrize("non_finite", [np.inf, np.nan])
+ def test_cannot_cast_inf_to_int(self, non_finite, dtype):
+ # GH#13149
+ idx = Float64Index([1, 2, non_finite])
+
+ msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
+ with pytest.raises(ValueError, match=msg):
+ idx.astype(dtype)
+
+ def test_astype_from_object(self):
+ index = Index([1.0, np.nan, 0.2], dtype="object")
+ result = index.astype(float)
+ expected = Float64Index([1.0, np.nan, 0.2])
+ assert result.dtype == expected.dtype
+ tm.assert_index_equal(result, expected)
diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py
index 35a1cbd141c89..0965694e5b51d 100644
--- a/pandas/tests/indexes/test_numeric.py
+++ b/pandas/tests/indexes/test_numeric.py
@@ -1,5 +1,4 @@
from datetime import datetime, timedelta
-import re
import numpy as np
import pytest
@@ -9,7 +8,6 @@
import pandas as pd
from pandas import Float64Index, Index, Int64Index, Series, UInt64Index
import pandas._testing as tm
-from pandas.api.types import pandas_dtype
from pandas.tests.indexes.common import Base
@@ -213,67 +211,6 @@ def test_constructor_explicit(self, mixed_index, float_index):
mixed_index, Index([1.5, 2, 3, 4, 5], dtype=object), is_float_index=False
)
- def test_astype(self, mixed_index, float_index):
-
- result = float_index.astype(object)
- assert result.equals(float_index)
- assert float_index.equals(result)
- self.check_is_index(result)
-
- i = mixed_index.copy()
- i.name = "foo"
- result = i.astype(object)
- assert result.equals(i)
- assert i.equals(result)
- self.check_is_index(result)
-
- # GH 12881
- # a float astype int
- for dtype in ["int16", "int32", "int64"]:
- i = Float64Index([0, 1, 2])
- result = i.astype(dtype)
- expected = Int64Index([0, 1, 2])
- tm.assert_index_equal(result, expected)
-
- i = Float64Index([0, 1.1, 2])
- result = i.astype(dtype)
- expected = Int64Index([0, 1, 2])
- tm.assert_index_equal(result, expected)
-
- for dtype in ["float32", "float64"]:
- i = Float64Index([0, 1, 2])
- result = i.astype(dtype)
- expected = i
- tm.assert_index_equal(result, expected)
-
- i = Float64Index([0, 1.1, 2])
- result = i.astype(dtype)
- expected = Index(i.values.astype(dtype))
- tm.assert_index_equal(result, expected)
-
- # invalid
- for dtype in ["M8[ns]", "m8[ns]"]:
- msg = (
- f"Cannot convert Float64Index to dtype {pandas_dtype(dtype)}; "
- f"integer values are required for conversion"
- )
- 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])
- msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
- with pytest.raises(ValueError, match=msg):
- i.astype(dtype)
-
- def test_cannot_cast_inf_to_int(self):
- idx = pd.Float64Index([1, 2, np.inf])
-
- msg = r"Cannot convert non-finite values \(NA or inf\) to integer"
- with pytest.raises(ValueError, match=msg):
- idx.astype(int)
-
def test_type_coercion_fail(self, any_int_dtype):
# see gh-15832
msg = "Trying to coerce float values to integers"
@@ -359,13 +296,6 @@ def test_nan_multiple_containment(self):
i = Float64Index([1.0, 2.0])
tm.assert_numpy_array_equal(i.isin([np.nan]), np.array([False, False]))
- def test_astype_from_object(self):
- index = Index([1.0, np.nan, 0.2], dtype="object")
- result = index.astype(float)
- expected = Float64Index([1.0, np.nan, 0.2])
- assert result.dtype == expected.dtype
- tm.assert_index_equal(result, expected)
-
def test_fillna_float64(self):
# GH 11343
idx = Index([1.0, np.nan, 3.0], dtype=float, name="x")
diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py
new file mode 100644
index 0000000000000..9fdc4179de2e1
--- /dev/null
+++ b/pandas/tests/series/methods/test_astype.py
@@ -0,0 +1,25 @@
+from pandas import Series, date_range
+import pandas._testing as tm
+
+
+class TestAstype:
+ def test_astype_dt64_to_str(self):
+ # GH#10442 : testing astype(str) is correct for Series/DatetimeIndex
+ dti = date_range("2012-01-01", periods=3)
+ result = Series(dti).astype(str)
+ expected = Series(["2012-01-01", "2012-01-02", "2012-01-03"], dtype=object)
+ tm.assert_series_equal(result, expected)
+
+ def test_astype_dt64tz_to_str(self):
+ # GH#10442 : testing astype(str) is correct for Series/DatetimeIndex
+ dti_tz = date_range("2012-01-01", periods=3, tz="US/Eastern")
+ result = Series(dti_tz).astype(str)
+ expected = Series(
+ [
+ "2012-01-01 00:00:00-05:00",
+ "2012-01-02 00:00:00-05:00",
+ "2012-01-03 00:00:00-05:00",
+ ],
+ dtype=object,
+ )
+ tm.assert_series_equal(result, expected)
| Split/parametrized in some places. | https://api.github.com/repos/pandas-dev/pandas/pulls/33734 | 2020-04-23T00:50:13Z | 2020-04-25T21:00:43Z | 2020-04-25T21:00:43Z | 2020-04-25T21:02:48Z |
CLN: Remove unused assignment | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 04ebaf26fc11c..8228edb12b29a 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -8325,7 +8325,6 @@ def blk_func(values):
result = result.iloc[0].rename(None)
return result
- data = self
if numeric_only is None:
data = self
values = data.values
| https://api.github.com/repos/pandas-dev/pandas/pulls/33733 | 2020-04-22T22:03:23Z | 2020-04-23T01:00:43Z | 2020-04-23T01:00:43Z | 2020-04-23T02:51:20Z | |
BLD: bump numpy min version to 1.15.4 | diff --git a/ci/deps/azure-36-minimum_versions.yaml b/ci/deps/azure-36-minimum_versions.yaml
index ae8fffa59fd50..f5af7bcf36189 100644
--- a/ci/deps/azure-36-minimum_versions.yaml
+++ b/ci/deps/azure-36-minimum_versions.yaml
@@ -1,6 +1,5 @@
name: pandas-dev
channels:
- - defaults
- conda-forge
dependencies:
- python=3.6.1
@@ -19,12 +18,12 @@ dependencies:
- jinja2=2.8
- numba=0.46.0
- numexpr=2.6.2
- - numpy=1.13.3
+ - numpy=1.15.4
- openpyxl=2.5.7
- pytables=3.4.3
- python-dateutil=2.7.3
- pytz=2017.2
- - scipy=0.19.0
+ - scipy=1.2
- xlrd=1.1.0
- xlsxwriter=0.9.8
- xlwt=1.2.0
diff --git a/ci/deps/azure-macos-36.yaml b/ci/deps/azure-macos-36.yaml
index 93885afbc4114..eeea249a19ca1 100644
--- a/ci/deps/azure-macos-36.yaml
+++ b/ci/deps/azure-macos-36.yaml
@@ -19,7 +19,7 @@ dependencies:
- matplotlib=2.2.3
- nomkl
- numexpr
- - numpy=1.14
+ - numpy=1.15.4
- openpyxl
- pyarrow>=0.13.0
- pytables
diff --git a/conda.recipe/meta.yaml b/conda.recipe/meta.yaml
index 47f63c11d0567..e833ea1f1f398 100644
--- a/conda.recipe/meta.yaml
+++ b/conda.recipe/meta.yaml
@@ -20,12 +20,12 @@ requirements:
- cython
- numpy
- setuptools >=3.3
- - python-dateutil >=2.5.0
+ - python-dateutil >=2.7.3
- pytz
run:
- python {{ python }}
- {{ pin_compatible('numpy') }}
- - python-dateutil >=2.5.0
+ - python-dateutil >=2.7.3
- pytz
test:
diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst
index d392e151e3f97..ba99aaa9f430c 100644
--- a/doc/source/getting_started/install.rst
+++ b/doc/source/getting_started/install.rst
@@ -220,7 +220,7 @@ Dependencies
Package Minimum supported version
================================================================ ==========================
`setuptools <https://setuptools.readthedocs.io/en/latest/>`__ 24.2.0
-`NumPy <https://www.numpy.org>`__ 1.13.3
+`NumPy <https://www.numpy.org>`__ 1.15.4
`python-dateutil <https://dateutil.readthedocs.io/en/stable/>`__ 2.7.3
`pytz <https://pypi.org/project/pytz/>`__ 2017.2
================================================================ ==========================
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 40adeb28d47b6..26aee8133a1e9 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -157,13 +157,23 @@ Other enhancements
Increased minimum versions for dependencies
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-Some minimum supported versions of dependencies were updated (:issue:`29766`, :issue:`29723`, pytables >= 3.4.3).
+Some minimum supported versions of dependencies were updated (:issue:`33718`, :issue:`29766`, :issue:`29723`, pytables >= 3.4.3).
If installed, we now require:
+-----------------+-----------------+----------+---------+
| Package | Minimum Version | Required | Changed |
+=================+=================+==========+=========+
-| python-dateutil | 2.7.3 | X | |
+| numpy | 1.15.4 | X | X |
++-----------------+-----------------+----------+---------+
+| pytz | 2015.4 | X | |
++-----------------+-----------------+----------+---------+
+| python-dateutil | 2.7.3 | X | X |
++-----------------+-----------------+----------+---------+
+| bottleneck | 1.2.1 | | |
++-----------------+-----------------+----------+---------+
+| numexpr | 2.6.2 | | |
++-----------------+-----------------+----------+---------+
+| pytest (dev) | 4.0.2 | | |
+-----------------+-----------------+----------+---------+
For `optional libraries <https://dev.pandas.io/docs/install.html#dependencies>`_ the general recommendation is to use the latest version.
@@ -195,7 +205,7 @@ Optional libraries below the lowest tested version may still work, but are not c
+-----------------+-----------------+---------+
| s3fs | 0.3.0 | |
+-----------------+-----------------+---------+
-| scipy | 0.19.0 | |
+| scipy | 1.2.0 | X |
+-----------------+-----------------+---------+
| sqlalchemy | 1.1.4 | |
+-----------------+-----------------+---------+
diff --git a/environment.yml b/environment.yml
index 8893302b4c9b2..bc7c715104ce5 100644
--- a/environment.yml
+++ b/environment.yml
@@ -75,7 +75,7 @@ dependencies:
- jinja2 # pandas.Styler
- matplotlib>=2.2.2 # pandas.plotting, Series.plot, DataFrame.plot
- numexpr>=2.6.8
- - scipy>=1.1
+ - scipy>=1.2
- numba>=0.46.0
# optional for io
diff --git a/pandas/__init__.py b/pandas/__init__.py
index 2b9a461e0e95d..d6584bf4f1c4f 100644
--- a/pandas/__init__.py
+++ b/pandas/__init__.py
@@ -20,8 +20,6 @@
# numpy compat
from pandas.compat.numpy import (
- _np_version_under1p14,
- _np_version_under1p15,
_np_version_under1p16,
_np_version_under1p17,
_np_version_under1p18,
diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py
index 7e253a52a9c00..c5fd294699c45 100644
--- a/pandas/compat/_optional.py
+++ b/pandas/compat/_optional.py
@@ -21,7 +21,7 @@
"pytest": "5.0.1",
"pyxlsb": "1.0.6",
"s3fs": "0.3.0",
- "scipy": "0.19.0",
+ "scipy": "1.2.0",
"sqlalchemy": "1.1.4",
"tables": "3.4.3",
"tabulate": "0.8.3",
diff --git a/pandas/compat/numpy/__init__.py b/pandas/compat/numpy/__init__.py
index 6c9ac5944e6a1..a8f49d91f040e 100644
--- a/pandas/compat/numpy/__init__.py
+++ b/pandas/compat/numpy/__init__.py
@@ -8,19 +8,17 @@
# numpy versioning
_np_version = np.__version__
_nlv = LooseVersion(_np_version)
-_np_version_under1p14 = _nlv < LooseVersion("1.14")
-_np_version_under1p15 = _nlv < LooseVersion("1.15")
_np_version_under1p16 = _nlv < LooseVersion("1.16")
_np_version_under1p17 = _nlv < LooseVersion("1.17")
_np_version_under1p18 = _nlv < LooseVersion("1.18")
_is_numpy_dev = ".dev" in str(_nlv)
-if _nlv < "1.13.3":
+if _nlv < "1.15.4":
raise ImportError(
- "this version of pandas is incompatible with numpy < 1.13.3\n"
+ "this version of pandas is incompatible with numpy < 1.15.4\n"
f"your numpy version is {_np_version}.\n"
- "Please upgrade numpy to >= 1.13.3 to use this pandas version"
+ "Please upgrade numpy to >= 1.15.4 to use this pandas version"
)
@@ -65,8 +63,6 @@ def np_array_datetime64_compat(arr, *args, **kwargs):
__all__ = [
"np",
"_np_version",
- "_np_version_under1p14",
- "_np_version_under1p15",
"_np_version_under1p16",
"_np_version_under1p17",
"_is_numpy_dev",
diff --git a/pandas/tests/api/test_api.py b/pandas/tests/api/test_api.py
index 5aab5b814bae7..ecd20796b6f21 100644
--- a/pandas/tests/api/test_api.py
+++ b/pandas/tests/api/test_api.py
@@ -193,8 +193,6 @@ class TestPDApi(Base):
"_hashtable",
"_lib",
"_libs",
- "_np_version_under1p14",
- "_np_version_under1p15",
"_np_version_under1p16",
"_np_version_under1p17",
"_np_version_under1p18",
diff --git a/pandas/tests/dtypes/cast/test_promote.py b/pandas/tests/dtypes/cast/test_promote.py
index 69f8f46356a4d..74a11c9f33195 100644
--- a/pandas/tests/dtypes/cast/test_promote.py
+++ b/pandas/tests/dtypes/cast/test_promote.py
@@ -98,14 +98,13 @@ def _assert_match(result_fill_value, expected_fill_value):
# GH#23982/25425 require the same type in addition to equality/NA-ness
res_type = type(result_fill_value)
ex_type = type(expected_fill_value)
- if res_type.__name__ == "uint64":
- # No idea why, but these (sometimes) do not compare as equal
- assert ex_type.__name__ == "uint64"
- elif res_type.__name__ == "ulonglong":
- # On some builds we get this instead of np.uint64
- # Note: cant check res_type.dtype.itemsize directly on numpy 1.18
- assert res_type(0).itemsize == 8
- assert ex_type == res_type or ex_type == np.uint64
+
+ if hasattr(result_fill_value, "dtype"):
+ # Compare types in a way that is robust to platform-specific
+ # idiosyncracies where e.g. sometimes we get "ulonglong" as an alias
+ # for "uint64" or "intc" as an alias for "int32"
+ assert result_fill_value.dtype.kind == expected_fill_value.dtype.kind
+ assert result_fill_value.dtype.itemsize == expected_fill_value.dtype.itemsize
else:
# On some builds, type comparison fails, e.g. np.int32 != np.int32
assert res_type == ex_type or res_type.__name__ == ex_type.__name__
diff --git a/pandas/tests/extension/test_boolean.py b/pandas/tests/extension/test_boolean.py
index 50b72698629bb..04dedac3e8b9b 100644
--- a/pandas/tests/extension/test_boolean.py
+++ b/pandas/tests/extension/test_boolean.py
@@ -16,8 +16,6 @@
import numpy as np
import pytest
-from pandas.compat.numpy import _np_version_under1p14
-
import pandas as pd
import pandas._testing as tm
from pandas.core.arrays.boolean import BooleanDtype
@@ -111,9 +109,6 @@ def check_opname(self, s, op_name, other, exc=None):
def _check_op(self, s, op, other, op_name, exc=NotImplementedError):
if exc is None:
if op_name in self.implements:
- # subtraction for bools raises TypeError (but not yet in 1.13)
- if _np_version_under1p14:
- pytest.skip("__sub__ does not yet raise in numpy 1.13")
msg = r"numpy boolean subtract"
with pytest.raises(TypeError, match=msg):
op(s, other)
diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py
index dc779562b662d..b06c3d72a2c77 100644
--- a/pandas/tests/frame/methods/test_astype.py
+++ b/pandas/tests/frame/methods/test_astype.py
@@ -14,7 +14,6 @@
Timedelta,
Timestamp,
UInt64Index,
- _np_version_under1p14,
concat,
date_range,
option_context,
@@ -169,9 +168,7 @@ def test_astype_str_float(self):
tm.assert_frame_equal(result, expected)
result = DataFrame([1.12345678901234567890]).astype(str)
- # < 1.14 truncates
- # >= 1.14 preserves the full repr
- val = "1.12345678901" if _np_version_under1p14 else "1.1234567890123457"
+ val = "1.1234567890123457"
expected = DataFrame([val])
tm.assert_frame_equal(result, expected)
diff --git a/pyproject.toml b/pyproject.toml
index 696785599d7da..efeb24edbdeb1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -5,8 +5,8 @@ requires = [
"setuptools",
"wheel",
"Cython>=0.29.16", # Note: sync with setup.py
- "numpy==1.13.3; python_version=='3.6' and platform_system!='AIX'",
- "numpy==1.14.5; python_version>='3.7' and platform_system!='AIX'",
+ "numpy==1.15.4; python_version=='3.6' and platform_system!='AIX'",
+ "numpy==1.15.4; python_version>='3.7' and platform_system!='AIX'",
"numpy==1.16.0; python_version=='3.6' and platform_system=='AIX'",
"numpy==1.16.0; python_version>='3.7' and platform_system=='AIX'",
]
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 8a954fabd2d8d..5f5b5d27a03a7 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -50,7 +50,7 @@ ipython>=7.11.1
jinja2
matplotlib>=2.2.2
numexpr>=2.6.8
-scipy>=1.1
+scipy>=1.2
numba>=0.46.0
beautifulsoup4>=4.6.0
html5lib
diff --git a/setup.py b/setup.py
index a2e01e08e8de2..58f3fb5706ad1 100755
--- a/setup.py
+++ b/setup.py
@@ -33,7 +33,7 @@ def is_platform_mac():
return sys.platform == "darwin"
-min_numpy_ver = "1.13.3"
+min_numpy_ver = "1.15.4"
min_cython_ver = "0.29.16" # note: sync with pyproject.toml
try:
| - [x] closes #33718
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/33729 | 2020-04-22T20:31:06Z | 2020-05-01T19:38:39Z | 2020-05-01T19:38:38Z | 2020-06-09T14:44:08Z |
TST: pd.concat on two (or more) series produces all-NaN dataframe | diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py
index bccae2c4c2772..c4025640bb49f 100644
--- a/pandas/tests/reshape/test_concat.py
+++ b/pandas/tests/reshape/test_concat.py
@@ -2768,3 +2768,37 @@ def test_concat_copy_index(test_series, axis):
comb = concat([df, df], axis=axis, copy=True)
assert comb.index is not df.index
assert comb.columns is not df.columns
+
+
+def test_concat_multiindex_datetime_object_index():
+ # https://github.com/pandas-dev/pandas/issues/11058
+ s = Series(
+ ["a", "b"],
+ index=MultiIndex.from_arrays(
+ [[1, 2], Index([dt.date(2013, 1, 1), dt.date(2014, 1, 1)], dtype="object")],
+ names=["first", "second"],
+ ),
+ )
+ s2 = Series(
+ ["a", "b"],
+ index=MultiIndex.from_arrays(
+ [[1, 2], Index([dt.date(2013, 1, 1), dt.date(2015, 1, 1)], dtype="object")],
+ names=["first", "second"],
+ ),
+ )
+ expected = DataFrame(
+ [["a", "a"], ["b", np.nan], [np.nan, "b"]],
+ index=MultiIndex.from_arrays(
+ [
+ [1, 2, 2],
+ DatetimeIndex(
+ ["2013-01-01", "2014-01-01", "2015-01-01"],
+ dtype="datetime64[ns]",
+ freq=None,
+ ),
+ ],
+ names=["first", "second"],
+ ),
+ )
+ result = concat([s, s2], axis=1)
+ tm.assert_frame_equal(result, expected)
| - [ ] closes #11058
- [ ] 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/33728 | 2020-04-22T19:25:46Z | 2020-04-22T21:26:00Z | 2020-04-22T21:26:00Z | 2020-04-23T07:01:36Z |
REF: avoid passing SingleBlockManager to Series | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 6c3523f830e97..5defb8916c73f 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -3649,7 +3649,9 @@ def reindexer(value):
@property
def _series(self):
return {
- item: Series(self._mgr.iget(idx), index=self.index, name=item)
+ item: Series(
+ self._mgr.iget(idx), index=self.index, name=item, fastpath=True
+ )
for idx, item in enumerate(self.columns)
}
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 2f35a5b6f9a7e..b2ed47465e395 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -11208,9 +11208,7 @@ def block_accum_func(blk_values):
result = self._mgr.apply(block_accum_func)
- d = self._construct_axes_dict()
- d["copy"] = False
- return self._constructor(result, **d).__finalize__(self, method=name)
+ return self._constructor(result).__finalize__(self, method=name)
return set_function_name(cum_func, name, cls)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 9ef865a964123..f990cc7ae7917 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -259,12 +259,8 @@ def __init__(
# astype copies
data = data.astype(dtype)
else:
- # need to copy to avoid aliasing issues
+ # GH#24096 we need to ensure the index remains immutable
data = data._values.copy()
- if isinstance(data, ABCDatetimeIndex) and data.tz is not None:
- # GH#24096 need copy to be deep for datetime64tz case
- # TODO: See if we can avoid these copies
- data = data._values.copy(deep=True)
copy = False
elif isinstance(data, np.ndarray):
@@ -281,6 +277,7 @@ def __init__(
index = data.index
else:
data = data.reindex(index, copy=copy)
+ copy = False
data = data._mgr
elif is_dict_like(data):
data, index = self._init_dict(data, index, dtype)
| cc @jorisvandenbossche IIRC you didnt want to disallow SingleBlockManager because geopandas passes it. In those cases, does it also pass `fastpath=True`? If so, we can consider deprecating allowing SingleBlockManager in the non-fastpath case | https://api.github.com/repos/pandas-dev/pandas/pulls/33727 | 2020-04-22T18:14:00Z | 2020-04-23T17:59:29Z | 2020-04-23T17:59:29Z | 2020-04-23T18:02:57Z |
TYP: construction | diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index cdd0717849e96..8a405d6ee0a00 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -330,7 +330,7 @@ def __init__(
values = _convert_to_list_like(values)
# By convention, empty lists result in object dtype:
- sanitize_dtype = "object" if len(values) == 0 else None
+ sanitize_dtype = np.dtype("O") if len(values) == 0 else None
null_mask = isna(values)
if null_mask.any():
values = [values[idx] for idx in np.where(~null_mask)[0]]
diff --git a/pandas/core/construction.py b/pandas/core/construction.py
index 2d60ad9ba50bf..d1b07585943ea 100644
--- a/pandas/core/construction.py
+++ b/pandas/core/construction.py
@@ -13,7 +13,7 @@
from pandas._libs import lib
from pandas._libs.tslibs import IncompatibleFrequency, OutOfBoundsDatetime
-from pandas._typing import ArrayLike, Dtype
+from pandas._typing import ArrayLike, Dtype, DtypeObj
from pandas.core.dtypes.cast import (
construct_1d_arraylike_from_scalar,
@@ -36,7 +36,6 @@
is_list_like,
is_object_dtype,
is_timedelta64_ns_dtype,
- pandas_dtype,
)
from pandas.core.dtypes.dtypes import CategoricalDtype, ExtensionDtype, registry
from pandas.core.dtypes.generic import (
@@ -52,13 +51,12 @@
if TYPE_CHECKING:
from pandas.core.series import Series # noqa: F401
from pandas.core.indexes.api import Index # noqa: F401
+ from pandas.core.arrays import ExtensionArray # noqa: F401
def array(
- data: Sequence[object],
- dtype: Optional[Union[str, np.dtype, ExtensionDtype]] = None,
- copy: bool = True,
-) -> ABCExtensionArray:
+ data: Sequence[object], dtype: Optional[Dtype] = None, copy: bool = True,
+) -> "ExtensionArray":
"""
Create an array.
@@ -388,14 +386,16 @@ def extract_array(obj, extract_numpy: bool = False):
def sanitize_array(
- data, index, dtype=None, copy: bool = False, raise_cast_failure: bool = False
-):
+ data,
+ index: Optional["Index"],
+ dtype: Optional[DtypeObj] = None,
+ copy: bool = False,
+ raise_cast_failure: bool = False,
+) -> ArrayLike:
"""
- Sanitize input data to an ndarray, copy if specified, coerce to the
- dtype if specified.
+ Sanitize input data to an ndarray or ExtensionArray, copy if specified,
+ coerce to the dtype if specified.
"""
- if dtype is not None:
- dtype = pandas_dtype(dtype)
if isinstance(data, ma.MaskedArray):
mask = ma.getmaskarray(data)
@@ -508,10 +508,7 @@ def sanitize_array(
def _try_cast(
- arr,
- dtype: Optional[Union[np.dtype, "ExtensionDtype"]],
- copy: bool,
- raise_cast_failure: bool,
+ arr, dtype: Optional[DtypeObj], copy: bool, raise_cast_failure: bool,
):
"""
Convert input to numpy ndarray and optionally cast to a given dtype.
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index c9419fded5de9..e50d635a1ba6c 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -3,7 +3,7 @@
"""
from datetime import date, datetime, timedelta
-from typing import TYPE_CHECKING, Type
+from typing import TYPE_CHECKING, Any, Optional, Tuple, Type
import numpy as np
@@ -17,7 +17,7 @@
iNaT,
)
from pandas._libs.tslibs.timezones import tz_compare
-from pandas._typing import Dtype, DtypeObj
+from pandas._typing import ArrayLike, Dtype, DtypeObj
from pandas.util._validators import validate_bool_kwarg
from pandas.core.dtypes.common import (
@@ -613,7 +613,7 @@ def _ensure_dtype_type(value, dtype):
return dtype.type(value)
-def infer_dtype_from(val, pandas_dtype: bool = False):
+def infer_dtype_from(val, pandas_dtype: bool = False) -> Tuple[DtypeObj, Any]:
"""
Interpret the dtype from a scalar or array.
@@ -630,7 +630,7 @@ def infer_dtype_from(val, pandas_dtype: bool = False):
return infer_dtype_from_array(val, pandas_dtype=pandas_dtype)
-def infer_dtype_from_scalar(val, pandas_dtype: bool = False):
+def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> Tuple[DtypeObj, Any]:
"""
Interpret the dtype from a scalar.
@@ -641,7 +641,7 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False):
If False, scalar belongs to pandas extension types is inferred as
object
"""
- dtype = np.object_
+ dtype = np.dtype(object)
# a 1-element ndarray
if isinstance(val, np.ndarray):
@@ -660,7 +660,7 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False):
# instead of np.empty (but then you still don't want things
# coming out as np.str_!
- dtype = np.object_
+ dtype = np.dtype(object)
elif isinstance(val, (np.datetime64, datetime)):
val = tslibs.Timestamp(val)
@@ -671,7 +671,7 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False):
dtype = DatetimeTZDtype(unit="ns", tz=val.tz)
else:
# return datetimetz as object
- return np.object_, val
+ return np.dtype(object), val
val = val.value
elif isinstance(val, (np.timedelta64, timedelta)):
@@ -679,22 +679,22 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False):
dtype = np.dtype("m8[ns]")
elif is_bool(val):
- dtype = np.bool_
+ dtype = np.dtype(np.bool_)
elif is_integer(val):
if isinstance(val, np.integer):
- dtype = type(val)
+ dtype = np.dtype(type(val))
else:
- dtype = np.int64
+ dtype = np.dtype(np.int64)
elif is_float(val):
if isinstance(val, np.floating):
- dtype = type(val)
+ dtype = np.dtype(type(val))
else:
- dtype = np.float64
+ dtype = np.dtype(np.float64)
elif is_complex(val):
- dtype = np.complex_
+ dtype = np.dtype(np.complex_)
elif pandas_dtype:
if lib.is_period(val):
@@ -707,7 +707,8 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False):
return dtype, val
-def infer_dtype_from_array(arr, pandas_dtype: bool = False):
+# TODO: try to make the Any in the return annotation more specific
+def infer_dtype_from_array(arr, pandas_dtype: bool = False) -> Tuple[DtypeObj, Any]:
"""
Infer the dtype from an array.
@@ -738,7 +739,7 @@ def infer_dtype_from_array(arr, pandas_dtype: bool = False):
array(['1', '1'], dtype='<U21')
>>> infer_dtype_from_array([1, '1'])
- (<class 'numpy.object_'>, [1, '1'])
+ (dtype('O'), [1, '1'])
"""
if isinstance(arr, np.ndarray):
return arr.dtype, arr
@@ -755,7 +756,7 @@ def infer_dtype_from_array(arr, pandas_dtype: bool = False):
# don't force numpy coerce with nan's
inferred = lib.infer_dtype(arr, skipna=False)
if inferred in ["string", "bytes", "mixed", "mixed-integer"]:
- return (np.object_, arr)
+ return (np.dtype(np.object_), arr)
arr = np.asarray(arr)
return arr.dtype, arr
@@ -1469,7 +1470,7 @@ def find_common_type(types):
return np.find_common_type(types, [])
-def cast_scalar_to_array(shape, value, dtype=None):
+def cast_scalar_to_array(shape, value, dtype: Optional[DtypeObj] = None) -> np.ndarray:
"""
Create np.ndarray of specified shape and dtype, filled with values.
@@ -1496,7 +1497,9 @@ def cast_scalar_to_array(shape, value, dtype=None):
return values
-def construct_1d_arraylike_from_scalar(value, length: int, dtype):
+def construct_1d_arraylike_from_scalar(
+ value, length: int, dtype: DtypeObj
+) -> ArrayLike:
"""
create a np.ndarray / pandas type of specified shape and dtype
filled with values
@@ -1505,7 +1508,7 @@ def construct_1d_arraylike_from_scalar(value, length: int, dtype):
----------
value : scalar value
length : int
- dtype : pandas_dtype / np.dtype
+ dtype : pandas_dtype or np.dtype
Returns
-------
@@ -1517,8 +1520,6 @@ def construct_1d_arraylike_from_scalar(value, length: int, dtype):
subarr = cls._from_sequence([value] * length, dtype=dtype)
else:
- if not isinstance(dtype, (np.dtype, type(np.dtype))):
- dtype = dtype.dtype
if length and is_integer_dtype(dtype) and isna(value):
# coerce if we have nan for an integer dtype
@@ -1536,7 +1537,7 @@ def construct_1d_arraylike_from_scalar(value, length: int, dtype):
return subarr
-def construct_1d_object_array_from_listlike(values):
+def construct_1d_object_array_from_listlike(values) -> np.ndarray:
"""
Transform any list-like object in a 1-dimensional numpy array of object
dtype.
@@ -1561,7 +1562,9 @@ def construct_1d_object_array_from_listlike(values):
return result
-def construct_1d_ndarray_preserving_na(values, dtype=None, copy: bool = False):
+def construct_1d_ndarray_preserving_na(
+ values, dtype: Optional[DtypeObj] = None, copy: bool = False
+) -> np.ndarray:
"""
Construct a new ndarray, coercing `values` to `dtype`, preserving NA.
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 8228edb12b29a..6ff72691ca757 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -104,6 +104,7 @@
is_scalar,
is_sequence,
needs_i8_conversion,
+ pandas_dtype,
)
from pandas.core.dtypes.generic import (
ABCDataFrame,
@@ -1917,7 +1918,12 @@ def to_records(
@classmethod
def _from_arrays(
- cls, arrays, columns, index, dtype=None, verify_integrity=True
+ cls,
+ arrays,
+ columns,
+ index,
+ dtype: Optional[Dtype] = None,
+ verify_integrity: bool = True,
) -> "DataFrame":
"""
Create DataFrame from a list of arrays corresponding to the columns.
@@ -1943,6 +1949,9 @@ def _from_arrays(
-------
DataFrame
"""
+ if dtype is not None:
+ dtype = pandas_dtype(dtype)
+
mgr = arrays_to_mgr(
arrays,
columns,
diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py
index 5c9e4b96047ee..ce3f07d06d6a2 100644
--- a/pandas/core/internals/construction.py
+++ b/pandas/core/internals/construction.py
@@ -3,13 +3,13 @@
constructors before passing them to a BlockManager.
"""
from collections import abc
-from typing import Dict, List, Optional, Tuple, Union
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple, Union
import numpy as np
import numpy.ma as ma
from pandas._libs import lib
-from pandas._typing import Axis, Dtype, Scalar
+from pandas._typing import Axis, DtypeObj, Scalar
from pandas.core.dtypes.cast import (
construct_1d_arraylike_from_scalar,
@@ -50,12 +50,20 @@
create_block_manager_from_blocks,
)
+if TYPE_CHECKING:
+ from pandas import Series # noqa:F401
+
# ---------------------------------------------------------------------
# BlockManager Interface
def arrays_to_mgr(
- arrays, arr_names, index, columns, dtype=None, verify_integrity: bool = True
+ arrays,
+ arr_names,
+ index,
+ columns,
+ dtype: Optional[DtypeObj] = None,
+ verify_integrity: bool = True,
):
"""
Segregate Series based on type and coerce into matrices.
@@ -85,7 +93,9 @@ def arrays_to_mgr(
return create_block_manager_from_arrays(arrays, arr_names, axes)
-def masked_rec_array_to_mgr(data, index, columns, dtype, copy: bool):
+def masked_rec_array_to_mgr(
+ data, index, columns, dtype: Optional[DtypeObj], copy: bool
+):
"""
Extract from a masked rec array and create the manager.
"""
@@ -130,7 +140,7 @@ def masked_rec_array_to_mgr(data, index, columns, dtype, copy: bool):
# DataFrame Constructor Interface
-def init_ndarray(values, index, columns, dtype=None, copy=False):
+def init_ndarray(values, index, columns, dtype: Optional[DtypeObj], copy: bool):
# input must be a ndarray, list, Series, index
if isinstance(values, ABCSeries):
@@ -189,7 +199,10 @@ def init_ndarray(values, index, columns, dtype=None, copy=False):
f"failed to cast to '{dtype}' (Exception was: {orig})"
) from orig
- index, columns = _get_axes(*values.shape, index=index, columns=columns)
+ # _prep_ndarray ensures that values.ndim == 2 at this point
+ index, columns = _get_axes(
+ values.shape[0], values.shape[1], index=index, columns=columns
+ )
values = values.T
# if we don't have a dtype specified, then try to convert objects
@@ -221,13 +234,15 @@ def init_ndarray(values, index, columns, dtype=None, copy=False):
return create_block_manager_from_blocks(block_values, [columns, index])
-def init_dict(data, index, columns, dtype=None):
+def init_dict(data: Dict, index, columns, dtype: Optional[DtypeObj] = None):
"""
Segregate Series based on type and coerce into matrices.
Needs to handle a lot of exceptional cases.
"""
+ arrays: Union[Sequence[Any], "Series"]
+
if columns is not None:
- from pandas.core.series import Series
+ from pandas.core.series import Series # noqa:F811
arrays = Series(data, index=columns, dtype=object)
data_names = arrays.index
@@ -244,7 +259,7 @@ def init_dict(data, index, columns, dtype=None):
if missing.any() and not is_integer_dtype(dtype):
if dtype is None or np.issubdtype(dtype, np.flexible):
# GH#1783
- nan_dtype = object
+ nan_dtype = np.dtype(object)
else:
nan_dtype = dtype
val = construct_1d_arraylike_from_scalar(np.nan, len(index), nan_dtype)
@@ -253,7 +268,7 @@ def init_dict(data, index, columns, dtype=None):
else:
keys = list(data.keys())
columns = data_names = Index(keys)
- arrays = (com.maybe_iterable_to_list(data[k]) for k in keys)
+ arrays = [com.maybe_iterable_to_list(data[k]) for k in keys]
# GH#24096 need copy to be deep for datetime64tz case
# TODO: See if we can avoid these copies
arrays = [
@@ -308,7 +323,7 @@ def convert(v):
return values
-def _homogenize(data, index, dtype=None):
+def _homogenize(data, index, dtype: Optional[DtypeObj]):
oindex = None
homogenized = []
@@ -339,7 +354,10 @@ def _homogenize(data, index, dtype=None):
return homogenized
-def extract_index(data):
+def extract_index(data) -> Index:
+ """
+ Try to infer an Index from the passed data, raise ValueError on failure.
+ """
index = None
if len(data) == 0:
index = Index([])
@@ -381,6 +399,7 @@ def extract_index(data):
)
if have_series:
+ assert index is not None # for mypy
if lengths[0] != len(index):
msg = (
f"array length {lengths[0]} does not match index "
@@ -442,7 +461,8 @@ def _get_axes(N, K, index, columns) -> Tuple[Index, Index]:
def dataclasses_to_dicts(data):
- """ Converts a list of dataclass instances to a list of dictionaries
+ """
+ Converts a list of dataclass instances to a list of dictionaries.
Parameters
----------
@@ -472,7 +492,9 @@ def dataclasses_to_dicts(data):
# Conversion of Inputs to Arrays
-def to_arrays(data, columns, coerce_float=False, dtype=None):
+def to_arrays(
+ data, columns, coerce_float: bool = False, dtype: Optional[DtypeObj] = None
+):
"""
Return list of arrays, columns.
"""
@@ -527,7 +549,7 @@ def _list_to_arrays(
data: List[Scalar],
columns: Union[Index, List],
coerce_float: bool = False,
- dtype: Optional[Dtype] = None,
+ dtype: Optional[DtypeObj] = None,
) -> Tuple[List[Scalar], Union[Index, List[Axis]]]:
if len(data) > 0 and isinstance(data[0], tuple):
content = list(lib.to_object_array_tuples(data).T)
@@ -547,7 +569,7 @@ def _list_of_series_to_arrays(
data: List,
columns: Union[Index, List],
coerce_float: bool = False,
- dtype: Optional[Dtype] = None,
+ dtype: Optional[DtypeObj] = None,
) -> Tuple[List[Scalar], Union[Index, List[Axis]]]:
if columns is None:
# We know pass_data is non-empty because data[0] is a Series
@@ -585,7 +607,7 @@ def _list_of_dict_to_arrays(
data: List,
columns: Union[Index, List],
coerce_float: bool = False,
- dtype: Optional[Dtype] = None,
+ dtype: Optional[DtypeObj] = None,
) -> Tuple[List[Scalar], Union[Index, List[Axis]]]:
"""
Convert list of dicts to numpy arrays
@@ -624,7 +646,7 @@ def _list_of_dict_to_arrays(
def _validate_or_indexify_columns(
- content: List, columns: Union[Index, List, None]
+ content: List, columns: Optional[Union[Index, List]]
) -> Union[Index, List[Axis]]:
"""
If columns is None, make numbers as column names; Otherwise, validate that
@@ -682,7 +704,7 @@ def _validate_or_indexify_columns(
def _convert_object_array(
- content: List[Scalar], coerce_float: bool = False, dtype: Optional[Dtype] = None
+ content: List[Scalar], coerce_float: bool = False, dtype: Optional[DtypeObj] = None
) -> List[Scalar]:
"""
Internal function ot convert object array.
@@ -699,7 +721,7 @@ def _convert_object_array(
"""
# provide soft conversion of object dtypes
def convert(arr):
- if dtype != object and dtype != np.object:
+ if dtype != np.dtype("O"):
arr = lib.maybe_convert_objects(arr, try_float=coerce_float)
arr = maybe_cast_to_datetime(arr, dtype)
return arr
| https://api.github.com/repos/pandas-dev/pandas/pulls/33725 | 2020-04-22T14:47:13Z | 2020-04-24T12:05:47Z | 2020-04-24T12:05:47Z | 2020-04-24T14:27:24Z | |
CLN: misc cleanups from LGTM.com | diff --git a/pandas/_testing.py b/pandas/_testing.py
index 4f957b7a55e3a..21e74dafcc944 100644
--- a/pandas/_testing.py
+++ b/pandas/_testing.py
@@ -279,16 +279,10 @@ def write_to_compressed(compression, path, data, dest="test"):
ValueError : An invalid compression value was passed in.
"""
if compression == "zip":
- import zipfile
-
compress_method = zipfile.ZipFile
elif compression == "gzip":
- import gzip
-
compress_method = gzip.GzipFile
elif compression == "bz2":
- import bz2
-
compress_method = bz2.BZ2File
elif compression == "xz":
compress_method = _get_lzma_file(lzma)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 202cb6488446e..d0276af2e9948 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -8218,7 +8218,6 @@ def blk_func(values):
result = result.iloc[0].rename(None)
return result
- data = self
if numeric_only is None:
data = self
values = data.values
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 9ef865a964123..a9db60f23f2e2 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -275,7 +275,6 @@ def __init__(
"Cannot construct a Series from an ndarray with "
"compound dtype. Use DataFrame instead."
)
- pass
elif isinstance(data, ABCSeries):
if index is None:
index = data.index
| https://api.github.com/repos/pandas-dev/pandas/pulls/33724 | 2020-04-22T13:55:34Z | 2020-04-23T03:09:11Z | 2020-04-23T03:09:11Z | 2020-04-23T07:03:00Z | |
BUG: Propagate Python exceptions from c_is_list_like (#33721) | diff --git a/pandas/_libs/lib.pxd b/pandas/_libs/lib.pxd
index 12aca9dabe2e7..b3c72c30a74de 100644
--- a/pandas/_libs/lib.pxd
+++ b/pandas/_libs/lib.pxd
@@ -1 +1 @@
-cdef bint c_is_list_like(object, bint)
+cdef bint c_is_list_like(object, bint) except -1
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index 5256bdc988995..14efab735fa7d 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -988,7 +988,7 @@ def is_list_like(obj: object, allow_sets: bool = True) -> bool:
return c_is_list_like(obj, allow_sets)
-cdef inline bint c_is_list_like(object obj, bint allow_sets):
+cdef inline bint c_is_list_like(object obj, bint allow_sets) except -1:
return (
isinstance(obj, abc.Iterable)
# we do not count strings/unicode/bytes as list-like
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py
index 8b20f9ada8ff7..4c4a5547247fc 100644
--- a/pandas/tests/dtypes/test_inference.py
+++ b/pandas/tests/dtypes/test_inference.py
@@ -123,6 +123,17 @@ def test_is_list_like_disallow_sets(maybe_list_like):
assert inference.is_list_like(obj, allow_sets=False) == expected
+def test_is_list_like_recursion():
+ # GH 33721
+ # interpreter would crash with with SIGABRT
+ def foo():
+ inference.is_list_like([])
+ foo()
+
+ with pytest.raises(RecursionError):
+ foo()
+
+
def test_is_sequence():
is_seq = inference.is_sequence
assert is_seq((1, 2))
| - [x] closes #33721
- [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/33723 | 2020-04-22T13:45:47Z | 2020-04-27T18:58:07Z | 2020-04-27T18:58:07Z | 2020-04-27T18:58:11Z |
TYP: add types to DataFrame._get_agg_axis | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 6c3523f830e97..04ebaf26fc11c 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -8548,7 +8548,7 @@ def idxmax(self, axis=0, skipna=True) -> Series:
result = [index[i] if i >= 0 else np.nan for i in indices]
return Series(result, index=self._get_agg_axis(axis))
- def _get_agg_axis(self, axis_num):
+ def _get_agg_axis(self, axis_num: int) -> Index:
"""
Let's be explicit about this.
"""
| Minor followup to #33610. | https://api.github.com/repos/pandas-dev/pandas/pulls/33722 | 2020-04-22T13:43:03Z | 2020-04-22T18:31:51Z | 2020-04-22T18:31:51Z | 2020-04-22T18:31:58Z |
BUG: DTA/TDA/PA setitem incorrectly allowing i8 | diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 9bc0dd7cc02e6..e902c4f7eb14f 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -773,7 +773,7 @@ def _validate_fill_value(self, fill_value):
return fill_value
def _validate_shift_value(self, fill_value):
- # TODO(2.0): once this deprecation is enforced, used _validate_fill_value
+ # TODO(2.0): once this deprecation is enforced, use _validate_fill_value
if is_valid_nat_for_dtype(fill_value, self.dtype):
fill_value = NaT
elif not isinstance(fill_value, self._recognized_scalars):
@@ -813,6 +813,9 @@ def _validate_searchsorted_value(self, value):
elif isinstance(value, self._recognized_scalars):
value = self._scalar_type(value)
+ elif isinstance(value, type(self)):
+ pass
+
elif is_list_like(value) and not isinstance(value, type(self)):
value = array(value)
@@ -822,7 +825,7 @@ def _validate_searchsorted_value(self, value):
f"not {type(value).__name__}"
)
- if not (isinstance(value, (self._scalar_type, type(self))) or (value is NaT)):
+ else:
raise TypeError(f"Unexpected type for 'value': {type(value)}")
if isinstance(value, type(self)):
@@ -834,18 +837,28 @@ def _validate_searchsorted_value(self, value):
return value
def _validate_setitem_value(self, value):
- if lib.is_scalar(value) and not isna(value):
- value = com.maybe_box_datetimelike(value)
if is_list_like(value):
- value = type(self)._from_sequence(value, dtype=self.dtype)
- self._check_compatible_with(value, setitem=True)
- value = value.asi8
- elif isinstance(value, self._scalar_type):
- self._check_compatible_with(value, setitem=True)
- value = self._unbox_scalar(value)
+ value = array(value)
+ if is_dtype_equal(value.dtype, "string"):
+ # We got a StringArray
+ try:
+ # TODO: Could use from_sequence_of_strings if implemented
+ # Note: passing dtype is necessary for PeriodArray tests
+ value = type(self)._from_sequence(value, dtype=self.dtype)
+ except ValueError:
+ pass
+
+ if not type(self)._is_recognized_dtype(value):
+ raise TypeError(
+ "setitem requires compatible dtype or scalar, "
+ f"not {type(value).__name__}"
+ )
+
+ elif isinstance(value, self._recognized_scalars):
+ value = self._scalar_type(value)
elif is_valid_nat_for_dtype(value, self.dtype):
- value = iNaT
+ value = NaT
else:
msg = (
f"'value' should be a '{self._scalar_type.__name__}', 'NaT', "
@@ -853,6 +866,12 @@ def _validate_setitem_value(self, value):
)
raise TypeError(msg)
+ self._check_compatible_with(value, setitem=True)
+ if isinstance(value, type(self)):
+ value = value.asi8
+ else:
+ value = self._unbox_scalar(value)
+
return value
def _validate_insert_value(self, value):
diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py
index 5b703cfe8fae5..e84ebf3e479f1 100644
--- a/pandas/tests/arrays/test_datetimelike.py
+++ b/pandas/tests/arrays/test_datetimelike.py
@@ -241,6 +241,16 @@ def test_setitem(self):
expected[:2] = expected[-2:]
tm.assert_numpy_array_equal(arr.asi8, expected)
+ def test_setitem_str_array(self, arr1d):
+ if isinstance(arr1d, DatetimeArray) and arr1d.tz is not None:
+ pytest.xfail(reason="timezone comparisons inconsistent")
+ expected = arr1d.copy()
+ expected[[0, 1]] = arr1d[-2:]
+
+ arr1d[:2] = [str(x) for x in arr1d[-2:]]
+
+ tm.assert_equal(arr1d, expected)
+
def test_setitem_raises(self):
data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
arr = self.array_cls(data, freq="D")
@@ -252,6 +262,17 @@ def test_setitem_raises(self):
with pytest.raises(TypeError, match="'value' should be a.* 'object'"):
arr[0] = object()
+ @pytest.mark.parametrize("box", [list, np.array, pd.Index, pd.Series])
+ def test_setitem_numeric_raises(self, arr1d, box):
+ # We dont case e.g. int64 to our own dtype for setitem
+
+ msg = "requires compatible dtype"
+ with pytest.raises(TypeError, match=msg):
+ arr1d[:2] = box([0, 1])
+
+ with pytest.raises(TypeError, match=msg):
+ arr1d[:2] = box([0.0, 1.0])
+
def test_inplace_arithmetic(self):
# GH#24115 check that iadd and isub are actually in-place
data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/33717 | 2020-04-21T23:26:39Z | 2020-04-30T13:44:37Z | 2020-04-30T13:44:37Z | 2020-05-04T20:03:22Z |
REF: implement _validate_comparison_value | diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 27b2ed822a49f..63932e64d3b05 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -60,29 +60,24 @@ def _datetimelike_array_cmp(cls, op):
opname = f"__{op.__name__}__"
nat_result = opname == "__ne__"
- @unpack_zerodim_and_defer(opname)
- def wrapper(self, other):
+ class InvalidComparison(Exception):
+ pass
+ def _validate_comparison_value(self, other):
if isinstance(other, str):
try:
# GH#18435 strings get a pass from tzawareness compat
other = self._scalar_from_string(other)
except ValueError:
# failed to parse as Timestamp/Timedelta/Period
- return invalid_comparison(self, other, op)
+ raise InvalidComparison(other)
if isinstance(other, self._recognized_scalars) or other is NaT:
other = self._scalar_type(other)
self._check_compatible_with(other)
- other_i8 = self._unbox_scalar(other)
-
- result = op(self.view("i8"), other_i8)
- if isna(other):
- result.fill(nat_result)
-
elif not is_list_like(other):
- return invalid_comparison(self, other, op)
+ raise InvalidComparison(other)
elif len(other) != len(self):
raise ValueError("Lengths must match")
@@ -93,34 +88,50 @@ def wrapper(self, other):
other = np.array(other)
if not isinstance(other, (np.ndarray, type(self))):
- return invalid_comparison(self, other, op)
-
- if is_object_dtype(other):
- # We have to use comp_method_OBJECT_ARRAY instead of numpy
- # comparison otherwise it would fail to raise when
- # comparing tz-aware and tz-naive
- with np.errstate(all="ignore"):
- result = ops.comp_method_OBJECT_ARRAY(
- op, self.astype(object), other
- )
- o_mask = isna(other)
+ raise InvalidComparison(other)
+
+ elif is_object_dtype(other.dtype):
+ pass
elif not type(self)._is_recognized_dtype(other.dtype):
- return invalid_comparison(self, other, op)
+ raise InvalidComparison(other)
else:
# For PeriodDType this casting is unnecessary
+ # TODO: use Index to do inference?
other = type(self)._from_sequence(other)
self._check_compatible_with(other)
- result = op(self.view("i8"), other.view("i8"))
- o_mask = other._isnan
+ return other
- if o_mask.any():
- result[o_mask] = nat_result
+ @unpack_zerodim_and_defer(opname)
+ def wrapper(self, other):
- if self._hasnans:
- result[self._isnan] = nat_result
+ try:
+ other = _validate_comparison_value(self, other)
+ except InvalidComparison:
+ return invalid_comparison(self, other, op)
+
+ dtype = getattr(other, "dtype", None)
+ if is_object_dtype(dtype):
+ # We have to use comp_method_OBJECT_ARRAY instead of numpy
+ # comparison otherwise it would fail to raise when
+ # comparing tz-aware and tz-naive
+ with np.errstate(all="ignore"):
+ result = ops.comp_method_OBJECT_ARRAY(op, self.astype(object), other)
+ return result
+
+ if isinstance(other, self._scalar_type) or other is NaT:
+ other_i8 = self._unbox_scalar(other)
+ else:
+ # Then type(other) == type(self)
+ other_i8 = other.asi8
+
+ result = op(self.asi8, other_i8)
+
+ o_mask = isna(other)
+ if self._hasnans | np.any(o_mask):
+ result[self._isnan | o_mask] = nat_result
return result
| Trying to match the patterns we use for all the other DTA/TDA/PA methods that have an `other`-like arg.
No logic should be changed here, just moved around. | https://api.github.com/repos/pandas-dev/pandas/pulls/33716 | 2020-04-21T23:15:51Z | 2020-04-23T17:58:38Z | 2020-04-23T17:58:38Z | 2020-04-23T18:03:37Z |
BUG: DTI/TDI/PI.where accepting incorrectly-typed NaTs | diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index af5834f01c24c..3fd0a7f4467a8 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -869,27 +869,33 @@ def _validate_insert_value(self, value):
def _validate_where_value(self, other):
if is_valid_nat_for_dtype(other, self.dtype):
- other = NaT.value
+ other = NaT
+ elif isinstance(other, self._recognized_scalars):
+ other = self._scalar_type(other)
+ self._check_compatible_with(other, setitem=True)
elif not is_list_like(other):
- # TODO: what about own-type scalars?
raise TypeError(f"Where requires matching dtype, not {type(other)}")
else:
# Do type inference if necessary up front
# e.g. we passed PeriodIndex.values and got an ndarray of Periods
- from pandas import Index
-
- other = Index(other)
+ other = array(other)
+ other = extract_array(other, extract_numpy=True)
- if is_categorical_dtype(other):
+ if is_categorical_dtype(other.dtype):
# e.g. we have a Categorical holding self.dtype
if is_dtype_equal(other.categories.dtype, self.dtype):
other = other._internal_get_values()
- if not is_dtype_equal(self.dtype, other.dtype):
+ if not type(self)._is_recognized_dtype(other.dtype):
raise TypeError(f"Where requires matching dtype, not {other.dtype}")
+ self._check_compatible_with(other, setitem=True)
+ if lib.is_scalar(other):
+ other = self._unbox_scalar(other)
+ else:
other = other.view("i8")
+
return other
# ------------------------------------------------------------------
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index 2200eadf3874f..838bece11b050 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -530,7 +530,12 @@ def isin(self, values, level=None):
def where(self, cond, other=None):
values = self.view("i8")
- other = self._data._validate_where_value(other)
+ try:
+ other = self._data._validate_where_value(other)
+ except (TypeError, ValueError) as err:
+ # Includes tzawareness mismatch and IncompatibleFrequencyError
+ oth = getattr(other, "dtype", other)
+ raise TypeError(f"Where requires matching dtype, not {oth}") from err
result = np.where(cond, values, other).astype("i8")
arr = type(self._data)._simple_new(result, dtype=self.dtype)
diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py
index f9b8bd27b7f5a..d813604400f9a 100644
--- a/pandas/tests/indexes/datetimes/test_indexing.py
+++ b/pandas/tests/indexes/datetimes/test_indexing.py
@@ -197,9 +197,15 @@ def test_where_invalid_dtypes(self):
# non-matching scalar
dti.where(notna(i2), pd.Timedelta(days=4))
- with pytest.raises(TypeError, match="Where requires matching dtype"):
- # non-matching NA value
- dti.where(notna(i2), np.timedelta64("NaT", "ns"))
+ def test_where_mismatched_nat(self, tz_aware_fixture):
+ tz = tz_aware_fixture
+ dti = pd.date_range("2013-01-01", periods=3, tz=tz)
+ cond = np.array([True, False, True])
+
+ msg = "Where requires matching dtype"
+ with pytest.raises(TypeError, match=msg):
+ # wrong-dtyped NaT
+ dti.where(cond, np.timedelta64("NaT", "ns"))
def test_where_tz(self):
i = pd.date_range("20130101", periods=3, tz="US/Eastern")
diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py
index bd71c04a9ab03..f0efff4bbdd88 100644
--- a/pandas/tests/indexes/period/test_indexing.py
+++ b/pandas/tests/indexes/period/test_indexing.py
@@ -541,9 +541,14 @@ def test_where_invalid_dtypes(self):
# non-matching scalar
pi.where(notna(i2), Timedelta(days=4))
- with pytest.raises(TypeError, match="Where requires matching dtype"):
- # non-matching NA value
- pi.where(notna(i2), np.timedelta64("NaT", "ns"))
+ def test_where_mismatched_nat(self):
+ pi = period_range("20130101", periods=5, freq="D")
+ cond = np.array([True, False, True, True, False])
+
+ msg = "Where requires matching dtype"
+ with pytest.raises(TypeError, match=msg):
+ # wrong-dtyped NaT
+ pi.where(cond, np.timedelta64("NaT", "ns"))
class TestTake:
diff --git a/pandas/tests/indexes/timedeltas/test_indexing.py b/pandas/tests/indexes/timedeltas/test_indexing.py
index 17feed3fd7a68..396a676b97a1b 100644
--- a/pandas/tests/indexes/timedeltas/test_indexing.py
+++ b/pandas/tests/indexes/timedeltas/test_indexing.py
@@ -163,9 +163,14 @@ def test_where_invalid_dtypes(self):
# non-matching scalar
tdi.where(notna(i2), pd.Timestamp.now())
- with pytest.raises(TypeError, match="Where requires matching dtype"):
- # non-matching NA value
- tdi.where(notna(i2), np.datetime64("NaT", "ns"))
+ def test_where_mismatched_nat(self):
+ tdi = timedelta_range("1 day", periods=3, freq="D", name="idx")
+ cond = np.array([True, False, False])
+
+ msg = "Where requires matching dtype"
+ with pytest.raises(TypeError, match=msg):
+ # wrong-dtyped NaT
+ tdi.where(cond, np.datetime64("NaT", "ns"))
class TestTake:
diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py
index 6cb73823adabb..1e362827e823b 100644
--- a/pandas/tests/indexing/test_coercion.py
+++ b/pandas/tests/indexing/test_coercion.py
@@ -1,3 +1,4 @@
+from datetime import timedelta
import itertools
from typing import Dict, List
@@ -686,8 +687,15 @@ def test_where_series_datetime64(self, fill_val, exp_dtype):
)
self._assert_where_conversion(obj, cond, values, exp, exp_dtype)
- def test_where_index_datetime(self):
- fill_val = pd.Timestamp("2012-01-01")
+ @pytest.mark.parametrize(
+ "fill_val",
+ [
+ pd.Timestamp("2012-01-01"),
+ pd.Timestamp("2012-01-01").to_datetime64(),
+ pd.Timestamp("2012-01-01").to_pydatetime(),
+ ],
+ )
+ def test_where_index_datetime(self, fill_val):
exp_dtype = "datetime64[ns]"
obj = pd.Index(
[
@@ -700,9 +708,9 @@ def test_where_index_datetime(self):
assert obj.dtype == "datetime64[ns]"
cond = pd.Index([True, False, True, False])
- msg = "Where requires matching dtype, not .*Timestamp"
- with pytest.raises(TypeError, match=msg):
- obj.where(cond, fill_val)
+ result = obj.where(cond, fill_val)
+ expected = pd.DatetimeIndex([obj[0], fill_val, obj[2], fill_val])
+ tm.assert_index_equal(result, expected)
values = pd.Index(pd.date_range(fill_val, periods=4))
exp = pd.Index(
@@ -717,7 +725,7 @@ def test_where_index_datetime(self):
self._assert_where_conversion(obj, cond, values, exp, exp_dtype)
@pytest.mark.xfail(reason="GH 22839: do not ignore timezone, must be object")
- def test_where_index_datetimetz(self):
+ def test_where_index_datetime64tz(self):
fill_val = pd.Timestamp("2012-01-01", tz="US/Eastern")
exp_dtype = np.object
obj = pd.Index(
@@ -754,23 +762,53 @@ def test_where_index_complex128(self):
def test_where_index_bool(self):
pass
- def test_where_series_datetime64tz(self):
- pass
-
def test_where_series_timedelta64(self):
pass
def test_where_series_period(self):
pass
- def test_where_index_datetime64tz(self):
- pass
+ @pytest.mark.parametrize(
+ "value", [pd.Timedelta(days=9), timedelta(days=9), np.timedelta64(9, "D")]
+ )
+ def test_where_index_timedelta64(self, value):
+ tdi = pd.timedelta_range("1 Day", periods=4)
+ cond = np.array([True, False, False, True])
- def test_where_index_timedelta64(self):
- pass
+ expected = pd.TimedeltaIndex(["1 Day", value, value, "4 Days"])
+ result = tdi.where(cond, value)
+ tm.assert_index_equal(result, expected)
+
+ msg = "Where requires matching dtype"
+ with pytest.raises(TypeError, match=msg):
+ # wrong-dtyped NaT
+ tdi.where(cond, np.datetime64("NaT", "ns"))
def test_where_index_period(self):
- pass
+ dti = pd.date_range("2016-01-01", periods=3, freq="QS")
+ pi = dti.to_period("Q")
+
+ cond = np.array([False, True, False])
+
+ # Passinga valid scalar
+ value = pi[-1] + pi.freq * 10
+ expected = pd.PeriodIndex([value, pi[1], value])
+ result = pi.where(cond, value)
+ tm.assert_index_equal(result, expected)
+
+ # Case passing ndarray[object] of Periods
+ other = np.asarray(pi + pi.freq * 10, dtype=object)
+ result = pi.where(cond, other)
+ expected = pd.PeriodIndex([other[0], pi[1], other[2]])
+ tm.assert_index_equal(result, expected)
+
+ # Passing a mismatched scalar
+ msg = "Where requires matching dtype"
+ with pytest.raises(TypeError, match=msg):
+ pi.where(cond, pd.Timedelta(days=4))
+
+ with pytest.raises(TypeError, match=msg):
+ pi.where(cond, pd.Period("2020-04-21", "D"))
class TestFillnaSeriesCoercion(CoercionBase):
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
In addition to the bug in the title, this makes DTI accept datetime/dt64, TDI accept timedelta/td64, and PI accept Period. This brings these into closer alignment with the other methods, which we ultimately want to make as consistent as possible.
| https://api.github.com/repos/pandas-dev/pandas/pulls/33715 | 2020-04-21T23:08:10Z | 2020-04-25T22:22:42Z | 2020-04-25T22:22:42Z | 2020-04-25T22:26:43Z |
CLN: simplify DTA.__getitem__ | diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 27b2ed822a49f..5237bc6226169 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -527,21 +527,6 @@ def __getitem__(self, key):
This getitem defers to the underlying array, which by-definition can
only handle list-likes, slices, and integer scalars
"""
- is_int = lib.is_integer(key)
- if lib.is_scalar(key) and not is_int:
- raise IndexError(
- "only integers, slices (`:`), ellipsis (`...`), "
- "numpy.newaxis (`None`) and integer or boolean "
- "arrays are valid indices"
- )
-
- getitem = self._data.__getitem__
- if is_int:
- val = getitem(key)
- if lib.is_scalar(val):
- # i.e. self.ndim == 1
- return self._box_func(val)
- return type(self)(val, dtype=self.dtype)
if com.is_bool_indexer(key):
# first convert to boolean, because check_array_indexer doesn't
@@ -558,6 +543,16 @@ def __getitem__(self, key):
else:
key = check_array_indexer(self, key)
+ freq = self._get_getitem_freq(key)
+ result = self._data[key]
+ if lib.is_scalar(result):
+ return self._box_func(result)
+ return self._simple_new(result, dtype=self.dtype, freq=freq)
+
+ def _get_getitem_freq(self, key):
+ """
+ Find the `freq` attribute to assign to the result of a __getitem__ lookup.
+ """
is_period = is_period_dtype(self.dtype)
if is_period:
freq = self.freq
@@ -572,11 +567,7 @@ def __getitem__(self, key):
# GH#21282 indexing with Ellipsis is similar to a full slice,
# should preserve `freq` attribute
freq = self.freq
-
- result = getitem(key)
- if lib.is_scalar(result):
- return self._box_func(result)
- return self._simple_new(result, dtype=self.dtype, freq=freq)
+ return freq
def __setitem__(
self,
| https://api.github.com/repos/pandas-dev/pandas/pulls/33714 | 2020-04-21T22:48:35Z | 2020-04-24T21:41:43Z | 2020-04-24T21:41:43Z | 2020-04-24T22:20:20Z | |
CLN: .values -> ._values | diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py
index 235b3113a2ae7..89e1c0fea2b32 100644
--- a/pandas/core/groupby/grouper.py
+++ b/pandas/core/groupby/grouper.py
@@ -299,7 +299,7 @@ def __init__(
self.name = grouper.name
if isinstance(grouper, MultiIndex):
- self.grouper = grouper.values
+ self.grouper = grouper._values
# we have a single grouper which may be a myriad of things,
# some of which are dependent on the passing in level
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index b67e3347e6af0..9275e4ba3ed25 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -112,22 +112,22 @@ def cmp_method(self, other):
if other.ndim > 0 and len(self) != len(other):
raise ValueError("Lengths must match to compare")
- if is_object_dtype(self) and isinstance(other, ABCCategorical):
+ if is_object_dtype(self.dtype) and isinstance(other, ABCCategorical):
left = type(other)(self._values, dtype=other.dtype)
return op(left, other)
- elif is_object_dtype(self) and isinstance(other, ExtensionArray):
+ elif is_object_dtype(self.dtype) and isinstance(other, ExtensionArray):
# e.g. PeriodArray
with np.errstate(all="ignore"):
- result = op(self.values, other)
+ result = op(self._values, other)
- elif is_object_dtype(self) and not isinstance(self, ABCMultiIndex):
+ elif is_object_dtype(self.dtype) and not isinstance(self, ABCMultiIndex):
# don't pass MultiIndex
with np.errstate(all="ignore"):
- result = ops.comp_method_OBJECT_ARRAY(op, self.values, other)
+ result = ops.comp_method_OBJECT_ARRAY(op, self._values, other)
else:
with np.errstate(all="ignore"):
- result = op(self.values, np.asarray(other))
+ result = op(self._values, np.asarray(other))
if is_bool_dtype(result):
return result
@@ -510,7 +510,7 @@ def _shallow_copy(self, values=None, name: Label = no_default):
name = self.name if name is no_default else name
cache = self._cache.copy() if values is None else {}
if values is None:
- values = self.values
+ values = self._values
result = self._simple_new(values, name=name)
result._cache = cache
@@ -722,7 +722,7 @@ def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs):
indices = ensure_platform_int(indices)
if self._can_hold_na:
taken = self._assert_take_fillable(
- self.values,
+ self._values,
indices,
allow_fill=allow_fill,
fill_value=fill_value,
@@ -734,7 +734,7 @@ def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs):
raise ValueError(
f"Unable to fill values because {cls_name} cannot contain NA"
)
- taken = self.values.take(indices)
+ taken = self._values.take(indices)
return self._shallow_copy(taken)
def _assert_take_fillable(
@@ -1988,7 +1988,7 @@ def is_all_dates(self) -> bool:
"""
Whether or not the index values only consist of dates.
"""
- return is_datetime_array(ensure_object(self.values))
+ return is_datetime_array(ensure_object(self._values))
# --------------------------------------------------------------------
# Pickle Methods
@@ -2339,13 +2339,13 @@ def _get_unique_index(self, dropna: bool = False):
if self.is_unique and not dropna:
return self
- values = self.values
-
if not self.is_unique:
values = self.unique()
if not isinstance(self, ABCMultiIndex):
# extract an array to pass to _shallow_copy
values = values._data
+ else:
+ values = self._values
if dropna:
try:
| https://api.github.com/repos/pandas-dev/pandas/pulls/33713 | 2020-04-21T22:46:48Z | 2020-04-22T02:24:07Z | 2020-04-22T02:24:07Z | 2020-04-22T02:49:53Z | |
TST: more accurate expecteds for DTI/TDI | diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py
index a8e9ad9ff7cc9..ac3864bea5309 100644
--- a/pandas/tests/arithmetic/test_datetime64.py
+++ b/pandas/tests/arithmetic/test_datetime64.py
@@ -2052,6 +2052,7 @@ def test_dti_add_tdi(self, tz_naive_fixture):
dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
tdi = pd.timedelta_range("0 days", periods=10)
expected = pd.date_range("2017-01-01", periods=10, tz=tz)
+ expected = pd.DatetimeIndex(list(expected), freq=None)
# add with TimdeltaIndex
result = dti + tdi
@@ -2073,6 +2074,7 @@ def test_dti_iadd_tdi(self, tz_naive_fixture):
dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
tdi = pd.timedelta_range("0 days", periods=10)
expected = pd.date_range("2017-01-01", periods=10, tz=tz)
+ expected = pd.DatetimeIndex(list(expected), freq=None)
# iadd with TimdeltaIndex
result = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
@@ -2098,6 +2100,7 @@ def test_dti_sub_tdi(self, tz_naive_fixture):
dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
tdi = pd.timedelta_range("0 days", periods=10)
expected = pd.date_range("2017-01-01", periods=10, tz=tz, freq="-1D")
+ expected = pd.DatetimeIndex(list(expected), freq=None)
# sub with TimedeltaIndex
result = dti - tdi
@@ -2121,6 +2124,7 @@ def test_dti_isub_tdi(self, tz_naive_fixture):
dti = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
tdi = pd.timedelta_range("0 days", periods=10)
expected = pd.date_range("2017-01-01", periods=10, tz=tz, freq="-1D")
+ expected = pd.DatetimeIndex(list(expected), freq=None)
# isub with TimedeltaIndex
result = DatetimeIndex([Timestamp("2017-01-01", tz=tz)] * 10)
diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py
index 202e30287881f..3f3f99fada188 100644
--- a/pandas/tests/arithmetic/test_numeric.py
+++ b/pandas/tests/arithmetic/test_numeric.py
@@ -165,7 +165,7 @@ def test_numeric_arr_mul_tdscalar(self, scalar_td, numeric_idx, box):
# GH#19333
index = numeric_idx
- expected = pd.timedelta_range("0 days", "4 days")
+ expected = pd.TimedeltaIndex([pd.Timedelta(days=n) for n in range(5)])
index = tm.box_expected(index, box)
expected = tm.box_expected(expected, box)
diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py
index 8387e4d708662..59188126593ec 100644
--- a/pandas/tests/arithmetic/test_timedelta64.py
+++ b/pandas/tests/arithmetic/test_timedelta64.py
@@ -403,9 +403,7 @@ def _check(result, expected):
_check(result, expected)
result = dti_tz - td
- expected = DatetimeIndex(
- ["20121231", "20130101", "20130102"], tz="US/Eastern", freq="D"
- )
+ expected = DatetimeIndex(["20121231", "20130101", "20130102"], tz="US/Eastern")
tm.assert_index_equal(result, expected)
def test_dti_tdi_numeric_ops(self):
@@ -512,9 +510,9 @@ def test_timedelta(self, freq):
rng = pd.date_range("2013", "2014")
s = Series(rng)
result1 = rng - pd.offsets.Hour(1)
- result2 = DatetimeIndex(s - np.timedelta64(100000000))
+ result2 = DatetimeIndex(s - np.timedelta64(100000000), freq=rng.freq)
result3 = rng - np.timedelta64(100000000)
- result4 = DatetimeIndex(s - pd.offsets.Hour(1))
+ result4 = DatetimeIndex(s - pd.offsets.Hour(1), freq=rng.freq)
tm.assert_index_equal(result1, result4)
tm.assert_index_equal(result2, result3)
diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py
index dd0bac683c35c..e605754f69010 100644
--- a/pandas/tests/test_multilevel.py
+++ b/pandas/tests/test_multilevel.py
@@ -1505,6 +1505,7 @@ def test_set_index_datetime(self):
tz="US/Eastern",
)
idx3 = pd.date_range("2011-01-01 09:00", periods=6, tz="Asia/Tokyo")
+ idx3 = pd.DatetimeIndex(list(idx3), freq=None)
df = df.set_index(idx1)
df = df.set_index(idx2, append=True)
| xref #33711 | https://api.github.com/repos/pandas-dev/pandas/pulls/33712 | 2020-04-21T21:27:56Z | 2020-04-23T23:10:24Z | null | 2020-04-23T23:11:01Z |
TST: prepare for freq-checking in tests.io | diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py
index 0811f2f822198..1692e1a8a0dd3 100644
--- a/pandas/tests/io/excel/test_writers.py
+++ b/pandas/tests/io/excel/test_writers.py
@@ -407,6 +407,10 @@ def test_mixed(self, frame, path):
def test_ts_frame(self, tsframe, path):
df = tsframe
+ # freq doesnt round-trip
+ index = pd.DatetimeIndex(np.asarray(df.index), freq=None)
+ df.index = index
+
df.to_excel(path, "test1")
reader = ExcelFile(path)
@@ -476,6 +480,11 @@ def test_inf_roundtrip(self, path):
tm.assert_frame_equal(df, recons)
def test_sheets(self, frame, tsframe, path):
+
+ # freq doesnt round-trip
+ index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None)
+ tsframe.index = index
+
frame = frame.copy()
frame["A"][:5] = np.nan
@@ -581,6 +590,11 @@ def test_excel_roundtrip_indexname(self, merge_cells, path):
def test_excel_roundtrip_datetime(self, merge_cells, tsframe, path):
# datetime.date, not sure what to test here exactly
+
+ # freq does not round-trip
+ index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None)
+ tsframe.index = index
+
tsf = tsframe.copy()
tsf.index = [x.date() for x in tsframe.index]
diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py
index 0576d8e91d531..137e4c991d080 100644
--- a/pandas/tests/io/json/test_pandas.py
+++ b/pandas/tests/io/json/test_pandas.py
@@ -42,6 +42,23 @@ def setup(self):
yield
+ @pytest.fixture
+ def datetime_series(self):
+ # Same as usual datetime_series, but with index freq set to None,
+ # since that doesnt round-trip, see GH#33711
+ ser = tm.makeTimeSeries()
+ ser.name = "ts"
+ ser.index = ser.index._with_freq(None)
+ return ser
+
+ @pytest.fixture
+ def datetime_frame(self):
+ # Same as usual datetime_frame, but with index freq set to None,
+ # since that doesnt round-trip, see GH#33711
+ df = DataFrame(tm.getTimeSeriesData())
+ df.index = df.index._with_freq(None)
+ return df
+
def test_frame_double_encoded_labels(self, orient):
df = DataFrame(
[["a", "b"], ["c", "d"]],
@@ -416,6 +433,9 @@ def test_frame_mixedtype_orient(self): # GH10289
tm.assert_frame_equal(left, right)
def test_v12_compat(self, datapath):
+ dti = pd.date_range("2000-01-03", "2000-01-07")
+ # freq doesnt roundtrip
+ dti = pd.DatetimeIndex(np.asarray(dti), freq=None)
df = DataFrame(
[
[1.56808523, 0.65727391, 1.81021139, -0.17251653],
@@ -425,7 +445,7 @@ def test_v12_compat(self, datapath):
[0.05951614, -2.69652057, 1.28163262, 0.34703478],
],
columns=["A", "B", "C", "D"],
- index=pd.date_range("2000-01-03", "2000-01-07"),
+ index=dti,
)
df["date"] = pd.Timestamp("19920106 18:21:32.12")
df.iloc[3, df.columns.get_loc("date")] = pd.Timestamp("20130101")
@@ -444,6 +464,9 @@ def test_v12_compat(self, datapath):
def test_blocks_compat_GH9037(self):
index = pd.date_range("20000101", periods=10, freq="H")
+ # freq doesnt round-trip
+ index = pd.DatetimeIndex(list(index), freq=None)
+
df_mixed = DataFrame(
OrderedDict(
float_1=[
diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py
index 34dd9ba9bc7b6..28b043e65b848 100644
--- a/pandas/tests/io/json/test_ujson.py
+++ b/pandas/tests/io/json/test_ujson.py
@@ -1011,7 +1011,8 @@ def test_index(self):
def test_datetime_index(self):
date_unit = "ns"
- rng = date_range("1/1/2000", periods=20)
+ # freq doesnt round-trip
+ rng = DatetimeIndex(list(date_range("1/1/2000", periods=20)), freq=None)
encoded = ujson.encode(rng, date_unit=date_unit)
decoded = DatetimeIndex(np.array(ujson.decode(encoded)))
diff --git a/pandas/tests/io/parser/test_dtypes.py b/pandas/tests/io/parser/test_dtypes.py
index e68dcb3aa577e..d1ed85cc6f466 100644
--- a/pandas/tests/io/parser/test_dtypes.py
+++ b/pandas/tests/io/parser/test_dtypes.py
@@ -299,7 +299,8 @@ def test_categorical_coerces_numeric(all_parsers):
def test_categorical_coerces_datetime(all_parsers):
parser = all_parsers
- dtype = {"b": CategoricalDtype(pd.date_range("2017", "2019", freq="AS"))}
+ dti = pd.DatetimeIndex(["2017-01-01", "2018-01-01", "2019-01-01"], freq=None)
+ dtype = {"b": CategoricalDtype(dti)}
data = "b\n2017-01-01\n2018-01-01\n2019-01-01"
expected = DataFrame({"b": Categorical(dtype["b"].categories)})
diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py
index 2fcac6fa57cf8..e11bbb89c885c 100644
--- a/pandas/tests/io/parser/test_parse_dates.py
+++ b/pandas/tests/io/parser/test_parse_dates.py
@@ -681,8 +681,10 @@ def test_parse_dates_string(all_parsers):
"""
parser = all_parsers
result = parser.read_csv(StringIO(data), index_col="date", parse_dates=["date"])
- index = date_range("1/1/2009", periods=3)
- index.name = "date"
+ # freq doesnt round-trip
+ index = DatetimeIndex(
+ list(date_range("1/1/2009", periods=3)), name="date", freq=None
+ )
expected = DataFrame(
{"A": ["a", "b", "c"], "B": [1, 3, 4], "C": [2, 4, 5]}, index=index
@@ -1430,11 +1432,16 @@ def test_parse_timezone(all_parsers):
2018-01-04 09:05:00+09:00,23400"""
result = parser.read_csv(StringIO(data), parse_dates=["dt"])
- dti = pd.date_range(
- start="2018-01-04 09:01:00",
- end="2018-01-04 09:05:00",
- freq="1min",
- tz=pytz.FixedOffset(540),
+ dti = pd.DatetimeIndex(
+ list(
+ pd.date_range(
+ start="2018-01-04 09:01:00",
+ end="2018-01-04 09:05:00",
+ freq="1min",
+ tz=pytz.FixedOffset(540),
+ ),
+ ),
+ freq=None,
)
expected_data = {"dt": dti, "val": [23350, 23400, 23400, 23400, 23400]}
diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py
index 6b6ae8e5f0ca2..299ae2f41d676 100644
--- a/pandas/tests/io/pytables/test_store.py
+++ b/pandas/tests/io/pytables/test_store.py
@@ -1231,6 +1231,8 @@ def test_append_frame_column_oriented(self, setup_path):
# column oriented
df = tm.makeTimeDataFrame()
+ df.index = df.index._with_freq(None) # freq doesnt round-trip
+
_maybe_remove(store, "df1")
store.append("df1", df.iloc[:, :2], axes=["columns"])
store.append("df1", df.iloc[:, 2:])
diff --git a/pandas/tests/io/pytables/test_timezones.py b/pandas/tests/io/pytables/test_timezones.py
index 74d5a77f86827..38d32b0bdc8a3 100644
--- a/pandas/tests/io/pytables/test_timezones.py
+++ b/pandas/tests/io/pytables/test_timezones.py
@@ -106,17 +106,11 @@ def test_append_with_timezones_dateutil(setup_path):
# as index
with ensure_clean_store(setup_path) as store:
+ dti = date_range("2000-1-1", periods=3, freq="H", tz=gettz("US/Eastern"))
+ dti = dti._with_freq(None) # freq doesnt round-trip
+
# GH 4098 example
- df = DataFrame(
- dict(
- A=Series(
- range(3),
- index=date_range(
- "2000-1-1", periods=3, freq="H", tz=gettz("US/Eastern")
- ),
- )
- )
- )
+ df = DataFrame(dict(A=Series(range(3), index=dti,)))
_maybe_remove(store, "df")
store.put("df", df)
@@ -199,15 +193,11 @@ def test_append_with_timezones_pytz(setup_path):
# as index
with ensure_clean_store(setup_path) as store:
+ dti = date_range("2000-1-1", periods=3, freq="H", tz="US/Eastern")
+ dti = dti._with_freq(None) # freq doesnt round-trip
+
# GH 4098 example
- df = DataFrame(
- dict(
- A=Series(
- range(3),
- index=date_range("2000-1-1", periods=3, freq="H", tz="US/Eastern"),
- )
- )
- )
+ df = DataFrame(dict(A=Series(range(3), index=dti,)))
_maybe_remove(store, "df")
store.put("df", df)
@@ -258,6 +248,7 @@ def test_timezones_fixed(setup_path):
# index
rng = date_range("1/1/2000", "1/30/2000", tz="US/Eastern")
+ rng = rng._with_freq(None) # freq doesnt round-trip
df = DataFrame(np.random.randn(len(rng), 4), index=rng)
store["df"] = df
result = store["df"]
@@ -346,6 +337,7 @@ def test_dst_transitions(setup_path):
freq="H",
ambiguous="infer",
)
+ times = times._with_freq(None) # freq doesnt round-trip
for i in [times, times + pd.Timedelta("10min")]:
_maybe_remove(store, "df")
diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py
index 0755501ee6285..a2220ceb7feaa 100644
--- a/pandas/tests/io/test_feather.py
+++ b/pandas/tests/io/test_feather.py
@@ -63,14 +63,21 @@ def test_basic(self):
"bool": [True, False, True],
"bool_with_null": [True, np.nan, False],
"cat": pd.Categorical(list("abc")),
- "dt": pd.date_range("20130101", periods=3),
- "dttz": pd.date_range("20130101", periods=3, tz="US/Eastern"),
+ "dt": pd.DatetimeIndex(
+ list(pd.date_range("20130101", periods=3)), freq=None
+ ),
+ "dttz": pd.DatetimeIndex(
+ list(pd.date_range("20130101", periods=3, tz="US/Eastern")),
+ freq=None,
+ ),
"dt_with_null": [
pd.Timestamp("20130101"),
pd.NaT,
pd.Timestamp("20130103"),
],
- "dtns": pd.date_range("20130101", periods=3, freq="ns"),
+ "dtns": pd.DatetimeIndex(
+ list(pd.date_range("20130101", periods=3, freq="ns")), freq=None,
+ ),
}
)
if pyarrow_version >= LooseVersion("0.16.1.dev"):
diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index 94cf16c20e6c4..e70a06cc5f582 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -385,6 +385,8 @@ def test_write_index(self, engine):
# non-default index
for index in indexes:
df.index = index
+ if isinstance(index, pd.DatetimeIndex):
+ index._set_freq(None) # freq doesnt round-trip
check_round_trip(df, engine, check_names=check_names)
# index with meta-data
@@ -462,7 +464,9 @@ def test_basic(self, pa, df_full):
df = df_full
# additional supported types for pyarrow
- df["datetime_tz"] = pd.date_range("20130101", periods=3, tz="Europe/Brussels")
+ dti = pd.date_range("20130101", periods=3, tz="Europe/Brussels")
+ dti._set_freq(None) # freq doesnt round-trip
+ df["datetime_tz"] = dti
df["bool_with_none"] = [True, None, True]
check_round_trip(df, pa)
@@ -629,7 +633,9 @@ class TestParquetFastParquet(Base):
def test_basic(self, fp, df_full):
df = df_full
- df["datetime_tz"] = pd.date_range("20130101", periods=3, tz="US/Eastern")
+ dti = pd.date_range("20130101", periods=3, tz="US/Eastern")
+ dti._set_freq(None) # freq doesnt round-trip
+ df["datetime_tz"] = dti
df["timedelta"] = pd.timedelta_range("1 day", periods=3)
check_round_trip(df, fp)
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index 2f2ae8cd9d32b..70f3f99442183 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -1491,7 +1491,7 @@ def test_out_of_bounds_datetime(self):
def test_naive_datetimeindex_roundtrip(self):
# GH 23510
# Ensure that a naive DatetimeIndex isn't converted to UTC
- dates = date_range("2018-01-01", periods=5, freq="6H")
+ dates = date_range("2018-01-01", periods=5, freq="6H")._with_freq(None)
expected = DataFrame({"nums": range(5)}, index=dates)
expected.to_sql("foo_table", self.conn, index_label="info_date")
result = sql.read_sql_table("foo_table", self.conn, index_col="info_date")
| Working on making assert_index_equal check that `freq` attrs match. This ports the necessary test changes from tests.io. | https://api.github.com/repos/pandas-dev/pandas/pulls/33711 | 2020-04-21T21:17:35Z | 2020-04-24T23:22:24Z | 2020-04-24T23:22:24Z | 2020-04-24T23:24:31Z |
DOC: Improve to_parquet documentation | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 1bff17b40433d..10382364621c0 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2225,6 +2225,16 @@ def to_parquet(
col1 col2
0 1 3
1 2 4
+
+ If you want to get a buffer to the parquet content you can use a io.BytesIO
+ object, as long as you don't use partition_cols, which creates multiple files.
+
+ >>> import io
+ >>> f = io.BytesIO()
+ >>> df.to_parquet(f)
+ >>> f.seek(0)
+ 0
+ >>> content = f.read()
"""
from pandas.io.parquet import to_parquet
| fixes #29476
- [x] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry / NA
| https://api.github.com/repos/pandas-dev/pandas/pulls/33709 | 2020-04-21T20:03:37Z | 2020-05-30T16:32:53Z | 2020-05-30T16:32:52Z | 2020-06-01T20:05:15Z |
TYP: remove #type: ignore for pd.array constructor | diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index bf14ed44e3a1c..48f62fe888b9a 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -463,7 +463,7 @@ def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike:
return self
return self._set_dtype(dtype)
if is_extension_array_dtype(dtype):
- return array(self, dtype=dtype, copy=copy) # type: ignore # GH 28770
+ return array(self, dtype=dtype, copy=copy)
if is_integer_dtype(dtype) and self.isna().any():
raise ValueError("Cannot convert float NaN to integer")
return np.array(self, dtype=dtype, copy=copy)
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 407daf15d5cce..76788f3f97a28 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -1,6 +1,6 @@
from datetime import datetime, timedelta
import operator
-from typing import Any, Sequence, Type, Union, cast
+from typing import Any, Sequence, Type, TypeVar, Union, cast
import warnings
import numpy as np
@@ -437,6 +437,9 @@ def _with_freq(self, freq):
return self
+DatetimeLikeArrayT = TypeVar("DatetimeLikeArrayT", bound="DatetimeLikeArrayMixin")
+
+
class DatetimeLikeArrayMixin(
ExtensionOpsMixin, AttributesMixin, NDArrayBackedExtensionArray
):
@@ -679,7 +682,7 @@ def _concat_same_type(cls, to_concat, axis: int = 0):
return cls._simple_new(values, dtype=dtype, freq=new_freq)
- def copy(self):
+ def copy(self: DatetimeLikeArrayT) -> DatetimeLikeArrayT:
values = self.asi8.copy()
return type(self)._simple_new(values, dtype=self.dtype, freq=self.freq)
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index 2d9522b00627c..b7dfcd4cb188c 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -1,6 +1,6 @@
from datetime import timedelta
import operator
-from typing import Any, Callable, List, Optional, Sequence, Union
+from typing import Any, Callable, List, Optional, Sequence, Type, Union
import numpy as np
@@ -20,6 +20,7 @@
period_asfreq_arr,
)
from pandas._libs.tslibs.timedeltas import Timedelta, delta_to_nanoseconds
+from pandas._typing import AnyArrayLike
from pandas.util._decorators import cache_readonly
from pandas.core.dtypes.common import (
@@ -172,8 +173,8 @@ def _simple_new(cls, values: np.ndarray, freq=None, **kwargs) -> "PeriodArray":
@classmethod
def _from_sequence(
- cls,
- scalars: Sequence[Optional[Period]],
+ cls: Type["PeriodArray"],
+ scalars: Union[Sequence[Optional[Period]], AnyArrayLike],
dtype: Optional[PeriodDtype] = None,
copy: bool = False,
) -> "PeriodArray":
@@ -186,7 +187,6 @@ def _from_sequence(
validate_dtype_freq(scalars.dtype, freq)
if copy:
scalars = scalars.copy()
- assert isinstance(scalars, PeriodArray) # for mypy
return scalars
periods = np.asarray(scalars, dtype=object)
@@ -772,7 +772,7 @@ def raise_on_incompatible(left, right):
def period_array(
- data: Sequence[Optional[Period]],
+ data: Union[Sequence[Optional[Period]], AnyArrayLike],
freq: Optional[Union[str, Tick]] = None,
copy: bool = False,
) -> PeriodArray:
diff --git a/pandas/core/construction.py b/pandas/core/construction.py
index 2f71f4f4ccc19..351ef1d0429da 100644
--- a/pandas/core/construction.py
+++ b/pandas/core/construction.py
@@ -13,7 +13,7 @@
from pandas._libs import lib
from pandas._libs.tslibs import IncompatibleFrequency, OutOfBoundsDatetime
-from pandas._typing import ArrayLike, Dtype, DtypeObj
+from pandas._typing import AnyArrayLike, ArrayLike, Dtype, DtypeObj
from pandas.core.dtypes.cast import (
construct_1d_arraylike_from_scalar,
@@ -54,7 +54,9 @@
def array(
- data: Sequence[object], dtype: Optional[Dtype] = None, copy: bool = True,
+ data: Union[Sequence[object], AnyArrayLike],
+ dtype: Optional[Dtype] = None,
+ copy: bool = True,
) -> "ExtensionArray":
"""
Create an array.
| pandas\core\arrays\categorical.py:481: error: Argument 1 to "array" has incompatible type "Categorical"; expected "Sequence[object]" | https://api.github.com/repos/pandas-dev/pandas/pulls/33706 | 2020-04-21T19:13:24Z | 2020-04-26T21:25:51Z | 2020-04-26T21:25:51Z | 2020-04-27T07:29:24Z |
TYP: remove #type:ignore from core.arrays.datetimelike | diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 27b2ed822a49f..3440df4b09c06 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -1532,7 +1532,7 @@ def __rsub__(self, other):
return -(self - other)
- def __iadd__(self, other): # type: ignore
+ def __iadd__(self, other):
result = self + other
self[:] = result[:]
@@ -1541,7 +1541,7 @@ def __iadd__(self, other): # type: ignore
self._freq = result._freq
return self
- def __isub__(self, other): # type: ignore
+ def __isub__(self, other):
result = self - other
self[:] = result[:]
diff --git a/pandas/core/ops/common.py b/pandas/core/ops/common.py
index 5c83591b0e71e..515a0a5198d74 100644
--- a/pandas/core/ops/common.py
+++ b/pandas/core/ops/common.py
@@ -2,13 +2,15 @@
Boilerplate functions used in defining binary operations.
"""
from functools import wraps
+from typing import Callable
from pandas._libs.lib import item_from_zerodim
+from pandas._typing import F
from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries
-def unpack_zerodim_and_defer(name: str):
+def unpack_zerodim_and_defer(name: str) -> Callable[[F], F]:
"""
Boilerplate for pandas conventions in arithmetic and comparison methods.
@@ -21,7 +23,7 @@ def unpack_zerodim_and_defer(name: str):
decorator
"""
- def wrapper(method):
+ def wrapper(method: F) -> F:
return _unpack_zerodim_and_defer(method, name)
return wrapper
| pandas\core\arrays\datetimelike.py:1535: error: Signatures of "__iadd__" and "__add__" are incompatible
pandas\core\arrays\datetimelike.py:1544: error: Signatures of "__isub__" and "__sub__" are incompatible | https://api.github.com/repos/pandas-dev/pandas/pulls/33705 | 2020-04-21T19:08:34Z | 2020-04-22T03:31:11Z | 2020-04-22T03:31:11Z | 2020-04-22T11:27:32Z |
BUG: DTI/TDI.insert doing invalid casting | diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index af5834f01c24c..b32e1516cbbfb 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -857,10 +857,13 @@ def _validate_setitem_value(self, value):
def _validate_insert_value(self, value):
if isinstance(value, self._recognized_scalars):
value = self._scalar_type(value)
+ self._check_compatible_with(value, setitem=True)
+ # TODO: if we dont have compat, should we raise or astype(object)?
+ # PeriodIndex does astype(object)
elif is_valid_nat_for_dtype(value, self.dtype):
# GH#18295
value = NaT
- elif lib.is_scalar(value) and isna(value):
+ else:
raise TypeError(
f"cannot insert {type(self).__name__} with incompatible label"
)
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index 2200eadf3874f..82e6aa9ad1ee6 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -961,37 +961,30 @@ def insert(self, loc, item):
-------
new_index : Index
"""
+ if isinstance(item, str):
+ # TODO: Why are strings special?
+ # TODO: Should we attempt _scalar_from_string?
+ return self.astype(object).insert(loc, item)
+
item = self._data._validate_insert_value(item)
freq = None
- if isinstance(item, self._data._scalar_type) or item is NaT:
- self._data._check_compatible_with(item, setitem=True)
-
- # check freq can be preserved on edge cases
- if self.size and self.freq is not None:
+ # check freq can be preserved on edge cases
+ if self.freq is not None:
+ if self.size:
if item is NaT:
pass
elif (loc == 0 or loc == -len(self)) and item + self.freq == self[0]:
freq = self.freq
elif (loc == len(self)) and item - self.freq == self[-1]:
freq = self.freq
- elif self.freq is not None:
+ else:
# Adding a single item to an empty index may preserve freq
if self.freq.is_on_offset(item):
freq = self.freq
- item = item.asm8
- try:
- new_i8s = np.concatenate(
- (self[:loc].asi8, [item.view(np.int64)], self[loc:].asi8)
- )
- arr = type(self._data)._simple_new(new_i8s, dtype=self.dtype, freq=freq)
- return type(self)._simple_new(arr, name=self.name)
- except (AttributeError, TypeError) as err:
+ item = self._data._unbox_scalar(item)
- # fall back to object index
- if isinstance(item, str):
- return self.astype(object).insert(loc, item)
- raise TypeError(
- f"cannot insert {type(self).__name__} with incompatible label"
- ) from err
+ new_i8s = np.concatenate([self[:loc].asi8, [item], self[loc:].asi8])
+ arr = type(self._data)._simple_new(new_i8s, dtype=self.dtype, freq=freq)
+ return type(self)._simple_new(arr, name=self.name)
diff --git a/pandas/tests/indexes/datetimes/test_insert.py b/pandas/tests/indexes/datetimes/test_insert.py
index 034e1c6a4e1b0..b4f6cc3798f4f 100644
--- a/pandas/tests/indexes/datetimes/test_insert.py
+++ b/pandas/tests/indexes/datetimes/test_insert.py
@@ -165,3 +165,26 @@ def test_insert(self):
assert result.name == expected.name
assert result.tz == expected.tz
assert result.freq is None
+
+ @pytest.mark.parametrize(
+ "item", [0, np.int64(0), np.float64(0), np.array(0), np.timedelta64(456)]
+ )
+ def test_insert_mismatched_types_raises(self, tz_aware_fixture, item):
+ # GH#33703 dont cast these to dt64
+ tz = tz_aware_fixture
+ dti = date_range("2019-11-04", periods=9, freq="-1D", name=9, tz=tz)
+
+ msg = "incompatible label"
+ with pytest.raises(TypeError, match=msg):
+ dti.insert(1, item)
+
+ def test_insert_object_casting(self, tz_aware_fixture):
+ # GH#33703
+ tz = tz_aware_fixture
+ dti = date_range("2019-11-04", periods=3, freq="-1D", name=9, tz=tz)
+
+ # ATM we treat this as a string, but we could plausibly wrap it in Timestamp
+ value = "2019-11-05"
+ result = dti.insert(0, value)
+ expected = Index(["2019-11-05"] + list(dti), dtype=object, name=9)
+ tm.assert_index_equal(result, expected)
diff --git a/pandas/tests/indexes/timedeltas/test_insert.py b/pandas/tests/indexes/timedeltas/test_insert.py
index e65c871428bab..1ebc0a4b1eca0 100644
--- a/pandas/tests/indexes/timedeltas/test_insert.py
+++ b/pandas/tests/indexes/timedeltas/test_insert.py
@@ -82,6 +82,17 @@ def test_insert_invalid_na(self):
with pytest.raises(TypeError, match="incompatible label"):
idx.insert(0, np.datetime64("NaT"))
+ @pytest.mark.parametrize(
+ "item", [0, np.int64(0), np.float64(0), np.array(0), np.datetime64(456, "us")]
+ )
+ def test_insert_mismatched_types_raises(self, item):
+ # GH#33703 dont cast these to td64
+ tdi = TimedeltaIndex(["4day", "1day", "2day"], name="idx")
+
+ msg = "incompatible label"
+ with pytest.raises(TypeError, match=msg):
+ tdi.insert(1, item)
+
def test_insert_dont_cast_strings(self):
# To match DatetimeIndex and PeriodIndex behavior, dont try to
# parse strings to Timedelta
diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py
index 6cb73823adabb..07dd8eac4fbe0 100644
--- a/pandas/tests/indexing/test_coercion.py
+++ b/pandas/tests/indexing/test_coercion.py
@@ -447,7 +447,7 @@ def test_insert_index_datetimes(self, fill_val, exp_dtype):
with pytest.raises(TypeError, match=msg):
obj.insert(1, pd.Timestamp("2012-01-01", tz="Asia/Tokyo"))
- msg = "cannot insert DatetimeIndex with incompatible label"
+ msg = "cannot insert DatetimeArray with incompatible label"
with pytest.raises(TypeError, match=msg):
obj.insert(1, 1)
@@ -464,12 +464,12 @@ def test_insert_index_timedelta64(self):
)
# ToDo: must coerce to object
- msg = "cannot insert TimedeltaIndex with incompatible label"
+ msg = "cannot insert TimedeltaArray with incompatible label"
with pytest.raises(TypeError, match=msg):
obj.insert(1, pd.Timestamp("2012-01-01"))
# ToDo: must coerce to object
- msg = "cannot insert TimedeltaIndex with incompatible label"
+ msg = "cannot insert TimedeltaArray with incompatible label"
with pytest.raises(TypeError, match=msg):
obj.insert(1, 1)
diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py
index 6c259db33cf7c..ee87a3f9f5ecd 100644
--- a/pandas/tests/indexing/test_partial.py
+++ b/pandas/tests/indexing/test_partial.py
@@ -335,7 +335,7 @@ def test_partial_set_invalid(self):
df = orig.copy()
# don't allow not string inserts
- msg = "cannot insert DatetimeIndex with incompatible label"
+ msg = "cannot insert DatetimeArray with incompatible label"
with pytest.raises(TypeError, match=msg):
df.loc[100.0, :] = df.iloc[0]
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/33703 | 2020-04-21T15:28:51Z | 2020-04-25T23:54:30Z | 2020-04-25T23:54:30Z | 2020-04-26T00:32:44Z |
fix bug of overflow validaion in 'reshape' | diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py
index 882e3e0a649cc..2594f6d5ba7ef 100644
--- a/pandas/core/reshape/reshape.py
+++ b/pandas/core/reshape/reshape.py
@@ -113,9 +113,10 @@ def __init__(
num_columns = self.removed_level.size
# GH20601: This forces an overflow if the number of cells is too high.
- num_cells = np.multiply(num_rows, num_columns, dtype=np.int32)
+ num_cells = num_rows * num_columns
- if num_rows > 0 and num_columns > 0 and num_cells <= 0:
+ if num_rows > 0 and num_columns > 0 \
+ and num_cells > np.iinfo(np.int32).max or num_cells < np.iinfo(np.int32).min:
raise ValueError("Unstacked DataFrame is too big, causing int32 overflow")
self._make_selectors()
| - [x] closes #26314
- [ ] 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/33697 | 2020-04-21T12:05:23Z | 2020-05-22T11:03:07Z | null | 2020-05-22T11:03:07Z |
BUG: Fix memory issues in rolling.min/max | diff --git a/asv_bench/benchmarks/rolling.py b/asv_bench/benchmarks/rolling.py
index f85dc83ab8605..e3c9c7ccdc51c 100644
--- a/asv_bench/benchmarks/rolling.py
+++ b/asv_bench/benchmarks/rolling.py
@@ -150,19 +150,18 @@ def time_quantile(self, constructor, window, dtype, percentile, interpolation):
self.roll.quantile(percentile, interpolation=interpolation)
-class PeakMemFixed:
- def setup(self):
- N = 10
- arr = 100 * np.random.random(N)
- self.roll = pd.Series(arr).rolling(10)
-
- def peakmem_fixed(self):
- # GH 25926
- # This is to detect memory leaks in rolling operations.
- # To save time this is only ran on one method.
- # 6000 iterations is enough for most types of leaks to be detected
- for x in range(6000):
- self.roll.max()
+class PeakMemFixedWindowMinMax:
+
+ params = ["min", "max"]
+
+ def setup(self, operation):
+ N = int(1e6)
+ arr = np.random.random(N)
+ self.roll = pd.Series(arr).rolling(2)
+
+ def peakmem_fixed(self, operation):
+ for x in range(5):
+ getattr(self.roll, operation)()
class ForwardWindowMethods:
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 07849702c646d..43bf0e82490e2 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -608,6 +608,7 @@ Groupby/resample/rolling
- 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:`Rolling.min` and :meth:`Rolling.max`: Growing memory usage after multiple calls when using a fixed window (:issue:`30726`)
Reshaping
^^^^^^^^^
diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx
index 673820fd8464a..afa0539014041 100644
--- a/pandas/_libs/window/aggregations.pyx
+++ b/pandas/_libs/window/aggregations.pyx
@@ -971,8 +971,8 @@ cdef inline numeric calc_mm(int64_t minp, Py_ssize_t nobs,
return result
-def roll_max_fixed(ndarray[float64_t] values, ndarray[int64_t] start,
- ndarray[int64_t] end, int64_t minp, int64_t win):
+def roll_max_fixed(float64_t[:] values, int64_t[:] start,
+ int64_t[:] end, int64_t minp, int64_t win):
"""
Moving max of 1d array of any numeric type along axis=0 ignoring NaNs.
@@ -988,7 +988,7 @@ def roll_max_fixed(ndarray[float64_t] values, ndarray[int64_t] start,
make the interval closed on the right, left,
both or neither endpoints
"""
- return _roll_min_max_fixed(values, start, end, minp, win, is_max=1)
+ return _roll_min_max_fixed(values, minp, win, is_max=1)
def roll_max_variable(ndarray[float64_t] values, ndarray[int64_t] start,
@@ -1011,8 +1011,8 @@ def roll_max_variable(ndarray[float64_t] values, ndarray[int64_t] start,
return _roll_min_max_variable(values, start, end, minp, is_max=1)
-def roll_min_fixed(ndarray[float64_t] values, ndarray[int64_t] start,
- ndarray[int64_t] end, int64_t minp, int64_t win):
+def roll_min_fixed(float64_t[:] values, int64_t[:] start,
+ int64_t[:] end, int64_t minp, int64_t win):
"""
Moving min of 1d array of any numeric type along axis=0 ignoring NaNs.
@@ -1025,7 +1025,7 @@ def roll_min_fixed(ndarray[float64_t] values, ndarray[int64_t] start,
index : ndarray, optional
index for window computation
"""
- return _roll_min_max_fixed(values, start, end, minp, win, is_max=0)
+ return _roll_min_max_fixed(values, minp, win, is_max=0)
def roll_min_variable(ndarray[float64_t] values, ndarray[int64_t] start,
@@ -1112,9 +1112,7 @@ cdef _roll_min_max_variable(ndarray[numeric] values,
return output
-cdef _roll_min_max_fixed(ndarray[numeric] values,
- ndarray[int64_t] starti,
- ndarray[int64_t] endi,
+cdef _roll_min_max_fixed(numeric[:] values,
int64_t minp,
int64_t win,
bint is_max):
| This fixes at least the reproducible part of #30726. I am not
totally sure what is going on here (is this a true memory leak?), and whether this fixes all issues, but it does strongly reduce memory usage as measured by `psutil`.
My tests have shown that there are two solutions that avoid growing memory
usage:
- pass memoryviews (`float64_t[:]`) instead of `ndarray[float64_t]`
- remove `starti` and `endi` as arguments to `_roll_min_max_fixed`
This commit implements both, since `_roll_min_max_fixed` doesn't use `starti` and `endi` anyways.
- [x] fixes at least part of
closes #30726
closes #32466
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
I am unsure about testing: Does this need a test? If so, what would be a good way to go about testing? The tests I performed (example code in the linked issue) are probably very system specific. | https://api.github.com/repos/pandas-dev/pandas/pulls/33693 | 2020-04-21T07:52:23Z | 2020-04-28T14:48:42Z | 2020-04-28T14:48:41Z | 2020-05-26T09:32:45Z |
CLN: remove shallow_copy_with_infer | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 530aaee24c7fb..62842e7286539 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -270,10 +270,6 @@ def _outer_indexer(self, left, right):
# would we like our indexing holder to defer to us
_defer_to_indexing = False
- # prioritize current class for _shallow_copy_with_infer,
- # used to infer integers as datetime-likes
- _infer_as_myclass = False
-
_engine_type = libindex.ObjectEngine
# whether we support partial string indexing. Overridden
# in DatetimeIndex and PeriodIndex
@@ -441,10 +437,6 @@ def __new__(
_simple_new), but fills caller's metadata otherwise specified. Passed
kwargs will overwrite corresponding metadata.
- - _shallow_copy_with_infer: It returns new Index inferring its type
- from passed values. It fills caller's metadata otherwise specified as the
- same as _shallow_copy.
-
See each method's docstring.
"""
@@ -517,35 +509,6 @@ def _shallow_copy(self, values=None, name: Label = no_default):
result._cache = cache
return result
- def _shallow_copy_with_infer(self, values, **kwargs):
- """
- Create a new Index inferring the class with passed value, don't copy
- the data, use the same object attributes with passed in attributes
- taking precedence.
-
- *this is an internal non-public method*
-
- Parameters
- ----------
- values : the values to create the new Index, optional
- kwargs : updates the default attributes for this Index
- """
- attributes = self._get_attributes_dict()
- attributes.update(kwargs)
- attributes["copy"] = False
- if not len(values) and "dtype" not in kwargs:
- # TODO: what if hasattr(values, "dtype")?
- attributes["dtype"] = self.dtype
- if self._infer_as_myclass:
- try:
- return self._constructor(values, **attributes)
- except (TypeError, ValueError):
- pass
-
- # Remove tz so Index will try non-DatetimeIndex inference
- attributes.pop("tz", None)
- return Index(values, **attributes)
-
def is_(self, other) -> bool:
"""
More flexible, faster check like ``is`` but that works through views.
@@ -2810,11 +2773,7 @@ def symmetric_difference(self, other, result_name=None, sort=None):
except TypeError:
pass
- attribs = self._get_attributes_dict()
- attribs["name"] = result_name
- if "freq" in attribs:
- attribs["freq"] = None
- return self._shallow_copy_with_infer(the_diff, **attribs)
+ return Index(the_diff, dtype=self.dtype, name=result_name)
def _assert_can_do_setop(self, other):
if not is_list_like(other):
@@ -3388,7 +3347,7 @@ def _reindex_non_unique(self, target):
new_indexer = np.arange(len(self.take(indexer)))
new_indexer[~check] = -1
- new_index = self._shallow_copy_with_infer(new_labels)
+ new_index = Index(new_labels, name=self.name)
return new_index, indexer, new_indexer
# --------------------------------------------------------------------
@@ -3945,7 +3904,7 @@ def where(self, cond, other=None):
# it's float) if there are NaN values in our output.
dtype = None
- return self._shallow_copy_with_infer(values, dtype=dtype)
+ return Index(values, dtype=dtype, name=self.name)
# construction helpers
@classmethod
@@ -4175,7 +4134,8 @@ def _concat_same_dtype(self, to_concat, name):
to_concat = [x._values if isinstance(x, Index) else x for x in to_concat]
- return self._shallow_copy_with_infer(np.concatenate(to_concat), **attribs)
+ res_values = np.concatenate(to_concat)
+ return Index(res_values, name=name)
def putmask(self, mask, value):
"""
@@ -5217,7 +5177,7 @@ def insert(self, loc: int, item):
arr = np.asarray(self)
item = self._coerce_scalar_to_index(item)._values
idx = np.concatenate((arr[:loc], item, arr[loc:]))
- return self._shallow_copy_with_infer(idx)
+ return Index(idx, name=self.name)
def drop(self, labels, errors: str_t = "raise"):
"""
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index ba1a9a4e08fa0..0cf6698d316bb 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -690,7 +690,8 @@ def map(self, mapper):
>>> idx.map({'a': 'first', 'b': 'second'})
Index(['first', 'second', nan], dtype='object')
"""
- return self._shallow_copy_with_infer(self._values.map(mapper))
+ mapped = self._values.map(mapper)
+ return Index(mapped, name=self.name)
def delete(self, loc):
"""
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index 1ec6cf8fd7b4e..649d4e6dfc384 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -214,7 +214,6 @@ class DatetimeIndex(DatetimeTimedeltaMixin):
_attributes = ["name", "tz", "freq"]
_is_numeric_dtype = False
- _infer_as_myclass = True
_data: DatetimeArray
tz: Optional[tzinfo]
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 42e0d228dab09..52439a1ea3946 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -1046,16 +1046,17 @@ def _shallow_copy(
result._cache.pop("levels", None) # GH32669
return result
- def _shallow_copy_with_infer(self, values, **kwargs):
- # On equal MultiIndexes the difference is empty.
+ def symmetric_difference(self, other, result_name=None, sort=None):
+ # On equal symmetric_difference MultiIndexes the difference is empty.
# Therefore, an empty MultiIndex is returned GH13490
- if len(values) == 0:
+ tups = Index.symmetric_difference(self, other, result_name, sort)
+ if len(tups) == 0:
return MultiIndex(
levels=[[] for _ in range(self.nlevels)],
codes=[[] for _ in range(self.nlevels)],
- **kwargs,
+ names=tups.name,
)
- return self._shallow_copy(values, **kwargs)
+ return type(self).from_tuples(tups, names=tups.name)
# --------------------------------------------------------------------
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py
index 1f565828ec7a5..ece656679688f 100644
--- a/pandas/core/indexes/period.py
+++ b/pandas/core/indexes/period.py
@@ -148,7 +148,6 @@ class PeriodIndex(DatetimeIndexOpsMixin, Int64Index):
# define my properties & methods for delegation
_is_numeric_dtype = False
- _infer_as_myclass = True
_data: PeriodArray
freq: DateOffset
diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py
index 765b948f13e96..4caf9107808ed 100644
--- a/pandas/core/indexes/timedeltas.py
+++ b/pandas/core/indexes/timedeltas.py
@@ -121,7 +121,6 @@ class TimedeltaIndex(DatetimeTimedeltaMixin, dtl.TimelikeOps):
_comparables = ["name", "freq"]
_attributes = ["name", "freq"]
_is_numeric_dtype = True
- _infer_as_myclass = True
_data: TimedeltaArray
diff --git a/pandas/core/tools/numeric.py b/pandas/core/tools/numeric.py
index f4eb16602f8a0..72831b29af61e 100644
--- a/pandas/core/tools/numeric.py
+++ b/pandas/core/tools/numeric.py
@@ -188,7 +188,7 @@ def to_numeric(arg, errors="raise", downcast=None):
return pd.Series(values, index=arg.index, name=arg.name)
elif is_index:
# because we want to coerce to numeric if possible,
- # do not use _shallow_copy_with_infer
+ # do not use _shallow_copy
return pd.Index(values, name=arg.name)
elif is_scalars:
return values[0]
| https://api.github.com/repos/pandas-dev/pandas/pulls/33691 | 2020-04-21T01:57:46Z | 2020-04-22T02:31:37Z | 2020-04-22T02:31:37Z | 2020-04-22T02:48:25Z | |
CLN: Split dtype inference tests | diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py
index 3d58df258e8e9..8c0580b7cf047 100644
--- a/pandas/tests/dtypes/test_inference.py
+++ b/pandas/tests/dtypes/test_inference.py
@@ -782,108 +782,91 @@ def test_datetime(self):
index = Index(dates)
assert index.inferred_type == "datetime64"
- def test_infer_dtype_datetime(self):
-
- arr = np.array([Timestamp("2011-01-01"), Timestamp("2011-01-02")])
- assert lib.infer_dtype(arr, skipna=True) == "datetime"
-
+ def test_infer_dtype_datetime64(self):
arr = np.array(
[np.datetime64("2011-01-01"), np.datetime64("2011-01-01")], dtype=object
)
assert lib.infer_dtype(arr, skipna=True) == "datetime64"
- arr = np.array([datetime(2011, 1, 1), datetime(2012, 2, 1)])
- assert lib.infer_dtype(arr, skipna=True) == "datetime"
-
+ @pytest.mark.parametrize("na_value", [pd.NaT, np.nan])
+ def test_infer_dtype_datetime64_with_na(self, na_value):
# starts with nan
- for n in [pd.NaT, np.nan]:
- arr = np.array([n, pd.Timestamp("2011-01-02")])
- assert lib.infer_dtype(arr, skipna=True) == "datetime"
-
- arr = np.array([n, np.datetime64("2011-01-02")])
- assert lib.infer_dtype(arr, skipna=True) == "datetime64"
-
- arr = np.array([n, datetime(2011, 1, 1)])
- assert lib.infer_dtype(arr, skipna=True) == "datetime"
-
- arr = np.array([n, pd.Timestamp("2011-01-02"), n])
- assert lib.infer_dtype(arr, skipna=True) == "datetime"
-
- arr = np.array([n, np.datetime64("2011-01-02"), n])
- assert lib.infer_dtype(arr, skipna=True) == "datetime64"
-
- arr = np.array([n, datetime(2011, 1, 1), n])
- assert lib.infer_dtype(arr, skipna=True) == "datetime"
+ arr = np.array([na_value, np.datetime64("2011-01-02")])
+ assert lib.infer_dtype(arr, skipna=True) == "datetime64"
- # different type of nat
- arr = np.array(
- [np.timedelta64("nat"), np.datetime64("2011-01-02")], dtype=object
- )
- assert lib.infer_dtype(arr, skipna=False) == "mixed"
+ arr = np.array([na_value, np.datetime64("2011-01-02"), na_value])
+ assert lib.infer_dtype(arr, skipna=True) == "datetime64"
- arr = np.array(
- [np.datetime64("2011-01-02"), np.timedelta64("nat")], dtype=object
- )
+ @pytest.mark.parametrize(
+ "arr",
+ [
+ np.array(
+ [np.timedelta64("nat"), np.datetime64("2011-01-02")], dtype=object
+ ),
+ np.array(
+ [np.datetime64("2011-01-02"), np.timedelta64("nat")], dtype=object
+ ),
+ np.array([np.datetime64("2011-01-01"), pd.Timestamp("2011-01-02")]),
+ np.array([pd.Timestamp("2011-01-02"), np.datetime64("2011-01-01")]),
+ np.array([np.nan, pd.Timestamp("2011-01-02"), 1.1]),
+ np.array([np.nan, "2011-01-01", pd.Timestamp("2011-01-02")]),
+ np.array([np.datetime64("nat"), np.timedelta64(1, "D")], dtype=object),
+ np.array([np.timedelta64(1, "D"), np.datetime64("nat")], dtype=object),
+ ],
+ )
+ def test_infer_datetimelike_dtype_mixed(self, arr):
assert lib.infer_dtype(arr, skipna=False) == "mixed"
- # mixed datetime
- arr = np.array([datetime(2011, 1, 1), pd.Timestamp("2011-01-02")])
- assert lib.infer_dtype(arr, skipna=True) == "datetime"
-
- # should be datetime?
- arr = np.array([np.datetime64("2011-01-01"), pd.Timestamp("2011-01-02")])
- assert lib.infer_dtype(arr, skipna=True) == "mixed"
-
- arr = np.array([pd.Timestamp("2011-01-02"), np.datetime64("2011-01-01")])
- assert lib.infer_dtype(arr, skipna=True) == "mixed"
-
+ def test_infer_dtype_mixed_integer(self):
arr = np.array([np.nan, pd.Timestamp("2011-01-02"), 1])
assert lib.infer_dtype(arr, skipna=True) == "mixed-integer"
- arr = np.array([np.nan, pd.Timestamp("2011-01-02"), 1.1])
- assert lib.infer_dtype(arr, skipna=True) == "mixed"
+ @pytest.mark.parametrize(
+ "arr",
+ [
+ np.array([Timestamp("2011-01-01"), Timestamp("2011-01-02")]),
+ np.array([datetime(2011, 1, 1), datetime(2012, 2, 1)]),
+ np.array([datetime(2011, 1, 1), pd.Timestamp("2011-01-02")]),
+ ],
+ )
+ def test_infer_dtype_datetime(self, arr):
+ assert lib.infer_dtype(arr, skipna=True) == "datetime"
- arr = np.array([np.nan, "2011-01-01", pd.Timestamp("2011-01-02")])
- assert lib.infer_dtype(arr, skipna=True) == "mixed"
+ @pytest.mark.parametrize("na_value", [pd.NaT, np.nan])
+ @pytest.mark.parametrize(
+ "time_stamp", [pd.Timestamp("2011-01-01"), datetime(2011, 1, 1)]
+ )
+ def test_infer_dtype_datetime_with_na(self, na_value, time_stamp):
+ # starts with nan
+ arr = np.array([na_value, time_stamp])
+ assert lib.infer_dtype(arr, skipna=True) == "datetime"
- def test_infer_dtype_timedelta(self):
+ arr = np.array([na_value, time_stamp, na_value])
+ assert lib.infer_dtype(arr, skipna=True) == "datetime"
- arr = np.array([pd.Timedelta("1 days"), pd.Timedelta("2 days")])
+ @pytest.mark.parametrize(
+ "arr",
+ [
+ np.array([pd.Timedelta("1 days"), pd.Timedelta("2 days")]),
+ np.array([np.timedelta64(1, "D"), np.timedelta64(2, "D")], dtype=object),
+ np.array([timedelta(1), timedelta(2)]),
+ ],
+ )
+ def test_infer_dtype_timedelta(self, arr):
assert lib.infer_dtype(arr, skipna=True) == "timedelta"
- arr = np.array([np.timedelta64(1, "D"), np.timedelta64(2, "D")], dtype=object)
+ @pytest.mark.parametrize("na_value", [pd.NaT, np.nan])
+ @pytest.mark.parametrize(
+ "delta", [Timedelta("1 days"), np.timedelta64(1, "D"), timedelta(1)]
+ )
+ def test_infer_dtype_timedelta_with_na(self, na_value, delta):
+ # starts with nan
+ arr = np.array([na_value, delta])
assert lib.infer_dtype(arr, skipna=True) == "timedelta"
- arr = np.array([timedelta(1), timedelta(2)])
+ arr = np.array([na_value, delta, na_value])
assert lib.infer_dtype(arr, skipna=True) == "timedelta"
- # starts with nan
- for n in [pd.NaT, np.nan]:
- arr = np.array([n, Timedelta("1 days")])
- assert lib.infer_dtype(arr, skipna=True) == "timedelta"
-
- arr = np.array([n, np.timedelta64(1, "D")])
- assert lib.infer_dtype(arr, skipna=True) == "timedelta"
-
- arr = np.array([n, timedelta(1)])
- assert lib.infer_dtype(arr, skipna=True) == "timedelta"
-
- arr = np.array([n, pd.Timedelta("1 days"), n])
- assert lib.infer_dtype(arr, skipna=True) == "timedelta"
-
- arr = np.array([n, np.timedelta64(1, "D"), n])
- assert lib.infer_dtype(arr, skipna=True) == "timedelta"
-
- arr = np.array([n, timedelta(1), n])
- assert lib.infer_dtype(arr, skipna=True) == "timedelta"
-
- # different type of nat
- arr = np.array([np.datetime64("nat"), np.timedelta64(1, "D")], dtype=object)
- assert lib.infer_dtype(arr, skipna=False) == "mixed"
-
- arr = np.array([np.timedelta64(1, "D"), np.datetime64("nat")], dtype=object)
- assert lib.infer_dtype(arr, skipna=False) == "mixed"
-
def test_infer_dtype_period(self):
# GH 13664
arr = np.array([pd.Period("2011-01", freq="D"), pd.Period("2011-02", freq="D")])
@@ -892,25 +875,26 @@ def test_infer_dtype_period(self):
arr = np.array([pd.Period("2011-01", freq="D"), pd.Period("2011-02", freq="M")])
assert lib.infer_dtype(arr, skipna=True) == "period"
- # starts with nan
- for n in [pd.NaT, np.nan]:
- arr = np.array([n, pd.Period("2011-01", freq="D")])
- assert lib.infer_dtype(arr, skipna=True) == "period"
-
- arr = np.array([n, pd.Period("2011-01", freq="D"), n])
- assert lib.infer_dtype(arr, skipna=True) == "period"
-
- # different type of nat
+ def test_infer_dtype_period_mixed(self):
arr = np.array(
- [np.datetime64("nat"), pd.Period("2011-01", freq="M")], dtype=object
+ [pd.Period("2011-01", freq="M"), np.datetime64("nat")], dtype=object
)
assert lib.infer_dtype(arr, skipna=False) == "mixed"
arr = np.array(
- [pd.Period("2011-01", freq="M"), np.datetime64("nat")], dtype=object
+ [np.datetime64("nat"), pd.Period("2011-01", freq="M")], dtype=object
)
assert lib.infer_dtype(arr, skipna=False) == "mixed"
+ @pytest.mark.parametrize("na_value", [pd.NaT, np.nan])
+ def test_infer_dtype_period_with_na(self, na_value):
+ # starts with nan
+ arr = np.array([na_value, pd.Period("2011-01", freq="D")])
+ assert lib.infer_dtype(arr, skipna=True) == "period"
+
+ arr = np.array([na_value, pd.Period("2011-01", freq="D"), na_value])
+ assert lib.infer_dtype(arr, skipna=True) == "period"
+
@pytest.mark.parametrize(
"data",
[
| Breaking up some very large tests in dtypes/test_inference.py | https://api.github.com/repos/pandas-dev/pandas/pulls/33690 | 2020-04-21T00:28:15Z | 2020-04-21T12:41:01Z | 2020-04-21T12:41:01Z | 2020-04-21T12:51:03Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.