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 |
|---|---|---|---|---|---|---|---|
[REDO] CLN: core/dtypes/cast.py::maybe_downcast_to_dtype | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index e550309461de4..bcd878bb5a084 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -2,6 +2,7 @@
Routines for casting.
"""
+from contextlib import suppress
from datetime import date, datetime, timedelta
from typing import (
TYPE_CHECKING,
@@ -133,7 +134,7 @@ def is_nested_object(obj) -> bool:
return False
-def maybe_downcast_to_dtype(result, dtype: Dtype):
+def maybe_downcast_to_dtype(result, dtype: Union[str, np.dtype]):
"""
try to cast to the specified dtype (e.g. convert back to bool/int
or could be an astype of float64->float32
@@ -169,12 +170,20 @@ def maybe_downcast_to_dtype(result, dtype: Dtype):
dtype = np.dtype(dtype)
+ elif dtype.type is Period:
+ from pandas.core.arrays import PeriodArray
+
+ with suppress(TypeError):
+ # e.g. TypeError: int() argument must be a string, a
+ # bytes-like object or a number, not 'Period
+ return PeriodArray(result, freq=dtype.freq)
+
converted = maybe_downcast_numeric(result, dtype, do_round)
if converted is not result:
return converted
# a datetimelike
- # GH12821, iNaT is casted to float
+ # GH12821, iNaT is cast to float
if dtype.kind in ["M", "m"] and result.dtype.kind in ["i", "f"]:
if hasattr(dtype, "tz"):
# not a numpy dtype
@@ -187,17 +196,6 @@ def maybe_downcast_to_dtype(result, dtype: Dtype):
else:
result = result.astype(dtype)
- elif dtype.type is Period:
- # TODO(DatetimeArray): merge with previous elif
- from pandas.core.arrays import PeriodArray
-
- try:
- return PeriodArray(result, freq=dtype.freq)
- except TypeError:
- # e.g. TypeError: int() argument must be a string, a
- # bytes-like object or a number, not 'Period
- pass
-
return result
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
xref https://github.com/pandas-dev/pandas/pull/37050#issuecomment-708487786
The combination of #37050 and #37024 generated a `mypy` complaint. This PR is resubmission of #37050 with the correct type hint.
cc @simonjayhawkins | https://api.github.com/repos/pandas-dev/pandas/pulls/37126 | 2020-10-15T03:26:12Z | 2020-10-17T13:47:03Z | 2020-10-17T13:47:03Z | 2020-10-17T13:47:14Z |
REF: IntervalArray comparisons | diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 161cf3bf3a677..f8ece2a9fe7d4 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -1,3 +1,4 @@
+import operator
from operator import le, lt
import textwrap
from typing import TYPE_CHECKING, Optional, Tuple, Union, cast
@@ -12,6 +13,7 @@
IntervalMixin,
intervals_to_interval_bounds,
)
+from pandas._libs.missing import NA
from pandas._typing import ArrayLike, Dtype
from pandas.compat.numpy import function as nv
from pandas.util._decorators import Appender
@@ -48,7 +50,7 @@
from pandas.core.construction import array, extract_array
from pandas.core.indexers import check_array_indexer
from pandas.core.indexes.base import ensure_index
-from pandas.core.ops import unpack_zerodim_and_defer
+from pandas.core.ops import invalid_comparison, unpack_zerodim_and_defer
if TYPE_CHECKING:
from pandas import Index
@@ -520,8 +522,7 @@ def __setitem__(self, key, value):
self._left[key] = value_left
self._right[key] = value_right
- @unpack_zerodim_and_defer("__eq__")
- def __eq__(self, other):
+ def _cmp_method(self, other, op):
# ensure pandas array for list-like and eliminate non-interval scalars
if is_list_like(other):
if len(self) != len(other):
@@ -529,7 +530,7 @@ def __eq__(self, other):
other = array(other)
elif not isinstance(other, Interval):
# non-interval scalar -> no matches
- return np.zeros(len(self), dtype=bool)
+ return invalid_comparison(self, other, op)
# determine the dtype of the elements we want to compare
if isinstance(other, Interval):
@@ -543,7 +544,8 @@ def __eq__(self, other):
# extract intervals if we have interval categories with matching closed
if is_interval_dtype(other_dtype):
if self.closed != other.categories.closed:
- return np.zeros(len(self), dtype=bool)
+ return invalid_comparison(self, other, op)
+
other = other.categories.take(
other.codes, allow_fill=True, fill_value=other.categories._na_value
)
@@ -551,27 +553,70 @@ def __eq__(self, other):
# interval-like -> need same closed and matching endpoints
if is_interval_dtype(other_dtype):
if self.closed != other.closed:
- return np.zeros(len(self), dtype=bool)
- return (self._left == other.left) & (self._right == other.right)
+ return invalid_comparison(self, other, op)
+ elif not isinstance(other, Interval):
+ other = type(self)(other)
+
+ if op is operator.eq:
+ return (self._left == other.left) & (self._right == other.right)
+ elif op is operator.ne:
+ return (self._left != other.left) | (self._right != other.right)
+ elif op is operator.gt:
+ return (self._left > other.left) | (
+ (self._left == other.left) & (self._right > other.right)
+ )
+ elif op is operator.ge:
+ return (self == other) | (self > other)
+ elif op is operator.lt:
+ return (self._left < other.left) | (
+ (self._left == other.left) & (self._right < other.right)
+ )
+ else:
+ # operator.lt
+ return (self == other) | (self < other)
# non-interval/non-object dtype -> no matches
if not is_object_dtype(other_dtype):
- return np.zeros(len(self), dtype=bool)
+ return invalid_comparison(self, other, op)
# object dtype -> iteratively check for intervals
result = np.zeros(len(self), dtype=bool)
for i, obj in enumerate(other):
- # need object to be an Interval with same closed and endpoints
- if (
- isinstance(obj, Interval)
- and self.closed == obj.closed
- and self._left[i] == obj.left
- and self._right[i] == obj.right
- ):
- result[i] = True
-
+ try:
+ result[i] = op(self[i], obj)
+ except TypeError:
+ if obj is NA:
+ # comparison with np.nan returns NA
+ # github.com/pandas-dev/pandas/pull/37124#discussion_r509095092
+ result[i] = op is operator.ne
+ else:
+ raise
return result
+ @unpack_zerodim_and_defer("__eq__")
+ def __eq__(self, other):
+ return self._cmp_method(other, operator.eq)
+
+ @unpack_zerodim_and_defer("__ne__")
+ def __ne__(self, other):
+ return self._cmp_method(other, operator.ne)
+
+ @unpack_zerodim_and_defer("__gt__")
+ def __gt__(self, other):
+ return self._cmp_method(other, operator.gt)
+
+ @unpack_zerodim_and_defer("__ge__")
+ def __ge__(self, other):
+ return self._cmp_method(other, operator.ge)
+
+ @unpack_zerodim_and_defer("__lt__")
+ def __lt__(self, other):
+ return self._cmp_method(other, operator.lt)
+
+ @unpack_zerodim_and_defer("__le__")
+ def __le__(self, other):
+ return self._cmp_method(other, operator.le)
+
def fillna(self, value=None, method=None, limit=None):
"""
Fill NA/NaN values using the specified method.
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index 1bd71f00b534d..2061e652a4c01 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -1074,19 +1074,6 @@ def _is_all_dates(self) -> bool:
# TODO: arithmetic operations
- # GH#30817 until IntervalArray implements inequalities, get them from Index
- def __lt__(self, other):
- return Index.__lt__(self, other)
-
- def __le__(self, other):
- return Index.__le__(self, other)
-
- def __gt__(self, other):
- return Index.__gt__(self, other)
-
- def __ge__(self, other):
- return Index.__ge__(self, other)
-
def _is_valid_endpoint(endpoint) -> bool:
"""
diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py
index e973b1247941f..29a59cdefbd83 100644
--- a/pandas/tests/extension/base/methods.py
+++ b/pandas/tests/extension/base/methods.py
@@ -447,7 +447,7 @@ def test_repeat(self, data, repeats, as_series, use_numpy):
@pytest.mark.parametrize(
"repeats, kwargs, error, msg",
[
- (2, dict(axis=1), ValueError, "'axis"),
+ (2, dict(axis=1), ValueError, "axis"),
(-1, dict(), ValueError, "negative"),
([1, 2], dict(), ValueError, "shape"),
(2, dict(foo="bar"), TypeError, "'foo'"),
diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py
index 67e031b53e44e..157446b1fff5d 100644
--- a/pandas/tests/indexes/interval/test_interval.py
+++ b/pandas/tests/indexes/interval/test_interval.py
@@ -579,9 +579,11 @@ def test_comparison(self):
actual = self.index == self.index.left
tm.assert_numpy_array_equal(actual, np.array([False, False]))
- msg = (
- "not supported between instances of 'int' and "
- "'pandas._libs.interval.Interval'"
+ msg = "|".join(
+ [
+ "not supported between instances of 'int' and '.*.Interval'",
+ r"Invalid comparison between dtype=interval\[int64\] and ",
+ ]
)
with pytest.raises(TypeError, match=msg):
self.index > 0
| - [ ] 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/37124 | 2020-10-14T23:02:47Z | 2020-11-03T09:57:29Z | 2020-11-03T09:57:28Z | 2020-11-03T15:11:29Z |
Backport PR #35688 on branch 1.1.x: Fix GH-29442 DataFrame.groupby doesn't preserve _metadata | diff --git a/doc/source/whatsnew/v1.1.4.rst b/doc/source/whatsnew/v1.1.4.rst
index aa2c77da4ee6f..6892fb62028c9 100644
--- a/doc/source/whatsnew/v1.1.4.rst
+++ b/doc/source/whatsnew/v1.1.4.rst
@@ -27,7 +27,7 @@ Fixed regressions
Bug fixes
~~~~~~~~~
--
+- Bug causing ``groupby(...).sum()`` and similar to not preserve metadata (:issue:`29442`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 11d0c8e42f745..f80e2b3758ae1 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -994,9 +994,10 @@ def _agg_general(
):
self._set_group_selection()
+ result = None
# try a cython aggregation if we can
try:
- return self._cython_agg_general(
+ result = self._cython_agg_general(
how=alias, alt=npfunc, numeric_only=numeric_only, min_count=min_count,
)
except DataError:
@@ -1012,8 +1013,9 @@ def _agg_general(
raise
# apply a non-cython aggregation
- result = self.aggregate(lambda x: npfunc(x, axis=self.axis))
- return result
+ if result is None:
+ result = self.aggregate(lambda x: npfunc(x, axis=self.axis))
+ return result.__finalize__(self.obj, method="groupby")
def _cython_agg_general(
self, how: str, alt=None, numeric_only: bool = True, min_count: int = -1
diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py
index 4d0f1a326225d..ad991f92ee99f 100644
--- a/pandas/tests/generic/test_finalize.py
+++ b/pandas/tests/generic/test_finalize.py
@@ -770,21 +770,31 @@ def test_categorical_accessor(method):
# Groupby
+@pytest.mark.parametrize(
+ "obj", [pd.Series([0, 0]), pd.DataFrame({"A": [0, 1], "B": [1, 2]})]
+)
+@pytest.mark.parametrize(
+ "method", [operator.methodcaller("sum"), lambda x: x.agg("sum")],
+)
+def test_groupby_finalize(obj, method):
+ obj.attrs = {"a": 1}
+ result = method(obj.groupby([0, 0]))
+ assert result.attrs == {"a": 1}
+
+
@pytest.mark.parametrize(
"obj", [pd.Series([0, 0]), pd.DataFrame({"A": [0, 1], "B": [1, 2]})]
)
@pytest.mark.parametrize(
"method",
[
- operator.methodcaller("sum"),
- lambda x: x.agg("sum"),
lambda x: x.agg(["sum", "count"]),
lambda x: x.transform(lambda y: y),
lambda x: x.apply(lambda y: y),
],
)
@not_implemented_mark
-def test_groupby(obj, method):
+def test_groupby_finalize_not_implemented(obj, method):
obj.attrs = {"a": 1}
result = method(obj.groupby([0, 0]))
assert result.attrs == {"a": 1}
| Backport PR #35688
| https://api.github.com/repos/pandas-dev/pandas/pulls/37122 | 2020-10-14T19:44:15Z | 2020-10-15T12:02:54Z | 2020-10-15T12:02:54Z | 2020-10-15T12:02:59Z |
ERR: Removing quotation marks in error message | diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index b7554081fb521..538c15b707761 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -3826,6 +3826,6 @@ def _validate_skipfooter(kwds: Dict[str, Any]) -> None:
"""
if kwds.get("skipfooter"):
if kwds.get("iterator") or kwds.get("chunksize"):
- raise ValueError("'skipfooter' not supported for 'iteration'")
+ raise ValueError("'skipfooter' not supported for iteration")
if kwds.get("nrows"):
raise ValueError("'skipfooter' not supported with 'nrows'")
diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py
index edf1d780ef107..b33289213e258 100644
--- a/pandas/tests/io/parser/test_common.py
+++ b/pandas/tests/io/parser/test_common.py
@@ -719,7 +719,7 @@ def test_iterator_stop_on_chunksize(all_parsers):
"kwargs", [dict(iterator=True, chunksize=1), dict(iterator=True), dict(chunksize=1)]
)
def test_iterator_skipfooter_errors(all_parsers, kwargs):
- msg = "'skipfooter' not supported for 'iteration'"
+ msg = "'skipfooter' not supported for iteration"
parser = all_parsers
data = "a\n1\n2"
| Follow-up to https://github.com/pandas-dev/pandas/pull/36852
When reviewing, I got confused and thought `iteration` was somehow an argument to `read_csv` (like `nrows`). Since it is now, the quotation marks don't make as much sense to have.
Doing this as a follow-up since the original PR was a pure refactoring. | https://api.github.com/repos/pandas-dev/pandas/pulls/37120 | 2020-10-14T18:57:43Z | 2020-10-15T00:27:51Z | 2020-10-15T00:27:51Z | 2020-10-15T00:48:34Z |
PERF: regression in DataFrame reduction ops performance #37081 | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 539275c7ff617..8779ad6ef1c0d 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -8652,11 +8652,10 @@ def _reduce(
assert filter_type is None or filter_type == "bool", filter_type
out_dtype = "bool" if filter_type == "bool" else None
+ own_dtypes = [arr.dtype for arr in self._iter_column_arrays()]
+
dtype_is_dt = np.array(
- [
- is_datetime64_any_dtype(values.dtype)
- for values in self._iter_column_arrays()
- ],
+ [is_datetime64_any_dtype(dtype) for dtype in own_dtypes],
dtype=bool,
)
if numeric_only is None and name in ["mean", "median"] and dtype_is_dt.any():
@@ -8670,7 +8669,11 @@ def _reduce(
cols = self.columns[~dtype_is_dt]
self = self[cols]
- any_object = self.dtypes.apply(is_object_dtype).any()
+ any_object = np.array(
+ [is_object_dtype(dtype) for dtype in own_dtypes],
+ dtype=bool,
+ ).any()
+
# TODO: Make other agg func handle axis=None properly GH#21597
axis = self._get_axis_number(axis)
labels = self._get_agg_axis(axis)
| - [x] closes #37081
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
Made the change proposed by @jorisvandenbossche in https://github.com/pandas-dev/pandas/pull/35881#discussion_r504035006
Did a very quick comparison :
With `self.dtypes` (old version) :
```
In [8]: values = np.random.randn(100000, 4)
...: df = pd.DataFrame(values).astype("int")
...: %timeit df.sum()
714 µs ± 21 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
```
With `self._iter_column_arrays()` (new version) :
```
In [4]: values = np.random.randn(100000, 4)
...: df = pd.DataFrame(values).astype("int")
...: %timeit df.sum()
477 µs ± 8.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/37118 | 2020-10-14T18:22:06Z | 2020-10-17T13:49:55Z | 2020-10-17T13:49:55Z | 2020-10-17T13:50:01Z |
CI: check for numpy.random-related imports | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index d9e48ab9b6189..1065ccff32632 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -66,9 +66,17 @@ repos:
from\ pandas\.core\ import\ common|
# Check for imports from collections.abc instead of `from collections import abc`
- from\ collections\.abc\ import|
+ from\ collections\.abc\ import
- from\ numpy\ import\ nan
+ - id: non-standard-numpy.random-related-imports
+ name: Check for non-standard numpy.random-related imports excluding pandas/_testing.py
+ language: pygrep
+ exclude: pandas/_testing.py
+ entry: |
+ (?x)
+ # Check for imports from np.random.<method> instead of `from numpy import random` or `from numpy.random import <method>`
+ from\ numpy\ import\ random|
+ from\ numpy.random\ import
types: [python]
- id: non-standard-imports-in-tests
name: Check for non-standard imports in test suite
| ~~- [x] closes #37053 (keep this issue open until both #37492 and #37117 are completed)~~
- [x] tests added / passed ~~(once #37492is merged)~~
# update 2020-10-31
now use a pre-commit check instead of the previous code_check
***
~~code_check.sh will be used to locate where numpy.random-related imports are.~~ See the separate script to do the whole clean-up in https://github.com/pandas-dev/pandas/pull/37103#issue-502582592. | https://api.github.com/repos/pandas-dev/pandas/pulls/37117 | 2020-10-14T17:37:22Z | 2020-10-31T14:50:32Z | 2020-10-31T14:50:32Z | 2020-10-31T15:11:51Z |
Revert "CLN: core/dtypes/cast.py::maybe_downcast_to_dtype" | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index b6b9a2ae2aab8..e550309461de4 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -2,7 +2,6 @@
Routines for casting.
"""
-from contextlib import suppress
from datetime import date, datetime, timedelta
from typing import (
TYPE_CHECKING,
@@ -170,20 +169,12 @@ def maybe_downcast_to_dtype(result, dtype: Dtype):
dtype = np.dtype(dtype)
- elif dtype.type is Period:
- from pandas.core.arrays import PeriodArray
-
- with suppress(TypeError):
- # e.g. TypeError: int() argument must be a string, a
- # bytes-like object or a number, not 'Period
- return PeriodArray(result, freq=dtype.freq)
-
converted = maybe_downcast_numeric(result, dtype, do_round)
if converted is not result:
return converted
# a datetimelike
- # GH12821, iNaT is cast to float
+ # GH12821, iNaT is casted to float
if dtype.kind in ["M", "m"] and result.dtype.kind in ["i", "f"]:
if hasattr(dtype, "tz"):
# not a numpy dtype
@@ -196,6 +187,17 @@ def maybe_downcast_to_dtype(result, dtype: Dtype):
else:
result = result.astype(dtype)
+ elif dtype.type is Period:
+ # TODO(DatetimeArray): merge with previous elif
+ from pandas.core.arrays import PeriodArray
+
+ try:
+ return PeriodArray(result, freq=dtype.freq)
+ except TypeError:
+ # e.g. TypeError: int() argument must be a string, a
+ # bytes-like object or a number, not 'Period
+ pass
+
return result
| Reverts pandas-dev/pandas#37050 | https://api.github.com/repos/pandas-dev/pandas/pulls/37116 | 2020-10-14T15:44:15Z | 2020-10-14T16:41:36Z | 2020-10-14T16:41:36Z | 2020-10-14T16:41:43Z |
TST: add message matches to pytest.raises in test_duplicate_labels.py GH30999 | diff --git a/pandas/tests/generic/test_duplicate_labels.py b/pandas/tests/generic/test_duplicate_labels.py
index 97468e1f10a8b..42745d2a69375 100644
--- a/pandas/tests/generic/test_duplicate_labels.py
+++ b/pandas/tests/generic/test_duplicate_labels.py
@@ -275,7 +275,8 @@ def test_set_flags_with_duplicates(self, cls, axes):
result = cls(**axes)
assert result.flags.allows_duplicate_labels is True
- with pytest.raises(pd.errors.DuplicateLabelError):
+ msg = "Index has duplicates."
+ with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
cls(**axes).set_flags(allows_duplicate_labels=False)
@pytest.mark.parametrize(
@@ -287,7 +288,8 @@ def test_set_flags_with_duplicates(self, cls, axes):
],
)
def test_setting_allows_duplicate_labels_raises(self, data):
- with pytest.raises(pd.errors.DuplicateLabelError):
+ msg = "Index has duplicates."
+ with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
data.flags.allows_duplicate_labels = False
assert data.flags.allows_duplicate_labels is True
@@ -297,7 +299,8 @@ def test_setting_allows_duplicate_labels_raises(self, data):
)
def test_series_raises(self, func):
s = pd.Series([0, 1], index=["a", "b"]).set_flags(allows_duplicate_labels=False)
- with pytest.raises(pd.errors.DuplicateLabelError):
+ msg = "Index has duplicates."
+ with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
func(s)
@pytest.mark.parametrize(
@@ -332,7 +335,8 @@ def test_getitem_raises(self, getter, target):
else:
target = df
- with pytest.raises(pd.errors.DuplicateLabelError):
+ msg = "Index has duplicates."
+ with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
getter(target)
@pytest.mark.parametrize(
@@ -352,7 +356,8 @@ def test_getitem_raises(self, getter, target):
],
)
def test_concat_raises(self, objs, kwargs):
- with pytest.raises(pd.errors.DuplicateLabelError):
+ msg = "Index has duplicates."
+ with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
pd.concat(objs, **kwargs)
@not_implemented
@@ -361,7 +366,8 @@ def test_merge_raises(self):
allows_duplicate_labels=False
)
b = pd.DataFrame({"B": [0, 1, 2]}, index=["a", "b", "b"])
- with pytest.raises(pd.errors.DuplicateLabelError):
+ msg = "Index has duplicates."
+ with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
pd.merge(a, b, left_index=True, right_index=True)
@@ -381,13 +387,14 @@ def test_merge_raises(self):
ids=lambda x: type(x).__name__,
)
def test_raises_basic(idx):
- with pytest.raises(pd.errors.DuplicateLabelError):
+ msg = "Index has duplicates."
+ with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
pd.Series(1, index=idx).set_flags(allows_duplicate_labels=False)
- with pytest.raises(pd.errors.DuplicateLabelError):
+ with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
pd.DataFrame({"A": [1, 1]}, index=idx).set_flags(allows_duplicate_labels=False)
- with pytest.raises(pd.errors.DuplicateLabelError):
+ with pytest.raises(pd.errors.DuplicateLabelError, match=msg):
pd.DataFrame([[1, 2]], columns=idx).set_flags(allows_duplicate_labels=False)
@@ -412,7 +419,8 @@ def test_format_duplicate_labels_message_multi():
def test_dataframe_insert_raises():
df = pd.DataFrame({"A": [1, 2]}).set_flags(allows_duplicate_labels=False)
- with pytest.raises(ValueError, match="Cannot specify"):
+ msg = "Cannot specify"
+ with pytest.raises(ValueError, match=msg):
df.insert(0, "A", [3, 4], allow_duplicates=True)
| Reference https://github.com/pandas-dev/pandas/issues/30999
- [x] tests added / passed
- [x] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
Hello! This is my first PR here. I followed the steps in the contributing guidelines [here](https://github.com/pandas-dev/pandas/blob/master/doc/source/development/contributing.rst#contributing-your-changes-to-pandas), but I didn't see anything about `git diff upstream/master -u -- "*.py" | flake8 --diff`.
When I run the command locally, with `origin/master`, it returns no output. I get fatal with `upstream/master`. Is that expected, and if it isn't, could anyone advise on how to resolve the issue please?
Thank you! | https://api.github.com/repos/pandas-dev/pandas/pulls/37114 | 2020-10-14T12:31:40Z | 2020-10-14T18:06:55Z | 2020-10-14T18:06:55Z | 2020-10-14T18:07:12Z |
CLN: runtime imports | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index a7379376c2f78..2febd36c76b75 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -7,15 +7,17 @@
import numpy as np
-from pandas._libs import lib, tslib, tslibs
+from pandas._libs import lib, tslib
from pandas._libs.tslibs import (
NaT,
OutOfBoundsDatetime,
Period,
Timedelta,
Timestamp,
+ conversion,
iNaT,
ints_to_pydatetime,
+ ints_to_pytimedelta,
)
from pandas._libs.tslibs.timezones import tz_compare
from pandas._typing import ArrayLike, Dtype, DtypeObj
@@ -552,7 +554,7 @@ def maybe_promote(dtype, fill_value=np.nan):
dtype = np.dtype(np.object_)
else:
try:
- fill_value = tslibs.Timestamp(fill_value).to_datetime64()
+ fill_value = Timestamp(fill_value).to_datetime64()
except (TypeError, ValueError):
dtype = np.dtype(np.object_)
elif issubclass(dtype.type, np.timedelta64):
@@ -565,7 +567,7 @@ def maybe_promote(dtype, fill_value=np.nan):
dtype = np.dtype(np.object_)
else:
try:
- fv = tslibs.Timedelta(fill_value)
+ fv = Timedelta(fill_value)
except ValueError:
dtype = np.dtype(np.object_)
else:
@@ -738,8 +740,8 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> Tuple[DtypeObj,
dtype = np.dtype(object)
elif isinstance(val, (np.datetime64, datetime)):
- val = tslibs.Timestamp(val)
- if val is tslibs.NaT or val.tz is None:
+ val = Timestamp(val)
+ if val is NaT or val.tz is None:
dtype = np.dtype("M8[ns]")
else:
if pandas_dtype:
@@ -750,7 +752,7 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> Tuple[DtypeObj,
val = val.value
elif isinstance(val, (np.timedelta64, timedelta)):
- val = tslibs.Timedelta(val).value
+ val = Timedelta(val).value
dtype = np.dtype("m8[ns]")
elif is_bool(val):
@@ -941,9 +943,9 @@ def conv(r, dtype):
if np.any(isna(r)):
pass
elif dtype == DT64NS_DTYPE:
- r = tslibs.Timestamp(r)
+ r = Timestamp(r)
elif dtype == TD64NS_DTYPE:
- r = tslibs.Timedelta(r)
+ r = Timedelta(r)
elif dtype == np.bool_:
# messy. non 0/1 integers do not get converted.
if is_integer(r) and r not in [0, 1]:
@@ -1006,7 +1008,7 @@ def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
elif is_timedelta64_dtype(arr):
if is_object_dtype(dtype):
- return tslibs.ints_to_pytimedelta(arr.view(np.int64))
+ return ints_to_pytimedelta(arr.view(np.int64))
elif dtype == np.int64:
if isna(arr).any():
raise ValueError("Cannot convert NaT values to integer")
@@ -1317,8 +1319,6 @@ def try_datetime(v):
# we might have a sequence of the same-datetimes with tz's
# if so coerce to a DatetimeIndex; if they are not the same,
# then these stay as object dtype, xref GH19671
- from pandas._libs.tslibs import conversion
-
from pandas import DatetimeIndex
try:
@@ -1492,7 +1492,7 @@ def maybe_cast_to_datetime(value, dtype, errors: str = "raise"):
dtype = value.dtype
if dtype.kind == "M" and dtype != DT64NS_DTYPE:
- value = tslibs.conversion.ensure_datetime64ns(value)
+ value = conversion.ensure_datetime64ns(value)
elif dtype.kind == "m" and dtype != TD64NS_DTYPE:
value = to_timedelta(value)
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index bf8d50db8416e..28b3a2414679b 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -406,8 +406,6 @@ def __repr__(self) -> str_type:
@staticmethod
def _hash_categories(categories, ordered: Ordered = True) -> int:
- from pandas.core.dtypes.common import DT64NS_DTYPE, is_datetime64tz_dtype
-
from pandas.core.util.hashing import (
combine_hash_arrays,
hash_array,
@@ -430,9 +428,9 @@ def _hash_categories(categories, ordered: Ordered = True) -> int:
hashed = hash((tuple(categories), ordered))
return hashed
- if is_datetime64tz_dtype(categories.dtype):
+ if DatetimeTZDtype.is_dtype(categories.dtype):
# Avoid future warning.
- categories = categories.astype(DT64NS_DTYPE)
+ categories = categories.astype("datetime64[ns]")
cat_array = hash_array(np.asarray(categories), categorize=False)
if ordered:
@@ -1011,11 +1009,7 @@ class IntervalDtype(PandasExtensionDtype):
_cache: Dict[str_type, PandasExtensionDtype] = {}
def __new__(cls, subtype=None):
- from pandas.core.dtypes.common import (
- is_categorical_dtype,
- is_string_dtype,
- pandas_dtype,
- )
+ from pandas.core.dtypes.common import is_string_dtype, pandas_dtype
if isinstance(subtype, IntervalDtype):
return subtype
@@ -1038,7 +1032,7 @@ def __new__(cls, subtype=None):
except TypeError as err:
raise TypeError("could not construct IntervalDtype") from err
- if is_categorical_dtype(subtype) or is_string_dtype(subtype):
+ if CategoricalDtype.is_dtype(subtype) or is_string_dtype(subtype):
# GH 19016
msg = (
"category, object, and string subtypes are not supported "
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index ba2f11c87369f..f6192a3ccdd7e 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -147,6 +147,7 @@
)
from pandas.core.reshape.melt import melt
from pandas.core.series import Series
+from pandas.core.sorting import get_group_index, lexsort_indexer, nargsort
from pandas.io.common import get_filepath_or_buffer
from pandas.io.formats import console, format as fmt
@@ -5251,8 +5252,6 @@ def duplicated(
"""
from pandas._libs.hashtable import SIZE_HINT_LIMIT, duplicated_int64
- from pandas.core.sorting import get_group_index
-
if self.empty:
return self._constructor_sliced(dtype=bool)
@@ -5315,7 +5314,6 @@ def sort_values( # type: ignore[override]
f"Length of ascending ({len(ascending)}) != length of by ({len(by)})"
)
if len(by) > 1:
- from pandas.core.sorting import lexsort_indexer
keys = [self._get_label_or_level_values(x, axis=axis) for x in by]
@@ -5328,7 +5326,6 @@ def sort_values( # type: ignore[override]
)
indexer = ensure_platform_int(indexer)
else:
- from pandas.core.sorting import nargsort
by = by[0]
k = self._get_label_or_level_values(by, axis=axis)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 7d0b0d6683e21..6b8f6b47ef882 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -34,7 +34,7 @@
from pandas._config import config
from pandas._libs import lib
-from pandas._libs.tslibs import Tick, Timestamp, to_offset
+from pandas._libs.tslibs import Period, Tick, Timestamp, to_offset
from pandas._typing import (
Axis,
CompressionOptions,
@@ -86,17 +86,21 @@
from pandas.core.dtypes.missing import isna, notna
import pandas as pd
-from pandas.core import missing, nanops
+from pandas.core import indexing, missing, nanops
import pandas.core.algorithms as algos
from pandas.core.base import PandasObject, SelectionMixin
import pandas.core.common as com
from pandas.core.construction import create_series_with_explicit_dtype
from pandas.core.flags import Flags
from pandas.core.indexes import base as ibase
-from pandas.core.indexes.api import Index, MultiIndex, RangeIndex, ensure_index
-from pandas.core.indexes.datetimes import DatetimeIndex
-from pandas.core.indexes.period import Period, PeriodIndex
-import pandas.core.indexing as indexing
+from pandas.core.indexes.api import (
+ DatetimeIndex,
+ Index,
+ MultiIndex,
+ PeriodIndex,
+ RangeIndex,
+ ensure_index,
+)
from pandas.core.internals import BlockManager
from pandas.core.missing import find_valid_index
from pandas.core.ops import align_method_FRAME
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 7d3c2c2297d5d..f885e03f21470 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -23,15 +23,13 @@
from pandas._libs import algos as libalgos, index as libindex, lib
import pandas._libs.join as libjoin
from pandas._libs.lib import is_datetime_array, no_default
-from pandas._libs.tslibs import OutOfBoundsDatetime, Timestamp
-from pandas._libs.tslibs.period import IncompatibleFrequency
+from pandas._libs.tslibs import IncompatibleFrequency, OutOfBoundsDatetime, Timestamp
from pandas._libs.tslibs.timezones import tz_compare
from pandas._typing import AnyArrayLike, Dtype, DtypeObj, Label
from pandas.compat.numpy import function as nv
from pandas.errors import DuplicateLabelError, InvalidIndexError
from pandas.util._decorators import Appender, cache_readonly, doc
-from pandas.core.dtypes import concat as _concat
from pandas.core.dtypes.cast import (
maybe_cast_to_integer_array,
validate_numeric_casting,
@@ -77,7 +75,7 @@
)
from pandas.core.dtypes.missing import array_equivalent, isna
-from pandas.core import ops
+from pandas.core import missing, ops
from pandas.core.accessor import CachedAccessor
import pandas.core.algorithms as algos
from pandas.core.arrays import Categorical, ExtensionArray
@@ -86,7 +84,6 @@
import pandas.core.common as com
from pandas.core.indexers import deprecate_ndim_indexing
from pandas.core.indexes.frozen import FrozenList
-import pandas.core.missing as missing
from pandas.core.ops import get_op_result_name
from pandas.core.ops.invalid import make_invalid_op
from pandas.core.sorting import ensure_key_mapped, nargsort
@@ -4205,7 +4202,7 @@ def _concat(self, to_concat, name):
"""
to_concat = [x._values if isinstance(x, Index) else x for x in to_concat]
- result = _concat.concat_compat(to_concat)
+ result = concat_compat(to_concat)
return Index(result, name=name)
def putmask(self, mask, value):
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 2ce4538a63d25..3153a9ce66b95 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -3093,7 +3093,6 @@ def get_locs(self, seq):
>>> mi.get_locs([[True, False, True], slice('e', 'f')]) # doctest: +SKIP
array([2], dtype=int64)
"""
- from pandas.core.indexes.numeric import Int64Index
# must be lexsorted to at least as many levels
true_slices = [i for (i, s) in enumerate(com.is_true_slices(seq)) if s]
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 61d9833a50a9f..ab349ce3539aa 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -6,8 +6,7 @@
import numpy as np
-from pandas._libs import NaT, algos as libalgos, lib, writers
-import pandas._libs.internals as libinternals
+from pandas._libs import NaT, algos as libalgos, internals as libinternals, lib, writers
from pandas._libs.internals import BlockPlacement
from pandas._libs.tslibs import conversion
from pandas._libs.tslibs.timezones import tz_compare
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 493ba87565220..5012be593820e 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -11,8 +11,7 @@
import numpy as np
-from pandas._libs import Timedelta, hashtable as libhashtable, lib
-import pandas._libs.join as libjoin
+from pandas._libs import Timedelta, hashtable as libhashtable, join as libjoin, lib
from pandas._typing import ArrayLike, FrameOrSeries, FrameOrSeriesUnion
from pandas.errors import MergeError
from pandas.util._decorators import Appender, Substitution
diff --git a/pandas/core/series.py b/pandas/core/series.py
index fb684da20bac8..55aa32dd028ef 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -67,7 +67,6 @@
remove_na_arraylike,
)
-import pandas as pd
from pandas.core import algorithms, base, generic, nanops, ops
from pandas.core.accessor import CachedAccessor
from pandas.core.aggregation import aggregate, transform
@@ -76,6 +75,7 @@
from pandas.core.arrays.sparse import SparseAccessor
import pandas.core.common as com
from pandas.core.construction import (
+ array as pd_array,
create_series_with_explicit_dtype,
extract_array,
is_empty_data,
@@ -4193,7 +4193,7 @@ def f(x):
if len(mapped) and isinstance(mapped[0], Series):
# GH 25959 use pd.array instead of tolist
# so extension arrays can be used
- return self._constructor_expanddim(pd.array(mapped), index=self.index)
+ return self._constructor_expanddim(pd_array(mapped), index=self.index)
else:
return self._constructor(mapped, index=self.index).__finalize__(
self, method="apply"
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py
index 7b384c9bbb47d..1553deeef4059 100644
--- a/pandas/core/tools/datetimes.py
+++ b/pandas/core/tools/datetimes.py
@@ -16,8 +16,16 @@
import numpy as np
-from pandas._libs import tslib, tslibs
-from pandas._libs.tslibs import Timestamp, conversion, parsing
+from pandas._libs import tslib
+from pandas._libs.tslibs import (
+ OutOfBoundsDatetime,
+ Timedelta,
+ Timestamp,
+ conversion,
+ iNaT,
+ nat_strings,
+ parsing,
+)
from pandas._libs.tslibs.parsing import ( # noqa
DateParseError,
format_is_iso,
@@ -404,7 +412,7 @@ def _convert_listlike_datetimes(
# datetime64[ns]
orig_arg = ensure_object(orig_arg)
result = _attempt_YYYYMMDD(orig_arg, errors=errors)
- except (ValueError, TypeError, tslibs.OutOfBoundsDatetime) as err:
+ except (ValueError, TypeError, OutOfBoundsDatetime) as err:
raise ValueError(
"cannot convert the input to '%Y%m%d' date format"
) from err
@@ -419,13 +427,13 @@ def _convert_listlike_datetimes(
return _return_parsed_timezone_results(
result, timezones, tz, name
)
- except tslibs.OutOfBoundsDatetime:
+ except OutOfBoundsDatetime:
if errors == "raise":
raise
elif errors == "coerce":
result = np.empty(arg.shape, dtype="M8[ns]")
iresult = result.view("i8")
- iresult.fill(tslibs.iNaT)
+ iresult.fill(iNaT)
else:
result = arg
except ValueError:
@@ -438,7 +446,7 @@ def _convert_listlike_datetimes(
elif errors == "coerce":
result = np.empty(arg.shape, dtype="M8[ns]")
iresult = result.view("i8")
- iresult.fill(tslibs.iNaT)
+ iresult.fill(iNaT)
else:
result = arg
except ValueError as e:
@@ -508,7 +516,7 @@ def _adjust_to_origin(arg, origin, unit):
j_max = Timestamp.max.to_julian_date() - j0
j_min = Timestamp.min.to_julian_date() - j0
if np.any(arg > j_max) or np.any(arg < j_min):
- raise tslibs.OutOfBoundsDatetime(
+ raise OutOfBoundsDatetime(
f"{original} is Out of Bounds for origin='julian'"
)
else:
@@ -525,10 +533,8 @@ def _adjust_to_origin(arg, origin, unit):
# we are going to offset back to unix / epoch time
try:
offset = Timestamp(origin)
- except tslibs.OutOfBoundsDatetime as err:
- raise tslibs.OutOfBoundsDatetime(
- f"origin {origin} is Out of Bounds"
- ) from err
+ except OutOfBoundsDatetime as err:
+ raise OutOfBoundsDatetime(f"origin {origin} is Out of Bounds") from err
except ValueError as err:
raise ValueError(
f"origin {origin} cannot be converted to a Timestamp"
@@ -540,7 +546,7 @@ def _adjust_to_origin(arg, origin, unit):
# convert the offset to the unit of the arg
# this should be lossless in terms of precision
- offset = offset // tslibs.Timedelta(1, unit=unit)
+ offset = offset // Timedelta(1, unit=unit)
# scalars & ndarray-like can handle the addition
if is_list_like(arg) and not isinstance(arg, (ABCSeries, Index, np.ndarray)):
@@ -809,7 +815,7 @@ def to_datetime(
elif is_list_like(arg):
try:
cache_array = _maybe_cache(arg, format, cache, convert_listlike)
- except tslibs.OutOfBoundsDatetime:
+ except OutOfBoundsDatetime:
# caching attempts to create a DatetimeIndex, which may raise
# an OOB. If that's the desired behavior, then just reraise...
if errors == "raise":
@@ -965,7 +971,7 @@ def calc(carg):
def calc_with_mask(carg, mask):
result = np.empty(carg.shape, dtype="M8[ns]")
iresult = result.view("i8")
- iresult[~mask] = tslibs.iNaT
+ iresult[~mask] = iNaT
masked_result = calc(carg[mask].astype(np.float64).astype(np.int64))
result[mask] = masked_result.astype("M8[ns]")
@@ -986,7 +992,7 @@ def calc_with_mask(carg, mask):
# string with NaN-like
try:
- mask = ~algorithms.isin(arg, list(tslibs.nat_strings))
+ mask = ~algorithms.isin(arg, list(nat_strings))
return calc_with_mask(arg, mask)
except (ValueError, OverflowError, TypeError):
pass
diff --git a/pandas/core/tools/numeric.py b/pandas/core/tools/numeric.py
index cff4695603d06..32ca83787c4c1 100644
--- a/pandas/core/tools/numeric.py
+++ b/pandas/core/tools/numeric.py
@@ -186,7 +186,7 @@ def to_numeric(arg, errors="raise", downcast=None):
break
if is_series:
- return pd.Series(values, index=arg.index, name=arg.name)
+ return arg._constructor(values, index=arg.index, name=arg.name)
elif is_index:
# because we want to coerce to numeric if possible,
# do not use _shallow_copy
diff --git a/pandas/core/tools/times.py b/pandas/core/tools/times.py
index 3bac4cf0edb63..643c1165180b4 100644
--- a/pandas/core/tools/times.py
+++ b/pandas/core/tools/times.py
@@ -5,11 +5,9 @@
from pandas._libs.lib import is_list_like
-from pandas.core.dtypes.generic import ABCSeries
+from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries
from pandas.core.dtypes.missing import notna
-from pandas.core.indexes.base import Index
-
def to_time(arg, format=None, infer_time_format=False, errors="raise"):
"""
@@ -105,7 +103,7 @@ def _convert_listlike(arg, format):
elif isinstance(arg, ABCSeries):
values = _convert_listlike(arg._values, format)
return arg._constructor(values, index=arg.index, name=arg.name)
- elif isinstance(arg, Index):
+ elif isinstance(arg, ABCIndexClass):
return _convert_listlike(arg, format)
elif is_list_like(arg):
return _convert_listlike(arg, format)
| - [ ] 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/37112 | 2020-10-14T01:05:36Z | 2020-10-14T12:12:38Z | 2020-10-14T12:12:38Z | 2020-10-14T14:41:30Z |
CLN: ops, unnecessary mixin | diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index eb5e5b03fe243..dd9adc59c909b 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -75,6 +75,7 @@
from pandas.core.arrays import DatetimeArray, TimedeltaArray
DTScalarOrNaT = Union[DatetimeLikeScalar, NaTType]
+DatetimeLikeArrayT = TypeVar("DatetimeLikeArrayT", bound="DatetimeLikeArrayMixin")
class InvalidComparison(Exception):
@@ -86,7 +87,20 @@ class InvalidComparison(Exception):
pass
-class AttributesMixin:
+class DatetimeLikeArrayMixin(OpsMixin, NDArrayBackedExtensionArray):
+ """
+ Shared Base/Mixin class for DatetimeArray, TimedeltaArray, PeriodArray
+
+ Assumes that __new__/__init__ defines:
+ _data
+ _freq
+
+ and that the inheriting class has methods:
+ _generate_range
+ """
+
+ _is_recognized_dtype: Callable[[DtypeObj], bool]
+ _recognized_scalars: Tuple[Type, ...]
_data: np.ndarray
def __init__(self, data, dtype=None, freq=None, copy=False):
@@ -184,25 +198,6 @@ def _check_compatible_with(
"""
raise AbstractMethodError(self)
-
-DatetimeLikeArrayT = TypeVar("DatetimeLikeArrayT", bound="DatetimeLikeArrayMixin")
-
-
-class DatetimeLikeArrayMixin(OpsMixin, AttributesMixin, NDArrayBackedExtensionArray):
- """
- Shared Base/Mixin class for DatetimeArray, TimedeltaArray, PeriodArray
-
- Assumes that __new__/__init__ defines:
- _data
- _freq
-
- and that the inheriting class has methods:
- _generate_range
- """
-
- _is_recognized_dtype: Callable[[DtypeObj], bool]
- _recognized_scalars: Tuple[Type, ...]
-
# ------------------------------------------------------------------
# NDArrayBackedExtensionArray compat
@@ -861,7 +856,9 @@ def _cmp_method(self, other, op):
# 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)
+ result = ops.comp_method_OBJECT_ARRAY(
+ op, np.asarray(self.astype(object)), other
+ )
return result
other_i8 = self._unbox(other)
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py
index 69b5abe65057a..27b6ad37bb612 100644
--- a/pandas/core/ops/__init__.py
+++ b/pandas/core/ops/__init__.py
@@ -28,8 +28,8 @@
from pandas.core.ops.common import unpack_zerodim_and_defer # noqa:F401
from pandas.core.ops.docstrings import (
_flex_comp_doc_FRAME,
- _make_flex_doc,
_op_descriptions,
+ make_flex_doc,
)
from pandas.core.ops.invalid import invalid_comparison # noqa:F401
from pandas.core.ops.mask_ops import kleene_and, kleene_or, kleene_xor # noqa: F401
@@ -209,7 +209,7 @@ def align_method_SERIES(left: "Series", right, align_asobject: bool = False):
def flex_method_SERIES(op):
name = op.__name__.strip("_")
- doc = _make_flex_doc(name, "series")
+ doc = make_flex_doc(name, "series")
@Appender(doc)
def flex_wrapper(self, other, level=None, fill_value=None, axis=0):
@@ -445,7 +445,7 @@ def flex_arith_method_FRAME(op):
default_axis = "columns"
na_op = get_array_op(op)
- doc = _make_flex_doc(op_name, "dataframe")
+ doc = make_flex_doc(op_name, "dataframe")
@Appender(doc)
def f(self, other, axis=default_axis, level=None, fill_value=None):
diff --git a/pandas/core/ops/array_ops.py b/pandas/core/ops/array_ops.py
index fd5f126051c53..97fa7988c1774 100644
--- a/pandas/core/ops/array_ops.py
+++ b/pandas/core/ops/array_ops.py
@@ -57,7 +57,7 @@ def comp_method_OBJECT_ARRAY(op, x, y):
return result.reshape(x.shape)
-def masked_arith_op(x: np.ndarray, y, op):
+def _masked_arith_op(x: np.ndarray, y, op):
"""
If the given arithmetic operation fails, attempt it again on
only the non-null elements of the input array(s).
@@ -116,7 +116,7 @@ def masked_arith_op(x: np.ndarray, y, op):
return result
-def na_arithmetic_op(left, right, op, is_cmp: bool = False):
+def _na_arithmetic_op(left, right, op, is_cmp: bool = False):
"""
Return the result of evaluating op on the passed in values.
@@ -147,7 +147,7 @@ def na_arithmetic_op(left, right, op, is_cmp: bool = False):
# In this case we do not fall back to the masked op, as that
# will handle complex numbers incorrectly, see GH#32047
raise
- result = masked_arith_op(left, right, op)
+ result = _masked_arith_op(left, right, op)
if is_cmp and (is_scalar(result) or result is NotImplemented):
# numpy returned a scalar instead of operating element-wise
@@ -179,7 +179,7 @@ def arithmetic_op(left: ArrayLike, right: Any, op):
# on `left` and `right`.
lvalues = maybe_upcast_datetimelike_array(left)
rvalues = maybe_upcast_datetimelike_array(right)
- rvalues = maybe_upcast_for_op(rvalues, lvalues.shape)
+ rvalues = _maybe_upcast_for_op(rvalues, lvalues.shape)
if should_extension_dispatch(lvalues, rvalues) or isinstance(rvalues, Timedelta):
# Timedelta is included because numexpr will fail on it, see GH#31457
@@ -187,7 +187,7 @@ def arithmetic_op(left: ArrayLike, right: Any, op):
else:
with np.errstate(all="ignore"):
- res_values = na_arithmetic_op(lvalues, rvalues, op)
+ res_values = _na_arithmetic_op(lvalues, rvalues, op)
return res_values
@@ -248,7 +248,7 @@ def comparison_op(left: ArrayLike, right: Any, op) -> ArrayLike:
# suppress warnings from numpy about element-wise comparison
warnings.simplefilter("ignore", DeprecationWarning)
with np.errstate(all="ignore"):
- res_values = na_arithmetic_op(lvalues, rvalues, op, is_cmp=True)
+ res_values = _na_arithmetic_op(lvalues, rvalues, op, is_cmp=True)
return res_values
@@ -427,7 +427,7 @@ def maybe_upcast_datetimelike_array(obj: ArrayLike) -> ArrayLike:
return obj
-def maybe_upcast_for_op(obj, shape: Tuple[int, ...]):
+def _maybe_upcast_for_op(obj, shape: Tuple[int, ...]):
"""
Cast non-pandas objects to pandas types to unify behavior of arithmetic
and comparison operations.
diff --git a/pandas/core/ops/docstrings.py b/pandas/core/ops/docstrings.py
index 839bdbfb2444a..08b7b0e89ea5f 100644
--- a/pandas/core/ops/docstrings.py
+++ b/pandas/core/ops/docstrings.py
@@ -4,7 +4,7 @@
from typing import Dict, Optional
-def _make_flex_doc(op_name, typ: str):
+def make_flex_doc(op_name: str, typ: str) -> str:
"""
Make the appropriate substitutions for the given operation and class-typ
into either _flex_doc_SERIES or _flex_doc_FRAME to return the docstring
@@ -427,33 +427,6 @@ def _make_flex_doc(op_name, typ: str):
Series.{reverse} : {see_also_desc}.
"""
-_arith_doc_FRAME = """
-Binary operator %s with support to substitute a fill_value for missing data in
-one of the inputs
-
-Parameters
-----------
-other : Series, DataFrame, or constant
-axis : {0, 1, 'index', 'columns'}
- For Series input, axis to match Series index on
-fill_value : None or float value, default None
- Fill existing missing (NaN) values, and any new element needed for
- successful DataFrame alignment, with this value before computation.
- If data in both corresponding DataFrame locations is missing
- the result will be missing
-level : int or name
- Broadcast across a level, matching Index values on the
- passed MultiIndex level
-
-Returns
--------
-result : DataFrame
-
-Notes
------
-Mismatched indices will be unioned together
-"""
-
_flex_doc_FRAME = """
Get {desc} of dataframe and other, element-wise (binary operator `{op_name}`).
diff --git a/scripts/validate_unwanted_patterns.py b/scripts/validate_unwanted_patterns.py
index b6ffab1482bbc..119ae1cce2ff0 100755
--- a/scripts/validate_unwanted_patterns.py
+++ b/scripts/validate_unwanted_patterns.py
@@ -33,9 +33,7 @@
"_get_version",
"__main__",
"_transform_template",
- "_arith_doc_FRAME",
"_flex_comp_doc_FRAME",
- "_make_flex_doc",
"_op_descriptions",
"_IntegerDtype",
"_use_inf_as_na",
| - [ ] 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/37111 | 2020-10-14T01:02:28Z | 2020-10-14T12:14:07Z | 2020-10-14T12:14:07Z | 2020-10-14T14:43:15Z |
TYP: fix typing errors for mypy==0.790, bump mypy version | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 946fda5f82279..cb97fdeccd579 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -88,7 +88,7 @@ If installed, we now require:
+-----------------+-----------------+----------+---------+
| pytest (dev) | 5.0.1 | | |
+-----------------+-----------------+----------+---------+
-| mypy (dev) | 0.782 | | |
+| mypy (dev) | 0.790 | | X |
+-----------------+-----------------+----------+---------+
For `optional libraries <https://dev.pandas.io/docs/install.html#dependencies>`_ the general recommendation is to use the latest version.
diff --git a/environment.yml b/environment.yml
index 600a20b153ed3..09736aeea25f2 100644
--- a/environment.yml
+++ b/environment.yml
@@ -23,7 +23,7 @@ dependencies:
- flake8
- flake8-comprehensions>=3.1.0 # used by flake8, linting of unnecessary comprehensions
- isort>=5.2.1 # check that imports are in the right order
- - mypy=0.782
+ - mypy=0.790
- pre-commit>=2.9.2
- pycodestyle # used by flake8
- pyupgrade
diff --git a/pandas/core/computation/parsing.py b/pandas/core/computation/parsing.py
index ef79c2b77e4e5..732b0650e5bd7 100644
--- a/pandas/core/computation/parsing.py
+++ b/pandas/core/computation/parsing.py
@@ -38,10 +38,7 @@ def create_valid_python_identifier(name: str) -> str:
# token.tok_name contains a readable description of the replacement string.
special_characters_replacements = {
char: f"_{token.tok_name[tokval]}_"
- # The ignore here is because of a bug in mypy that is resolved in 0.740
- for char, tokval in (
- tokenize.EXACT_TOKEN_TYPES.items() # type: ignore[attr-defined]
- )
+ for char, tokval in (tokenize.EXACT_TOKEN_TYPES.items())
}
special_characters_replacements.update(
{
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 3262407a99c0a..62d11183691f0 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -283,8 +283,8 @@ def groups(self) -> Dict[Hashable, np.ndarray]:
return self.groupings[0].groups
else:
to_groupby = zip(*(ping.grouper for ping in self.groupings))
- to_groupby = Index(to_groupby)
- return self.axis.groupby(to_groupby)
+ index = Index(to_groupby)
+ return self.axis.groupby(index)
@final
@cache_readonly
diff --git a/pandas/io/common.py b/pandas/io/common.py
index 8f04724773a8a..12a886d057199 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -179,7 +179,8 @@ def stringify_path(
# this function with convert_file_like=True to infer the compression.
return cast(FileOrBuffer[AnyStr], filepath_or_buffer)
- if isinstance(filepath_or_buffer, os.PathLike):
+ # Only @runtime_checkable protocols can be used with instance and class checks
+ if isinstance(filepath_or_buffer, os.PathLike): # type: ignore[misc]
filepath_or_buffer = filepath_or_buffer.__fspath__()
return _expand_user(filepath_or_buffer)
@@ -487,9 +488,15 @@ def infer_compression(
if compression in _compression_to_extension:
return compression
- msg = f"Unrecognized compression type: {compression}"
- valid = ["infer", None] + sorted(_compression_to_extension)
- msg += f"\nValid compression types are {valid}"
+ # https://github.com/python/mypy/issues/5492
+ # Unsupported operand types for + ("List[Optional[str]]" and "List[str]")
+ valid = ["infer", None] + sorted(
+ _compression_to_extension
+ ) # type: ignore[operator]
+ msg = (
+ f"Unrecognized compression type: {compression}\n"
+ f"Valid compression types are {valid}"
+ )
raise ValueError(msg)
diff --git a/requirements-dev.txt b/requirements-dev.txt
index d45e87b1785b0..80fd7b243f6ce 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -11,7 +11,7 @@ cpplint
flake8
flake8-comprehensions>=3.1.0
isort>=5.2.1
-mypy==0.782
+mypy==0.790
pre-commit>=2.9.2
pycodestyle
pyupgrade
| - [x] closes #37104
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
| https://api.github.com/repos/pandas-dev/pandas/pulls/37108 | 2020-10-13T20:31:00Z | 2021-01-10T09:38:05Z | 2021-01-10T09:38:04Z | 2021-01-10T15:29:51Z |
CLN: remove unnecessary _validate_foo methods | diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py
index 95a003efbe1d0..948ffdc1f7c01 100644
--- a/pandas/core/arrays/_mixins.py
+++ b/pandas/core/arrays/_mixins.py
@@ -180,13 +180,10 @@ def _validate_shift_value(self, fill_value):
return self._validate_fill_value(fill_value)
def __setitem__(self, key, value):
- key = self._validate_setitem_key(key)
+ key = check_array_indexer(self, key)
value = self._validate_setitem_value(value)
self._ndarray[key] = value
- def _validate_setitem_key(self, key):
- return check_array_indexer(self, key)
-
def _validate_setitem_value(self, value):
return value
@@ -198,7 +195,8 @@ def __getitem__(self, key):
return self._box_func(result)
return self._from_backing_data(result)
- key = self._validate_getitem_key(key)
+ key = extract_array(key, extract_numpy=True)
+ key = check_array_indexer(self, key)
result = self._ndarray[key]
if lib.is_scalar(result):
return self._box_func(result)
@@ -206,10 +204,6 @@ def __getitem__(self, key):
result = self._from_backing_data(result)
return result
- def _validate_getitem_key(self, key):
- key = extract_array(key, extract_numpy=True)
- return check_array_indexer(self, key)
-
@doc(ExtensionArray.fillna)
def fillna(self: _T, value=None, method=None, limit=None) -> _T:
value, method = validate_fillna_kwargs(value, method)
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index eb5e5b03fe243..f1455aa864197 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -65,7 +65,7 @@
from pandas.core.arrays._mixins import NDArrayBackedExtensionArray
import pandas.core.common as com
from pandas.core.construction import array, extract_array
-from pandas.core.indexers import check_setitem_lengths
+from pandas.core.indexers import check_array_indexer, check_setitem_lengths
from pandas.core.ops.common import unpack_zerodim_and_defer
from pandas.core.ops.invalid import invalid_comparison, make_invalid_op
@@ -294,7 +294,7 @@ def _get_getitem_freq(self, key):
elif self.ndim != 1:
freq = None
else:
- key = self._validate_getitem_key(key) # maybe ndarray[bool] -> slice
+ key = check_array_indexer(self, key) # maybe ndarray[bool] -> slice
freq = None
if isinstance(key, slice):
if self.freq is not None and key.step is not None:
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
since DatetimeLike and Categorical no longer special-case these, we can inline them. | https://api.github.com/repos/pandas-dev/pandas/pulls/37106 | 2020-10-13T18:37:02Z | 2020-10-14T12:21:59Z | 2020-10-14T12:21:59Z | 2020-10-14T14:42:29Z |
VIS: Accept xlabel and ylabel for scatter and hexbin plots | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index a963442ecda1c..d9d1ce797dd62 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -193,6 +193,7 @@ Other enhancements
- Where possible :meth:`RangeIndex.difference` and :meth:`RangeIndex.symmetric_difference` will return :class:`RangeIndex` instead of :class:`Int64Index` (:issue:`36564`)
- Added :meth:`Rolling.sem()` and :meth:`Expanding.sem()` to compute the standard error of mean (:issue:`26476`).
- :meth:`Rolling.var()` and :meth:`Rolling.std()` use Kahan summation and Welfords Method to avoid numerical issues (:issue:`37051`)
+- :meth:`DataFrame.plot` now recognizes ``xlabel`` and ``ylabel`` arguments for plots of type ``scatter`` and ``hexbin`` (:issue:`37001`)
.. _whatsnew_120.api_breaking.python:
diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py
index d02f12a8e1029..e0e35e31d22ac 100644
--- a/pandas/plotting/_core.py
+++ b/pandas/plotting/_core.py
@@ -678,15 +678,25 @@ class PlotAccessor(PandasObject):
ylim : 2-tuple/list
Set the y limits of the current axes.
xlabel : label, optional
- Name to use for the xlabel on x-axis. Default uses index name as xlabel.
+ Name to use for the xlabel on x-axis. Default uses index name as xlabel, or the
+ x-column name for planar plots.
.. versionadded:: 1.1.0
+ .. versionchanged:: 1.2.0
+
+ Now applicable to planar plots (`scatter`, `hexbin`).
+
ylabel : label, optional
- Name to use for the ylabel on y-axis. Default will show no ylabel.
+ Name to use for the ylabel on y-axis. Default will show no ylabel, or the
+ y-column name for planar plots.
.. versionadded:: 1.1.0
+ .. versionchanged:: 1.2.0
+
+ Now applicable to planar plots (`scatter`, `hexbin`).
+
rot : int, default None
Rotation for ticks (xticks for vertical, yticks for horizontal
plots).
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py
index a69767df267fc..6c9924e0ada79 100644
--- a/pandas/plotting/_matplotlib/core.py
+++ b/pandas/plotting/_matplotlib/core.py
@@ -924,8 +924,10 @@ def nseries(self) -> int:
def _post_plot_logic(self, ax: "Axes", data):
x, y = self.x, self.y
- ax.set_ylabel(pprint_thing(y))
- ax.set_xlabel(pprint_thing(x))
+ xlabel = self.xlabel if self.xlabel is not None else pprint_thing(x)
+ ylabel = self.ylabel if self.ylabel is not None else pprint_thing(y)
+ ax.set_xlabel(xlabel)
+ ax.set_ylabel(ylabel)
def _plot_colorbar(self, ax: "Axes", **kwds):
# Addresses issues #10611 and #10678:
diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py
index d4d2256d209cf..e666a8e412a52 100644
--- a/pandas/tests/plotting/test_frame.py
+++ b/pandas/tests/plotting/test_frame.py
@@ -3449,6 +3449,27 @@ def test_xlabel_ylabel_dataframe_single_plot(
assert ax.get_ylabel() == str(new_label)
assert ax.get_xlabel() == str(new_label)
+ @pytest.mark.parametrize(
+ "xlabel, ylabel",
+ [
+ (None, None),
+ ("X Label", None),
+ (None, "Y Label"),
+ ("X Label", "Y Label"),
+ ],
+ )
+ @pytest.mark.parametrize("kind", ["scatter", "hexbin"])
+ def test_xlabel_ylabel_dataframe_plane_plot(self, kind, xlabel, ylabel):
+ # GH 37001
+ xcol = "Type A"
+ ycol = "Type B"
+ df = pd.DataFrame([[1, 2], [2, 5]], columns=[xcol, ycol])
+
+ # default is the labels are column names
+ ax = df.plot(kind=kind, x=xcol, y=ycol, xlabel=xlabel, ylabel=ylabel)
+ assert ax.get_xlabel() == (xcol if xlabel is None else xlabel)
+ assert ax.get_ylabel() == (ycol if ylabel is None else ylabel)
+
@pytest.mark.parametrize(
"index_name, old_label, new_label",
[
| - [x] closes #37001
- [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/37102 | 2020-10-13T15:44:23Z | 2020-10-14T17:54:11Z | 2020-10-14T17:54:11Z | 2020-10-15T08:02:43Z |
Update code_checks.sh to check for instances of os.remove | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index 784d2c9a411ab..5437692d54439 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -268,6 +268,10 @@ if [[ -z "$CHECK" || "$CHECK" == "patterns" ]]; then
invgrep -RI --exclude=\*.{svg,c,cpp,html,js} --exclude-dir=env "\s$" *
RET=$(($RET + $?)) ; echo $MSG "DONE"
unset INVGREP_APPEND
+
+ MSG='Check code for instances of os.remove' ; echo $MSG
+ invgrep -R --include="*.py*" --exclude "common.py" --exclude "test_writers.py" --exclude "test_store.py" -E "os\.remove" pandas/tests/
+ RET=$(($RET + $?)) ; echo $MSG "DONE"
fi
### CODE ###
| I have included a check for instances of os.remove in the tests folder. This is in line with issue #37095 whereby ensure_clean should be used rather than os.remove.
A few outstanding questions remain:
- Should this be expanded to search for cases of os.remove elsewhere?
- ~~Cases of `os.remove ` still exist in common.py, test_writers.py, and test_store.py. For some reason, the case in test_store.py is not picked up by this check? Any idea why?~~ _(solved by passing arguments separately rather than as a list)_
- ~~Advice on how to implement this as a pre-commit hook also welcome.~~ _(to be implemented in separate PR)_
- [x] closes #37095
- [ ] 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/37097 | 2020-10-13T10:42:01Z | 2020-10-16T01:30:56Z | 2020-10-16T01:30:55Z | 2020-10-16T09:13:58Z |
Gh 36562 typeerror comparison not supported between float and str | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index 7111d54d65815..ae6e2de1b819c 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -469,6 +469,7 @@ MultiIndex
- Bug in :meth:`DataFrame.xs` when used with :class:`IndexSlice` raises ``TypeError`` with message ``"Expected label or tuple of labels"`` (:issue:`35301`)
- Bug in :meth:`DataFrame.reset_index` with ``NaT`` values in index raises ``ValueError`` with message ``"cannot convert float NaN to integer"`` (:issue:`36541`)
+- Bug in :meth:`DataFrame.combine_first` when used with :class:`MultiIndex` containing string and ``NaN`` values raises ``TypeError`` (:issue:`36562`)
I/O
^^^
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index e9e04ace784b6..ec88eb817b3f8 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -2061,27 +2061,25 @@ def safe_sort(
dtype, _ = infer_dtype_from_array(values)
values = np.asarray(values, dtype=dtype)
- def sort_mixed(values):
- # order ints before strings, safe in py3
- str_pos = np.array([isinstance(x, str) for x in values], dtype=bool)
- nums = np.sort(values[~str_pos])
- strs = np.sort(values[str_pos])
- return np.concatenate([nums, np.asarray(strs, dtype=object)])
-
sorter = None
+
if (
not is_extension_array_dtype(values)
and lib.infer_dtype(values, skipna=False) == "mixed-integer"
):
- # unorderable in py3 if mixed str/int
- ordered = sort_mixed(values)
+ ordered = _sort_mixed(values)
else:
try:
sorter = values.argsort()
ordered = values.take(sorter)
except TypeError:
- # try this anyway
- ordered = sort_mixed(values)
+ # Previous sorters failed or were not applicable, try `_sort_mixed`
+ # which would work, but which fails for special case of 1d arrays
+ # with tuples.
+ if values.size and isinstance(values[0], tuple):
+ ordered = _sort_tuples(values)
+ else:
+ ordered = _sort_mixed(values)
# codes:
@@ -2128,3 +2126,26 @@ def sort_mixed(values):
np.putmask(new_codes, mask, na_sentinel)
return ordered, ensure_platform_int(new_codes)
+
+
+def _sort_mixed(values):
+ """ order ints before strings in 1d arrays, safe in py3 """
+ str_pos = np.array([isinstance(x, str) for x in values], dtype=bool)
+ nums = np.sort(values[~str_pos])
+ strs = np.sort(values[str_pos])
+ return np.concatenate([nums, np.asarray(strs, dtype=object)])
+
+
+def _sort_tuples(values: np.ndarray[tuple]):
+ """
+ Convert array of tuples (1d) to array or array (2d).
+ We need to keep the columns separately as they contain different types and
+ nans (can't use `np.sort` as it may fail when str and nan are mixed in a
+ column as types cannot be compared).
+ """
+ from pandas.core.internals.construction import to_arrays
+ from pandas.core.sorting import lexsort_indexer
+
+ arrays, _ = to_arrays(values, None)
+ indexer = lexsort_indexer(arrays, orders=True)
+ return values[indexer]
diff --git a/pandas/tests/frame/methods/test_combine_first.py b/pandas/tests/frame/methods/test_combine_first.py
index 4850c6a50f8a8..08c4293323500 100644
--- a/pandas/tests/frame/methods/test_combine_first.py
+++ b/pandas/tests/frame/methods/test_combine_first.py
@@ -4,7 +4,7 @@
import pytest
import pandas as pd
-from pandas import DataFrame, Index, Series
+from pandas import DataFrame, Index, MultiIndex, Series
import pandas._testing as tm
@@ -365,3 +365,32 @@ def test_combine_first_string_dtype_only_na(self):
{"a": ["962", "85"], "b": [pd.NA] * 2}, dtype="string"
).set_index(["a", "b"])
tm.assert_frame_equal(result, expected)
+
+
+def test_combine_first_with_nan_multiindex():
+ # gh-36562
+
+ mi1 = MultiIndex.from_arrays(
+ [["b", "b", "c", "a", "b", np.nan], [1, 2, 3, 4, 5, 6]], names=["a", "b"]
+ )
+ df = DataFrame({"c": [1, 1, 1, 1, 1, 1]}, index=mi1)
+ mi2 = MultiIndex.from_arrays(
+ [["a", "b", "c", "a", "b", "d"], [1, 1, 1, 1, 1, 1]], names=["a", "b"]
+ )
+ s = Series([1, 2, 3, 4, 5, 6], index=mi2)
+ res = df.combine_first(DataFrame({"d": s}))
+ mi_expected = MultiIndex.from_arrays(
+ [
+ ["a", "a", "a", "b", "b", "b", "b", "c", "c", "d", np.nan],
+ [1, 1, 4, 1, 1, 2, 5, 1, 3, 1, 6],
+ ],
+ names=["a", "b"],
+ )
+ expected = DataFrame(
+ {
+ "c": [np.nan, np.nan, 1, 1, 1, 1, 1, np.nan, 1, np.nan, 1],
+ "d": [1.0, 4.0, np.nan, 2.0, 5.0, np.nan, np.nan, 3.0, np.nan, 6.0, np.nan],
+ },
+ index=mi_expected,
+ )
+ tm.assert_frame_equal(res, expected)
diff --git a/pandas/tests/test_sorting.py b/pandas/tests/test_sorting.py
index 1c9fd46ae451f..5f85ae2ec2318 100644
--- a/pandas/tests/test_sorting.py
+++ b/pandas/tests/test_sorting.py
@@ -453,3 +453,10 @@ def test_extension_array_codes(self, verify, na_sentinel):
expected_codes = np.array([0, 2, na_sentinel, 1], dtype=np.intp)
tm.assert_extension_array_equal(result, expected_values)
tm.assert_numpy_array_equal(codes, expected_codes)
+
+
+def test_mixed_str_nan():
+ values = np.array(["b", np.nan, "a", "b"], dtype=object)
+ result = safe_sort(values)
+ expected = np.array([np.nan, "a", "b", "b"], dtype=object)
+ tm.assert_numpy_array_equal(result, expected)
| - [x] closes #36562
- [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/37096 | 2020-10-13T09:51:07Z | 2020-11-04T01:55:12Z | 2020-11-04T01:55:11Z | 2021-08-19T01:54:36Z |
REF/TYP: pandas/core/window/*.py | diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx
index 131e0154ce8fc..fe97c048d4472 100644
--- a/pandas/_libs/window/aggregations.pyx
+++ b/pandas/_libs/window/aggregations.pyx
@@ -3,7 +3,6 @@
import cython
from cython import Py_ssize_t
-from libc.stdlib cimport free, malloc
from libcpp.deque cimport deque
import numpy as np
@@ -906,7 +905,7 @@ 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,
+ ndarray[int64_t] end, int64_t minp,
float64_t quantile, str interpolation):
"""
O(N log(window)) implementation using skip list
@@ -933,7 +932,7 @@ def roll_quantile(ndarray[float64_t, cast=True] values, ndarray[int64_t] start,
# actual skiplist ops outweigh any window computation costs
output = np.empty(N, dtype=float)
- if win == 0 or (end - start).max() == 0:
+ if (end - start).max() == 0:
output[:] = NaN
return output
win = (end - start).max()
@@ -1020,7 +1019,7 @@ def roll_quantile(ndarray[float64_t, cast=True] values, ndarray[int64_t] start,
def roll_apply(object obj,
ndarray[int64_t] start, ndarray[int64_t] end,
int64_t minp,
- object func, bint raw,
+ object function, bint raw,
tuple args, dict kwargs):
cdef:
ndarray[float64_t] output, counts
@@ -1048,9 +1047,9 @@ def roll_apply(object obj,
if counts[i] >= minp:
if raw:
- output[i] = func(arr[s:e], *args, **kwargs)
+ output[i] = function(arr[s:e], *args, **kwargs)
else:
- output[i] = func(obj.iloc[s:e], *args, **kwargs)
+ output[i] = function(obj.iloc[s:e], *args, **kwargs)
else:
output[i] = NaN
diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py
index 25938b57d9720..9f7040943d9a3 100644
--- a/pandas/core/window/ewm.py
+++ b/pandas/core/window/ewm.py
@@ -1,7 +1,7 @@
import datetime
from functools import partial
from textwrap import dedent
-from typing import Optional, Union
+from typing import TYPE_CHECKING, Optional, Union
import numpy as np
@@ -17,6 +17,10 @@
from pandas.core.window.common import _doc_template, _shared_docs, zsqrt
from pandas.core.window.rolling import BaseWindow, flex_binary_moment
+if TYPE_CHECKING:
+ from pandas import Series
+
+
_bias_template = """
Parameters
----------
@@ -60,6 +64,15 @@ def get_center_of_mass(
return float(comass)
+def wrap_result(obj: "Series", result: np.ndarray) -> "Series":
+ """
+ Wrap a single 1D result.
+ """
+ obj = obj._selected_obj
+
+ return obj._constructor(result, obj.index, name=obj.name)
+
+
class ExponentialMovingWindow(BaseWindow):
r"""
Provide exponential weighted (EW) functions.
@@ -413,7 +426,7 @@ def _get_cov(X, Y):
self.min_periods,
bias,
)
- return X._wrap_result(cov)
+ return wrap_result(X, cov)
return flex_binary_moment(
self._selected_obj, other._selected_obj, _get_cov, pairwise=bool(pairwise)
@@ -467,7 +480,7 @@ def _cov(x, y):
x_var = _cov(x_values, x_values)
y_var = _cov(y_values, y_values)
corr = cov / zsqrt(x_var * y_var)
- return X._wrap_result(corr)
+ return wrap_result(X, corr)
return flex_binary_moment(
self._selected_obj, other._selected_obj, _get_corr, pairwise=bool(pairwise)
diff --git a/pandas/core/window/expanding.py b/pandas/core/window/expanding.py
index 44e0e36b61d46..aa1dfe8567c15 100644
--- a/pandas/core/window/expanding.py
+++ b/pandas/core/window/expanding.py
@@ -1,6 +1,9 @@
from textwrap import dedent
-from typing import Dict, Optional
+from typing import Any, Callable, Dict, Optional, Tuple, Union
+import numpy as np
+
+from pandas._typing import FrameOrSeries
from pandas.compat.numpy import function as nv
from pandas.util._decorators import Appender, Substitution, doc
@@ -65,7 +68,9 @@ def __init__(self, obj, min_periods=1, center=None, axis=0, **kwargs):
def _constructor(self):
return Expanding
- def _get_window(self, other=None, **kwargs):
+ def _get_window(
+ self, other: Optional[Union[np.ndarray, FrameOrSeries]] = None, **kwargs
+ ) -> int:
"""
Get the window length over which to perform some operation.
@@ -135,12 +140,12 @@ def count(self, **kwargs):
@Appender(_shared_docs["apply"])
def apply(
self,
- func,
+ func: Callable[..., Any],
raw: bool = False,
engine: Optional[str] = None,
engine_kwargs: Optional[Dict[str, bool]] = None,
- args=None,
- kwargs=None,
+ args: Optional[Tuple[Any, ...]] = None,
+ kwargs: Optional[Dict[str, Any]] = None,
):
return super().apply(
func,
@@ -183,19 +188,19 @@ def median(self, **kwargs):
@Substitution(name="expanding", versionadded="")
@Appender(_shared_docs["std"])
- def std(self, ddof=1, *args, **kwargs):
+ def std(self, ddof: int = 1, *args, **kwargs):
nv.validate_expanding_func("std", args, kwargs)
return super().std(ddof=ddof, **kwargs)
@Substitution(name="expanding", versionadded="")
@Appender(_shared_docs["var"])
- def var(self, ddof=1, *args, **kwargs):
+ def var(self, ddof: int = 1, *args, **kwargs):
nv.validate_expanding_func("var", args, kwargs)
return super().var(ddof=ddof, **kwargs)
@Substitution(name="expanding")
@Appender(_shared_docs["sem"])
- def sem(self, ddof=1, *args, **kwargs):
+ def sem(self, ddof: int = 1, *args, **kwargs):
return super().sem(ddof=ddof, **kwargs)
@Substitution(name="expanding", func_name="skew")
@@ -245,12 +250,23 @@ def quantile(self, quantile, interpolation="linear", **kwargs):
@Substitution(name="expanding", func_name="cov")
@Appender(_doc_template)
@Appender(_shared_docs["cov"])
- def cov(self, other=None, pairwise=None, ddof=1, **kwargs):
+ def cov(
+ self,
+ other: Optional[Union[np.ndarray, FrameOrSeries]] = None,
+ pairwise: Optional[bool] = None,
+ ddof: int = 1,
+ **kwargs,
+ ):
return super().cov(other=other, pairwise=pairwise, ddof=ddof, **kwargs)
@Substitution(name="expanding")
@Appender(_shared_docs["corr"])
- def corr(self, other=None, pairwise=None, **kwargs):
+ def corr(
+ self,
+ other: Optional[Union[np.ndarray, FrameOrSeries]] = None,
+ pairwise: Optional[bool] = None,
+ **kwargs,
+ ):
return super().corr(other=other, pairwise=pairwise, **kwargs)
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index fdeb91d37724d..4077e4e7e039e 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -8,6 +8,7 @@
from textwrap import dedent
from typing import (
TYPE_CHECKING,
+ Any,
Callable,
Dict,
List,
@@ -73,23 +74,6 @@
from pandas.core.internals import Block # noqa:F401
-def calculate_center_offset(window: np.ndarray) -> int:
- """
- Calculate an offset necessary to have the window label to be centered
- for weighted windows.
-
- Parameters
- ----------
- window: ndarray
- window weights
-
- Returns
- -------
- int
- """
- return (len(window) - 1) // 2
-
-
def calculate_min_periods(
window: int,
min_periods: Optional[int],
@@ -125,28 +109,6 @@ def calculate_min_periods(
return max(min_periods, floor)
-def get_weighted_roll_func(cfunc: Callable) -> Callable:
- """
- Wrap weighted rolling cython function with min periods argument.
-
- Parameters
- ----------
- cfunc : function
- Cython weighted rolling function
-
- Returns
- -------
- function
- """
-
- def func(arg, window, min_periods=None):
- if min_periods is None:
- min_periods = len(window)
- return cfunc(arg, window, min_periods)
-
- return func
-
-
class BaseWindow(ShallowMixin, SelectionMixin):
"""Provides utilities for performing windowing operations."""
@@ -213,25 +175,19 @@ def validate(self) -> None:
if not isinstance(self.obj, (ABCSeries, ABCDataFrame)):
raise TypeError(f"invalid type: {type(self)}")
if isinstance(self.window, BaseIndexer):
- self._validate_get_window_bounds_signature(self.window)
-
- @staticmethod
- def _validate_get_window_bounds_signature(window: BaseIndexer) -> None:
- """
- Validate that the passed BaseIndexer subclass has
- a get_window_bounds with the correct signature.
- """
- get_window_bounds_signature = inspect.signature(
- window.get_window_bounds
- ).parameters.keys()
- expected_signature = inspect.signature(
- BaseIndexer().get_window_bounds
- ).parameters.keys()
- if get_window_bounds_signature != expected_signature:
- raise ValueError(
- f"{type(window).__name__} does not implement the correct signature for "
- f"get_window_bounds"
- )
+ # Validate that the passed BaseIndexer subclass has
+ # a get_window_bounds with the correct signature.
+ get_window_bounds_signature = inspect.signature(
+ self.window.get_window_bounds
+ ).parameters.keys()
+ expected_signature = inspect.signature(
+ BaseIndexer().get_window_bounds
+ ).parameters.keys()
+ if get_window_bounds_signature != expected_signature:
+ raise ValueError(
+ f"{type(self.window).__name__} does not implement "
+ f"the correct signature for get_window_bounds"
+ )
def _create_data(self, obj: FrameOrSeries) -> FrameOrSeries:
"""
@@ -285,31 +241,16 @@ def __getattr__(self, attr: str):
def _dir_additions(self):
return self.obj._dir_additions()
- def _get_win_type(self, kwargs: Dict):
- """
- Exists for compatibility, overridden by subclass Window.
-
- Parameters
- ----------
- kwargs : dict
- ignored, exists for compatibility
-
- Returns
- -------
- None
- """
- return None
-
- def _get_window(self, other=None, win_type: Optional[str] = None) -> int:
+ def _get_window(
+ self, other: Optional[Union[np.ndarray, FrameOrSeries]] = None
+ ) -> int:
"""
Return window length.
Parameters
----------
other :
- ignored, exists for compatibility
- win_type :
- ignored, exists for compatibility
+ Used in Expanding
Returns
-------
@@ -336,7 +277,7 @@ def __repr__(self) -> str:
return f"{self._window_type} [{attrs}]"
def __iter__(self):
- window = self._get_window(win_type=None)
+ window = self._get_window()
obj = self._create_data(self._selected_obj)
index = self._get_window_indexer(window=window)
@@ -382,14 +323,6 @@ def _prep_values(self, values: Optional[np.ndarray] = None) -> np.ndarray:
return values
- def _wrap_result(self, result: np.ndarray) -> "Series":
- """
- Wrap a single 1D result.
- """
- obj = self._selected_obj
-
- return obj._constructor(result, obj.index, name=obj.name)
-
def _insert_on_column(self, result: "DataFrame", obj: "DataFrame"):
# if we have an 'on' column we want to put it back into
# the results in the same location
@@ -415,21 +348,7 @@ def _insert_on_column(self, result: "DataFrame", obj: "DataFrame"):
# insert at the end
result[name] = extra_col
- def _center_window(self, result: np.ndarray, window: np.ndarray) -> np.ndarray:
- """
- Center the result in the window for weighted rolling aggregations.
- """
- if self.axis > result.ndim - 1:
- raise ValueError("Requested axis is larger then no. of argument dimensions")
-
- offset = calculate_center_offset(window)
- if offset > 0:
- lead_indexer = [slice(None)] * result.ndim
- lead_indexer[self.axis] = slice(offset, None)
- result = np.copy(result[tuple(lead_indexer)])
- return result
-
- def _get_roll_func(self, func_name: str) -> Callable:
+ def _get_roll_func(self, func_name: str) -> Callable[..., Any]:
"""
Wrap rolling function to check values passed.
@@ -513,10 +432,9 @@ def hfunc(bvalues: ArrayLike) -> ArrayLike:
def _apply(
self,
- func: Callable,
+ func: Callable[..., Any],
require_min_periods: int = 0,
floor: int = 1,
- is_weighted: bool = False,
name: Optional[str] = None,
use_numba_cache: bool = False,
**kwargs,
@@ -531,9 +449,7 @@ def _apply(
func : callable function to apply
require_min_periods : int
floor : int
- is_weighted : bool
name : str,
- compatibility with groupby.rolling
use_numba_cache : bool
whether to cache a numba compiled function. Only available for numba
enabled methods (so far only apply)
@@ -544,8 +460,7 @@ def _apply(
-------
y : type of input
"""
- win_type = self._get_win_type(kwargs)
- window = self._get_window(win_type=win_type)
+ window = self._get_window()
window_indexer = self._get_window_indexer(window)
def homogeneous_func(values: np.ndarray):
@@ -554,36 +469,26 @@ def homogeneous_func(values: np.ndarray):
if values.size == 0:
return values.copy()
- if not is_weighted:
-
- def calc(x):
- 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(
- window_indexer.window_size,
- self.min_periods,
- len(x),
- require_min_periods,
- floor,
- )
- start, end = window_indexer.get_window_bounds(
- num_values=len(x),
- min_periods=self.min_periods,
- center=self.center,
- closed=self.closed,
+ def calc(x):
+ if not isinstance(self.window, BaseIndexer):
+ min_periods = calculate_min_periods(
+ window, self.min_periods, len(x), require_min_periods, floor
)
- return func(x, start, end, min_periods)
-
- else:
-
- def calc(x):
- offset = calculate_center_offset(window) if self.center else 0
- additional_nans = np.array([np.nan] * offset)
- x = np.concatenate((x, additional_nans))
- return func(x, window, self.min_periods)
+ else:
+ min_periods = calculate_min_periods(
+ window_indexer.window_size,
+ self.min_periods,
+ len(x),
+ require_min_periods,
+ floor,
+ )
+ start, end = window_indexer.get_window_bounds(
+ num_values=len(x),
+ min_periods=self.min_periods,
+ center=self.center,
+ closed=self.closed,
+ )
+ return func(x, start, end, min_periods)
with np.errstate(all="ignore"):
if values.ndim > 1:
@@ -595,9 +500,6 @@ def calc(x):
if use_numba_cache:
NUMBA_FUNC_CACHE[(kwargs["original_func"], "rolling_apply")] = func
- if self.center and is_weighted:
- result = self._center_window(result, window)
-
return result
return self._apply_blockwise(homogeneous_func, name)
@@ -890,19 +792,17 @@ def __init__(self, obj, *args, **kwargs):
def _apply(
self,
- func: Callable,
+ func: Callable[..., Any],
require_min_periods: int = 0,
floor: int = 1,
- is_weighted: bool = False,
name: Optional[str] = None,
use_numba_cache: bool = False,
**kwargs,
- ):
+ ) -> FrameOrSeries:
result = super()._apply(
func,
require_min_periods,
floor,
- is_weighted,
name,
use_numba_cache,
**kwargs,
@@ -1166,7 +1066,7 @@ def validate(self):
else:
raise ValueError(f"Invalid window {window}")
- def _get_win_type(self, kwargs: Dict) -> Union[str, Tuple]:
+ def _get_win_type(self, kwargs: Dict[str, Any]) -> Union[str, Tuple]:
"""
Extract arguments for the window type, provide validation for it
and return the validated window type.
@@ -1210,16 +1110,27 @@ def _pop_args(win_type, arg_names, kwargs):
return _validate_win_type(self.win_type, kwargs)
- def _get_window(
- self, other=None, win_type: Optional[Union[str, Tuple]] = None
+ def _center_window(self, result: np.ndarray, offset: int) -> np.ndarray:
+ """
+ Center the result in the window for weighted rolling aggregations.
+ """
+ if self.axis > result.ndim - 1:
+ raise ValueError("Requested axis is larger then no. of argument dimensions")
+
+ if offset > 0:
+ lead_indexer = [slice(None)] * result.ndim
+ lead_indexer[self.axis] = slice(offset, None)
+ result = np.copy(result[tuple(lead_indexer)])
+ return result
+
+ def _get_window_weights(
+ self, win_type: Optional[Union[str, Tuple]] = None
) -> np.ndarray:
"""
Get the window, weights.
Parameters
----------
- other :
- ignored, exists for compatibility
win_type : str, or tuple
type of window to create
@@ -1237,6 +1148,65 @@ def _get_window(
# GH #15662. `False` makes symmetric window, rather than periodic.
return sig.get_window(win_type, window, False).astype(float)
+ def _apply(
+ self,
+ func: Callable[[np.ndarray, int, int], np.ndarray],
+ require_min_periods: int = 0,
+ floor: int = 1,
+ name: Optional[str] = None,
+ use_numba_cache: bool = False,
+ **kwargs,
+ ):
+ """
+ Rolling with weights statistical measure using supplied function.
+
+ Designed to be used with passed-in Cython array-based functions.
+
+ Parameters
+ ----------
+ func : callable function to apply
+ require_min_periods : int
+ floor : int
+ name : str,
+ use_numba_cache : bool
+ whether to cache a numba compiled function. Only available for numba
+ enabled methods (so far only apply)
+ **kwargs
+ additional arguments for rolling function and window function
+
+ Returns
+ -------
+ y : type of input
+ """
+ win_type = self._get_win_type(kwargs)
+ window = self._get_window_weights(win_type=win_type)
+ offset = (len(window) - 1) // 2 if self.center else 0
+
+ def homogeneous_func(values: np.ndarray):
+ # calculation function
+
+ if values.size == 0:
+ return values.copy()
+
+ def calc(x):
+ additional_nans = np.array([np.nan] * offset)
+ x = np.concatenate((x, additional_nans))
+ return func(x, window, self.min_periods or len(window))
+
+ with np.errstate(all="ignore"):
+ if values.ndim > 1:
+ result = np.apply_along_axis(calc, self.axis, values)
+ else:
+ result = calc(values)
+ result = np.asarray(result)
+
+ if self.center:
+ result = self._center_window(result, offset)
+
+ return result
+
+ return self._apply_blockwise(homogeneous_func, name)
+
_agg_see_also_doc = dedent(
"""
See Also
@@ -1288,29 +1258,26 @@ def aggregate(self, func, *args, **kwargs):
def sum(self, *args, **kwargs):
nv.validate_window_func("sum", args, kwargs)
window_func = self._get_roll_func("roll_weighted_sum")
- window_func = get_weighted_roll_func(window_func)
- return self._apply(window_func, is_weighted=True, name="sum", **kwargs)
+ return self._apply(window_func, name="sum", **kwargs)
@Substitution(name="window")
@Appender(_shared_docs["mean"])
def mean(self, *args, **kwargs):
nv.validate_window_func("mean", args, kwargs)
window_func = self._get_roll_func("roll_weighted_mean")
- window_func = get_weighted_roll_func(window_func)
- return self._apply(window_func, is_weighted=True, name="mean", **kwargs)
+ return self._apply(window_func, name="mean", **kwargs)
@Substitution(name="window", versionadded="\n.. versionadded:: 1.0.0\n")
@Appender(_shared_docs["var"])
- def var(self, ddof=1, *args, **kwargs):
+ def var(self, ddof: int = 1, *args, **kwargs):
nv.validate_window_func("var", args, kwargs)
window_func = partial(self._get_roll_func("roll_weighted_var"), ddof=ddof)
- window_func = get_weighted_roll_func(window_func)
kwargs.pop("name", None)
- return self._apply(window_func, is_weighted=True, name="var", **kwargs)
+ return self._apply(window_func, name="var", **kwargs)
@Substitution(name="window", versionadded="\n.. versionadded:: 1.0.0\n")
@Appender(_shared_docs["std"])
- def std(self, ddof=1, *args, **kwargs):
+ def std(self, ddof: int = 1, *args, **kwargs):
nv.validate_window_func("std", args, kwargs)
return zsqrt(self.var(ddof=ddof, name="std", **kwargs))
@@ -1425,12 +1392,12 @@ def count(self):
def apply(
self,
- func,
+ func: Callable[..., Any],
raw: bool = False,
engine: Optional[str] = None,
- engine_kwargs: Optional[Dict] = None,
- args: Optional[Tuple] = None,
- kwargs: Optional[Dict] = None,
+ engine_kwargs: Optional[Dict[str, bool]] = None,
+ args: Optional[Tuple[Any, ...]] = None,
+ kwargs: Optional[Dict[str, Any]] = None,
):
if args is None:
args = ()
@@ -1460,7 +1427,13 @@ def apply(
kwargs=kwargs,
)
- def _generate_cython_apply_func(self, args, kwargs, raw, func):
+ def _generate_cython_apply_func(
+ self,
+ args: Tuple[Any, ...],
+ kwargs: Dict[str, Any],
+ raw: bool,
+ function: Callable[..., Any],
+ ) -> Callable[[np.ndarray, np.ndarray, np.ndarray, int], np.ndarray]:
from pandas import Series
window_func = partial(
@@ -1468,7 +1441,7 @@ def _generate_cython_apply_func(self, args, kwargs, raw, func):
args=args,
kwargs=kwargs,
raw=raw,
- func=func,
+ function=function,
)
def apply_func(values, begin, end, min_periods, raw=raw):
@@ -1589,7 +1562,7 @@ def median(self, **kwargs):
# the median function implementation
return self._apply(window_func, name="median", **kwargs)
- def std(self, ddof=1, *args, **kwargs):
+ def std(self, ddof: int = 1, *args, **kwargs):
nv.validate_window_func("std", args, kwargs)
window_func = self._get_roll_func("roll_var")
@@ -1603,7 +1576,7 @@ def zsqrt_func(values, begin, end, min_periods):
**kwargs,
)
- def var(self, ddof=1, *args, **kwargs):
+ def var(self, ddof: int = 1, *args, **kwargs):
nv.validate_window_func("var", args, kwargs)
window_func = partial(self._get_roll_func("roll_var"), ddof=ddof)
return self._apply(
@@ -1665,7 +1638,7 @@ def skew(self, **kwargs):
"""
)
- def sem(self, ddof=1, *args, **kwargs):
+ def sem(self, ddof: int = 1, *args, **kwargs):
return self.std(*args, **kwargs) / (self.count() - ddof).pow(0.5)
_shared_docs["sem"] = dedent(
@@ -1781,7 +1754,7 @@ def kurt(self, **kwargs):
"""
)
- def quantile(self, quantile, interpolation="linear", **kwargs):
+ def quantile(self, quantile: float, interpolation: str = "linear", **kwargs):
if quantile == 1.0:
window_func = self._get_roll_func("roll_max")
elif quantile == 0.0:
@@ -1789,14 +1762,10 @@ def quantile(self, quantile, interpolation="linear", **kwargs):
else:
window_func = partial(
self._get_roll_func("roll_quantile"),
- win=self._get_window(),
quantile=quantile,
interpolation=interpolation,
)
- # Pass through for groupby.rolling
- kwargs["quantile"] = quantile
- kwargs["interpolation"] = interpolation
return self._apply(window_func, name="quantile", **kwargs)
_shared_docs[
@@ -2305,7 +2274,7 @@ def _get_window_indexer(self, window: int) -> GroupbyIndexer:
GroupbyIndexer
"""
rolling_indexer: Type[BaseIndexer]
- indexer_kwargs: Optional[Dict] = None
+ indexer_kwargs: Optional[Dict[str, Any]] = None
index_array = self._on.asi8
if isinstance(self.window, BaseIndexer):
rolling_indexer = type(self.window)
| - [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
* Create clearer separation for methods belonging to `Window` vs `Rolling`
* More typing | https://api.github.com/repos/pandas-dev/pandas/pulls/37091 | 2020-10-12T23:55:29Z | 2020-10-15T16:40:28Z | 2020-10-15T16:40:28Z | 2020-10-15T23:22:48Z |
TST: Series constructor behavior is consistent for mixed float NaN and int dtype data | diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index a950ca78fc742..e20da0b891006 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -688,6 +688,13 @@ def test_constructor_coerce_float_valid(self, float_dtype):
expected = Series([1, 2, 3.5]).astype(float_dtype)
tm.assert_series_equal(s, expected)
+ def test_constructor_invalid_coerce_ints_with_float_nan(self, any_int_dtype):
+ # GH 22585
+
+ msg = "cannot convert float NaN to integer"
+ with pytest.raises(ValueError, match=msg):
+ pd.Series([1, 2, np.nan], dtype=any_int_dtype)
+
def test_constructor_dtype_no_cast(self):
# see gh-1572
s = Series([1, 2, 3])
| - [x] closes #22585
- [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/37090 | 2020-10-12T23:41:06Z | 2020-10-25T18:52:39Z | 2020-10-25T18:52:39Z | 2021-12-30T00:39:40Z |
CLN: in maybe_cast_to_integer_array assert that dtype arg is an integer dtype | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index a7379376c2f78..3f6cfe2d44650 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -1740,6 +1740,8 @@ def maybe_cast_to_integer_array(arr, dtype, copy: bool = False):
...
ValueError: Trying to coerce float values to integers
"""
+ assert is_integer_dtype(dtype)
+
try:
if not hasattr(arr, "astype"):
casted = np.array(arr, dtype=dtype, copy=copy)
@@ -1764,7 +1766,7 @@ def maybe_cast_to_integer_array(arr, dtype, copy: bool = False):
if is_unsigned_integer_dtype(dtype) and (arr < 0).any():
raise OverflowError("Trying to coerce negative values to unsigned integers")
- if is_integer_dtype(dtype) and (is_float_dtype(arr) or is_object_dtype(arr)):
+ if is_float_dtype(arr) or is_object_dtype(arr):
raise ValueError("Trying to coerce float values to integers")
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry | https://api.github.com/repos/pandas-dev/pandas/pulls/37089 | 2020-10-12T22:59:43Z | 2020-10-14T12:25:51Z | 2020-10-14T12:25:51Z | 2020-10-14T12:25:55Z |
CLN: clean Index._id | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index b3f5fb6f0291a..d180945d85d00 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -9,6 +9,7 @@
FrozenSet,
Hashable,
List,
+ NewType,
Optional,
Sequence,
Tuple,
@@ -139,7 +140,9 @@ def index_arithmetic_method(self, other):
_o_dtype = np.dtype(object)
-_Identity = object
+
+
+_Identity = NewType("_Identity", object)
def _new_Index(cls, d):
@@ -238,7 +241,7 @@ def _outer_indexer(self, left, right):
_typ = "index"
_data: Union[ExtensionArray, np.ndarray]
- _id = None
+ _id: _Identity
_name: Label = None
# MultiIndex.levels previously allowed setting the index name. We
# don't allow this anymore, and raise if it happens rather than
@@ -453,8 +456,9 @@ def _simple_new(cls, values, name: Label = None):
result._index_data = values
result._name = name
result._cache = {}
+ result._reset_identity()
- return result._reset_identity()
+ return result
@cache_readonly
def _constructor(self):
@@ -558,15 +562,16 @@ def is_(self, other) -> bool:
--------
Index.identical : Works like ``Index.is_`` but also checks metadata.
"""
- # use something other than None to be clearer
- return self._id is getattr(other, "_id", Ellipsis) and self._id is not None
+ try:
+ return self._id is other._id
+ except AttributeError:
+ return False
- def _reset_identity(self):
+ def _reset_identity(self) -> None:
"""
Initializes or resets ``_id`` attribute with new object.
"""
- self._id = _Identity()
- return self
+ self._id = _Identity(object())
def _cleanup(self):
self._engine.clear_mapping()
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 2ce4538a63d25..38a0d18ac732d 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -316,7 +316,9 @@ def __new__(
new_codes = result._verify_integrity()
result._codes = new_codes
- return result._reset_identity()
+ result._reset_identity()
+
+ return result
def _validate_codes(self, level: List, code: List):
"""
diff --git a/pandas/tests/arithmetic/test_object.py b/pandas/tests/arithmetic/test_object.py
index 02cb4f4d7a606..e0c03f28f7af5 100644
--- a/pandas/tests/arithmetic/test_object.py
+++ b/pandas/tests/arithmetic/test_object.py
@@ -343,8 +343,9 @@ def _simple_new(cls, values, name=None, dtype=None):
result._index_data = values
result._name = name
result._calls = 0
+ result._reset_identity()
- return result._reset_identity()
+ return result
def __add__(self, other):
self._calls += 1
| Minor cleanup. | https://api.github.com/repos/pandas-dev/pandas/pulls/37087 | 2020-10-12T22:15:38Z | 2020-10-14T12:26:46Z | 2020-10-14T12:26:46Z | 2020-10-14T13:30:01Z |
CI: remove xfail for numpy-dev on branch 1.1.x only | diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py
index 5f82203d92dc3..1cb539f6010fd 100644
--- a/pandas/tests/indexes/common.py
+++ b/pandas/tests/indexes/common.py
@@ -5,7 +5,6 @@
import pytest
from pandas._libs import iNaT
-from pandas.compat.numpy import _is_numpy_dev
from pandas.errors import InvalidIndexError
from pandas.core.dtypes.common import is_datetime64tz_dtype
@@ -418,7 +417,7 @@ def test_set_ops_error_cases(self, case, method, index):
with pytest.raises(TypeError, match=msg):
getattr(index, method)(case)
- def test_intersection_base(self, index, request):
+ def test_intersection_base(self, index):
if isinstance(index, CategoricalIndex):
return
@@ -435,15 +434,6 @@ def test_intersection_base(self, index, request):
# GH 10149
cases = [klass(second.values) for klass in [np.array, Series, list]]
for case in cases:
- # https://github.com/pandas-dev/pandas/issues/35481
- if (
- _is_numpy_dev
- and isinstance(case, Series)
- and isinstance(index, UInt64Index)
- ):
- mark = pytest.mark.xfail(reason="gh-35481")
- request.node.add_marker(mark)
-
result = first.intersection(case)
assert tm.equalContents(result, second)
| partially reverts pandas-dev/pandas#35537, xref https://github.com/pandas-dev/pandas/issues/35481#issuecomment-705144719 | https://api.github.com/repos/pandas-dev/pandas/pulls/37082 | 2020-10-12T15:22:22Z | 2020-10-14T19:24:03Z | 2020-10-14T19:24:03Z | 2020-10-21T12:36:19Z |
Backport PR #37046 on branch 1.1.x: Add whatsnew for #36727 | diff --git a/doc/source/whatsnew/v1.1.4.rst b/doc/source/whatsnew/v1.1.4.rst
index 3ad8d981be2c9..3cd72caa3d257 100644
--- a/doc/source/whatsnew/v1.1.4.rst
+++ b/doc/source/whatsnew/v1.1.4.rst
@@ -17,6 +17,7 @@ Fixed regressions
- Fixed regression where attempting to mutate a :class:`DateOffset` object would no longer raise an ``AttributeError`` (:issue:`36940`)
- Fixed regression where :meth:`DataFrame.agg` would fail with :exc:`TypeError` when passed positional arguments to be passed on to the aggregation function (:issue:`36948`).
- Fixed regression in :class:`RollingGroupby` with ``sort=False`` not being respected (:issue:`36889`)
+- Fixed regression in :class:`RollingGroupby` causing a segmentation fault with Index of dtype object (:issue:`36727`)
.. ---------------------------------------------------------------------------
| Backport PR #37046 on branch 1.1.x | https://api.github.com/repos/pandas-dev/pandas/pulls/37079 | 2020-10-12T14:12:53Z | 2020-10-12T15:06:23Z | 2020-10-12T15:06:23Z | 2020-10-12T15:06:28Z |
Backport PR #36937 on branch 1.1.x: BUG: GH36928 Allow dict_keys to be used as column names by read_csv | diff --git a/doc/source/whatsnew/v1.1.4.rst b/doc/source/whatsnew/v1.1.4.rst
index 3ad8d981be2c9..e2a17052726b0 100644
--- a/doc/source/whatsnew/v1.1.4.rst
+++ b/doc/source/whatsnew/v1.1.4.rst
@@ -14,6 +14,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
+- Fixed regression in :func:`read_csv` raising a ``ValueError`` when ``names`` was of type ``dict_keys`` (:issue:`36928`)
- Fixed regression where attempting to mutate a :class:`DateOffset` object would no longer raise an ``AttributeError`` (:issue:`36940`)
- Fixed regression where :meth:`DataFrame.agg` would fail with :exc:`TypeError` when passed positional arguments to be passed on to the aggregation function (:issue:`36948`).
- Fixed regression in :class:`RollingGroupby` with ``sort=False`` not being respected (:issue:`36889`)
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index a02b059967e88..6ce887710ad8f 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -413,7 +413,9 @@ def _validate_names(names):
if names is not None:
if len(names) != len(set(names)):
raise ValueError("Duplicate names are not allowed.")
- if not is_list_like(names, allow_sets=False):
+ if not (
+ is_list_like(names, allow_sets=False) or isinstance(names, abc.KeysView)
+ ):
raise ValueError("Names should be an ordered collection.")
diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py
index c6a43d22ca155..9434ad5fe8761 100644
--- a/pandas/tests/io/parser/test_common.py
+++ b/pandas/tests/io/parser/test_common.py
@@ -2212,3 +2212,15 @@ def test_read_table_delim_whitespace_non_default_sep(all_parsers):
)
with pytest.raises(ValueError, match=msg):
parser.read_table(f, delim_whitespace=True, sep=",")
+
+
+def test_dict_keys_as_names(all_parsers):
+ # GH: 36928
+ data = "1,2"
+
+ keys = {"a": int, "b": int}.keys()
+ parser = all_parsers
+
+ result = parser.read_csv(StringIO(data), names=keys)
+ expected = DataFrame({"a": [1], "b": [2]})
+ tm.assert_frame_equal(result, expected)
| Backport PR #36937 on branch 1.1.x | https://api.github.com/repos/pandas-dev/pandas/pulls/37078 | 2020-10-12T14:07:40Z | 2020-10-12T15:09:51Z | 2020-10-12T15:09:51Z | 2020-10-12T15:09:56Z |
Backport PR #37034 on branch 1.1.x (REGR: Fix casting of None to str during astype) | diff --git a/doc/source/whatsnew/v1.1.4.rst b/doc/source/whatsnew/v1.1.4.rst
index 4b93362e5fd3f..aa2c77da4ee6f 100644
--- a/doc/source/whatsnew/v1.1.4.rst
+++ b/doc/source/whatsnew/v1.1.4.rst
@@ -18,6 +18,7 @@ Fixed regressions
- Fixed regression where attempting to mutate a :class:`DateOffset` object would no longer raise an ``AttributeError`` (:issue:`36940`)
- Fixed regression where :meth:`DataFrame.agg` would fail with :exc:`TypeError` when passed positional arguments to be passed on to the aggregation function (:issue:`36948`).
- Fixed regression in :class:`RollingGroupby` with ``sort=False`` not being respected (:issue:`36889`)
+- Fixed regression in :meth:`Series.astype` converting ``None`` to ``"nan"`` when casting to string (:issue:`36904`)
- Fixed regression in :class:`RollingGroupby` causing a segmentation fault with Index of dtype object (:issue:`36727`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index a87bddef481b5..bdf294a380edc 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -922,7 +922,9 @@ def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
dtype = pandas_dtype(dtype)
if issubclass(dtype.type, str):
- return lib.ensure_string_array(arr.ravel(), skipna=skipna).reshape(arr.shape)
+ return lib.ensure_string_array(
+ arr.ravel(), skipna=skipna, convert_na_value=False
+ ).reshape(arr.shape)
elif is_datetime64_dtype(arr):
if is_object_dtype(dtype):
diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py
index 7449d8d65ef96..ad960d4c65268 100644
--- a/pandas/tests/series/methods/test_astype.py
+++ b/pandas/tests/series/methods/test_astype.py
@@ -1,7 +1,7 @@
import numpy as np
import pytest
-from pandas import Interval, Series, Timestamp, date_range
+from pandas import NA, Interval, Series, Timestamp, date_range
import pandas._testing as tm
@@ -55,3 +55,13 @@ def test_astype_from_float_to_str(self, dtype):
result = s.astype(str)
expected = Series(["0.1"])
tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "value, string_value", [(None, "None"), (np.nan, "nan"), (NA, "<NA>")],
+ )
+ def test_astype_to_str_preserves_na(self, value, string_value):
+ # https://github.com/pandas-dev/pandas/issues/36904
+ s = Series(["a", "b", value], dtype=object)
+ result = s.astype(str)
+ expected = Series(["a", "b", string_value], dtype=object)
+ tm.assert_series_equal(result, expected)
| Backport PR #37034: REGR: Fix casting of None to str during astype | https://api.github.com/repos/pandas-dev/pandas/pulls/37076 | 2020-10-12T14:00:58Z | 2020-10-12T16:47:42Z | 2020-10-12T16:47:42Z | 2020-10-12T16:47:42Z |
ENH: Add MultiIndex.dtypes | diff --git a/doc/source/reference/indexing.rst b/doc/source/reference/indexing.rst
index d3f9413dae565..8446b384b8fb8 100644
--- a/doc/source/reference/indexing.rst
+++ b/doc/source/reference/indexing.rst
@@ -290,6 +290,7 @@ MultiIndex properties
MultiIndex.codes
MultiIndex.nlevels
MultiIndex.levshape
+ MultiIndex.dtypes
MultiIndex components
~~~~~~~~~~~~~~~~~~~~~
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index b40f012f034b6..e62c7a0073dcf 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -19,7 +19,7 @@ Enhancements
Other enhancements
^^^^^^^^^^^^^^^^^^
--
+- Added :meth:`MultiIndex.dtypes` (:issue:`37062`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index a9d93f473e0e1..c9f83a41042a3 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -701,6 +701,15 @@ def array(self):
"'MultiIndex.to_numpy()' to get a NumPy array of tuples."
)
+ @cache_readonly
+ def dtypes(self) -> "Series":
+ """
+ Return the dtypes as a Series for the underlying MultiIndex
+ """
+ from pandas import Series
+
+ return Series({level.name: level.dtype for level in self.levels})
+
@property
def shape(self) -> Shape:
"""
diff --git a/pandas/tests/indexes/multi/test_get_set.py b/pandas/tests/indexes/multi/test_get_set.py
index 63dd1b575284c..83cebf90623fe 100644
--- a/pandas/tests/indexes/multi/test_get_set.py
+++ b/pandas/tests/indexes/multi/test_get_set.py
@@ -1,6 +1,8 @@
import numpy as np
import pytest
+from pandas.core.dtypes.dtypes import DatetimeTZDtype
+
import pandas as pd
from pandas import CategoricalIndex, MultiIndex
import pandas._testing as tm
@@ -27,6 +29,22 @@ def test_get_level_number_integer(idx):
idx._get_level_number("fourth")
+def test_get_dtypes():
+ # Test MultiIndex.dtypes (# Gh37062)
+ idx_multitype = MultiIndex.from_product(
+ [[1, 2, 3], ["a", "b", "c"], pd.date_range("20200101", periods=2, tz="UTC")],
+ names=["int", "string", "dt"],
+ )
+ expected = pd.Series(
+ {
+ "int": np.dtype("int64"),
+ "string": np.dtype("O"),
+ "dt": DatetimeTZDtype(tz="utc"),
+ }
+ )
+ tm.assert_series_equal(expected, idx_multitype.dtypes)
+
+
def test_get_level_number_out_of_bounds(multiindex_dataframe_random_data):
frame = multiindex_dataframe_random_data
| - [x] closes #37062
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Adds the .dtypes property to MultiIndex using the suggested implementation | https://api.github.com/repos/pandas-dev/pandas/pulls/37073 | 2020-10-12T09:42:47Z | 2020-12-11T23:04:19Z | 2020-12-11T23:04:19Z | 2020-12-11T23:04:25Z |
BUG: preserve timezone info when writing empty tz-aware series to HDF5 | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index 4b2318350b286..80f4ceccfb82c 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -476,6 +476,7 @@ I/O
- Bug in :meth:`DataFrame.to_html`, :meth:`DataFrame.to_string`, and :meth:`DataFrame.to_latex` ignoring the ``na_rep`` argument when ``float_format`` was also specified (:issue:`9046`, :issue:`13828`)
- Bug in output rendering of complex numbers showing too many trailing zeros (:issue:`36799`)
- Bug in :class:`HDFStore` threw a ``TypeError`` when exporting an empty :class:`DataFrame` with ``datetime64[ns, tz]`` dtypes with a fixed HDF5 store (:issue:`20594`)
+- Bug in :class:`HDFStore` was dropping timezone information when exporting :class:`Series` with ``datetime64[ns, tz]`` dtypes with a fixed HDF5 store (:issue:`20594`)
Plotting
^^^^^^^^
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index ffc3a4501470f..347ce6e853794 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -45,7 +45,6 @@
is_string_dtype,
is_timedelta64_dtype,
)
-from pandas.core.dtypes.generic import ABCExtensionArray
from pandas.core.dtypes.missing import array_equivalent
from pandas import (
@@ -63,6 +62,7 @@
from pandas.core.arrays import Categorical, DatetimeArray, PeriodArray
import pandas.core.common as com
from pandas.core.computation.pytables import PyTablesExpr, maybe_expression
+from pandas.core.construction import extract_array
from pandas.core.indexes.api import ensure_index
from pandas.io.common import stringify_path
@@ -2968,11 +2968,12 @@ def write_array_empty(self, key: str, value: ArrayLike):
node._v_attrs.value_type = str(value.dtype)
node._v_attrs.shape = value.shape
- def write_array(self, key: str, value: ArrayLike, items: Optional[Index] = None):
- # TODO: we only have one test that gets here, the only EA
+ def write_array(self, key: str, obj: FrameOrSeries, items: Optional[Index] = None):
+ # TODO: we only have a few tests that get here, the only EA
# that gets passed is DatetimeArray, and we never have
# both self._filters and EA
- assert isinstance(value, (np.ndarray, ABCExtensionArray)), type(value)
+
+ value = extract_array(obj, extract_numpy=True)
if key in self.group:
self._handle.remove_node(self.group, key)
@@ -3077,7 +3078,7 @@ def read(
def write(self, obj, **kwargs):
super().write(obj, **kwargs)
self.write_index("index", obj.index)
- self.write_array("values", obj.values)
+ self.write_array("values", obj)
self.attrs.name = obj.name
diff --git a/pandas/tests/io/pytables/test_timezones.py b/pandas/tests/io/pytables/test_timezones.py
index e137bc2dca48e..b18b81875dcd1 100644
--- a/pandas/tests/io/pytables/test_timezones.py
+++ b/pandas/tests/io/pytables/test_timezones.py
@@ -296,8 +296,11 @@ def test_timezones_fixed_format_frame_non_empty(setup_path):
tm.assert_frame_equal(result, df)
-@pytest.mark.parametrize("dtype", ["datetime64[ns, UTC]", "datetime64[ns, US/Eastern]"])
-def test_timezones_fixed_format_frame_empty(setup_path, dtype):
+def test_timezones_fixed_format_frame_empty(setup_path, tz_aware_fixture):
+ # GH 20594
+
+ dtype = pd.DatetimeTZDtype(tz=tz_aware_fixture)
+
with ensure_clean_store(setup_path) as store:
s = Series(dtype=dtype)
df = DataFrame({"A": s})
@@ -306,6 +309,30 @@ def test_timezones_fixed_format_frame_empty(setup_path, dtype):
tm.assert_frame_equal(result, df)
+def test_timezones_fixed_format_series_nonempty(setup_path, tz_aware_fixture):
+ # GH 20594
+
+ dtype = pd.DatetimeTZDtype(tz=tz_aware_fixture)
+
+ with ensure_clean_store(setup_path) as store:
+ s = Series([0], dtype=dtype)
+ store["s"] = s
+ result = store["s"]
+ tm.assert_series_equal(result, s)
+
+
+def test_timezones_fixed_format_series_empty(setup_path, tz_aware_fixture):
+ # GH 20594
+
+ dtype = pd.DatetimeTZDtype(tz=tz_aware_fixture)
+
+ with ensure_clean_store(setup_path) as store:
+ s = Series(dtype=dtype)
+ store["s"] = s
+ result = store["s"]
+ tm.assert_series_equal(result, s)
+
+
def test_fixed_offset_tz(setup_path):
rng = date_range("1/1/2000 00:00:00-07:00", "1/30/2000 00:00:00-07:00")
frame = DataFrame(np.random.randn(len(rng), 4), index=rng)
| - [x] closes #20594 (coupled with #37069 for empty tz-aware dataframes)
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
xref #20595 (stale PR that looked into this) | https://api.github.com/repos/pandas-dev/pandas/pulls/37072 | 2020-10-12T06:21:28Z | 2020-10-31T15:00:03Z | 2020-10-31T15:00:03Z | 2020-11-01T02:24:22Z |
BUG: preserve timezone info when writing empty tz-aware frame to HDF5 | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index 339cda4db48fb..9fc094330fb36 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -433,6 +433,7 @@ I/O
- Bug in :meth:`to_json` with ``lines=True`` and ``orient='records'`` the last line of the record is not appended with 'new line character' (:issue:`36888`)
- Bug in :meth:`read_parquet` with fixed offset timezones. String representation of timezones was not recognized (:issue:`35997`, :issue:`36004`)
- Bug in output rendering of complex numbers showing too many trailing zeros (:issue:`36799`)
+- Bug in :class:`HDFStore` threw a ``TypeError`` when exporting an empty :class:`DataFrame` with ``datetime64[ns, tz]`` dtypes with a fixed HDF5 store (:issue:`20594`)
Plotting
^^^^^^^^
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 5160773455067..ffc3a4501470f 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -3027,8 +3027,6 @@ def write_array(self, key: str, value: ArrayLike, items: Optional[Index] = None)
vlarr = self._handle.create_vlarray(self.group, key, _tables().ObjectAtom())
vlarr.append(value)
- elif empty_array:
- self.write_array_empty(key, value)
elif is_datetime64_dtype(value.dtype):
self._handle.create_array(self.group, key, value.view("i8"))
getattr(self.group, key)._v_attrs.value_type = "datetime64"
@@ -3043,6 +3041,8 @@ def write_array(self, key: str, value: ArrayLike, items: Optional[Index] = None)
elif is_timedelta64_dtype(value.dtype):
self._handle.create_array(self.group, key, value.view("i8"))
getattr(self.group, key)._v_attrs.value_type = "timedelta64"
+ elif empty_array:
+ self.write_array_empty(key, value)
else:
self._handle.create_array(self.group, key, value)
diff --git a/pandas/tests/io/pytables/test_timezones.py b/pandas/tests/io/pytables/test_timezones.py
index dc28e9543f19e..bcc5dcf9f5181 100644
--- a/pandas/tests/io/pytables/test_timezones.py
+++ b/pandas/tests/io/pytables/test_timezones.py
@@ -268,7 +268,7 @@ def test_tseries_select_index_column(setup_path):
assert rng.tz == result.dt.tz
-def test_timezones_fixed(setup_path):
+def test_timezones_fixed_format_frame_non_empty(setup_path):
with ensure_clean_store(setup_path) as store:
# index
@@ -296,6 +296,16 @@ def test_timezones_fixed(setup_path):
tm.assert_frame_equal(result, df)
+@pytest.mark.parametrize("dtype", ["datetime64[ns, UTC]", "datetime64[ns, US/Eastern]"])
+def test_timezones_fixed_format_frame_empty(setup_path, dtype):
+ with ensure_clean_store(setup_path) as store:
+ s = Series(dtype=dtype)
+ df = DataFrame({"A": s})
+ store["df"] = df
+ result = store["df"]
+ tm.assert_frame_equal(result, df)
+
+
def test_fixed_offset_tz(setup_path):
rng = date_range("1/1/2000 00:00:00-07:00", "1/30/2000 00:00:00-07:00")
frame = DataFrame(np.random.randn(len(rng), 4), index=rng)
| - [ ] partially closes #20594
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Will handle series case in follow-on | https://api.github.com/repos/pandas-dev/pandas/pulls/37069 | 2020-10-12T05:03:20Z | 2020-10-15T12:27:50Z | 2020-10-15T12:27:49Z | 2020-10-15T13:27:07Z |
CLN: remove unnecessary Categorical._validate_setitem_key | diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 8dc5e6c0ff2aa..081a363ce03c6 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -9,7 +9,7 @@
from pandas._config import get_option
-from pandas._libs import NaT, algos as libalgos, hashtable as htable, lib
+from pandas._libs import NaT, 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 cache_readonly, deprecate_kwarg
@@ -1907,32 +1907,6 @@ def _validate_setitem_value(self, value):
return self._unbox_listlike(rvalue)
- def _validate_setitem_key(self, key):
- if lib.is_integer(key):
- # set by position
- pass
-
- elif isinstance(key, tuple):
- # tuple of indexers (dataframe)
- # only allow 1 dimensional slicing, but can
- # in a 2-d case be passed (slice(None),....)
- if len(key) == 2:
- if not com.is_null_slice(key[0]):
- raise AssertionError("invalid slicing for a 1-ndim categorical")
- key = key[1]
- elif len(key) == 1:
- key = key[0]
- else:
- raise AssertionError("invalid slicing for a 1-ndim categorical")
-
- elif isinstance(key, slice):
- # slicing in Series or Categorical
- pass
-
- # else: array of True/False in Series or Categorical
-
- return super()._validate_setitem_key(key)
-
def _reverse_indexer(self) -> Dict[Hashable, np.ndarray]:
"""
Compute the inverse of a categorical, returning
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 98ae52b04cee3..61d9833a50a9f 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -2008,11 +2008,7 @@ class NumericBlock(Block):
_can_hold_na = True
-class FloatOrComplexBlock(NumericBlock):
- __slots__ = ()
-
-
-class FloatBlock(FloatOrComplexBlock):
+class FloatBlock(NumericBlock):
__slots__ = ()
is_float = True
@@ -2020,13 +2016,13 @@ def _can_hold_element(self, element: Any) -> bool:
tipo = maybe_infer_dtype_type(element)
if tipo is not None:
return issubclass(tipo.type, (np.floating, np.integer)) and not issubclass(
- tipo.type, (np.datetime64, np.timedelta64)
+ tipo.type, np.timedelta64
)
return isinstance(
element, (float, int, np.floating, np.int_)
) and not isinstance(
element,
- (bool, np.bool_, datetime, timedelta, np.datetime64, np.timedelta64),
+ (bool, np.bool_, np.timedelta64),
)
def to_native_types(
@@ -2063,7 +2059,7 @@ def to_native_types(
return self.make_block(res)
-class ComplexBlock(FloatOrComplexBlock):
+class ComplexBlock(NumericBlock):
__slots__ = ()
is_complex = True
@@ -2086,7 +2082,7 @@ def _can_hold_element(self, element: Any) -> bool:
if tipo is not None:
return (
issubclass(tipo.type, np.integer)
- and not issubclass(tipo.type, (np.datetime64, np.timedelta64))
+ and not issubclass(tipo.type, np.timedelta64)
and self.dtype.itemsize >= tipo.itemsize
)
# We have not inferred an integer from the dtype
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
and some unrelated cleanup in internals | https://api.github.com/repos/pandas-dev/pandas/pulls/37068 | 2020-10-12T03:45:43Z | 2020-10-12T23:27:50Z | 2020-10-12T23:27:50Z | 2020-10-13T00:43:48Z |
TYP: Misc groupby typing | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 86b6c4a6cf575..3079bb0b79b33 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -5417,7 +5417,7 @@ def __setattr__(self, name: str, value) -> None:
)
object.__setattr__(self, name, value)
- def _dir_additions(self):
+ def _dir_additions(self) -> Set[str]:
"""
add the string-like attributes from the info_axis.
If info_axis is a MultiIndex, it's first level values are used.
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py
index af3aa5d121391..9c78166ce0480 100644
--- a/pandas/core/groupby/generic.py
+++ b/pandas/core/groupby/generic.py
@@ -30,7 +30,7 @@
import numpy as np
from pandas._libs import lib, reduction as libreduction
-from pandas._typing import ArrayLike, FrameOrSeries, FrameOrSeriesUnion
+from pandas._typing import ArrayLike, FrameOrSeries, FrameOrSeriesUnion, Label
from pandas.util._decorators import Appender, Substitution, doc
from pandas.core.dtypes.cast import (
@@ -1131,7 +1131,7 @@ def _aggregate_frame(self, func, *args, **kwargs) -> DataFrame:
axis = self.axis
obj = self._obj_with_exclusions
- result: Dict[Union[int, str], Union[NDFrame, np.ndarray]] = {}
+ result: Dict[Label, Union[NDFrame, np.ndarray]] = {}
if axis != obj._info_axis_number:
for name, data in self:
fres = func(data, *args, **kwargs)
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index c758844da3a2b..4ab40e25db84e 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -20,6 +20,7 @@ class providing the base-class of operations.
Generic,
Hashable,
Iterable,
+ Iterator,
List,
Mapping,
Optional,
@@ -465,7 +466,7 @@ def f(self):
@contextmanager
-def group_selection_context(groupby: "BaseGroupBy"):
+def group_selection_context(groupby: "BaseGroupBy") -> Iterator["BaseGroupBy"]:
"""
Set / reset the group_selection_context.
"""
@@ -486,7 +487,7 @@ def group_selection_context(groupby: "BaseGroupBy"):
class BaseGroupBy(PandasObject, SelectionMixin, Generic[FrameOrSeries]):
- _group_selection = None
+ _group_selection: Optional[IndexLabel] = None
_apply_allowlist: FrozenSet[str] = frozenset()
def __init__(
@@ -570,7 +571,7 @@ def groups(self) -> Dict[Hashable, np.ndarray]:
return self.grouper.groups
@property
- def ngroups(self):
+ def ngroups(self) -> int:
self._assure_grouper()
return self.grouper.ngroups
@@ -649,7 +650,7 @@ def _selected_obj(self):
else:
return self.obj[self._selection]
- def _reset_group_selection(self):
+ def _reset_group_selection(self) -> None:
"""
Clear group based selection.
@@ -661,7 +662,7 @@ def _reset_group_selection(self):
self._group_selection = None
self._reset_cache("_selected_obj")
- def _set_group_selection(self):
+ def _set_group_selection(self) -> None:
"""
Create group based selection.
@@ -686,7 +687,9 @@ def _set_group_selection(self):
self._group_selection = ax.difference(Index(groupers), sort=False).tolist()
self._reset_cache("_selected_obj")
- def _set_result_index_ordered(self, result):
+ def _set_result_index_ordered(
+ self, result: "OutputFrameOrSeries"
+ ) -> "OutputFrameOrSeries":
# set the result index on the passed values object and
# return the new object, xref 8046
@@ -700,7 +703,7 @@ def _set_result_index_ordered(self, result):
result.set_axis(self.obj._get_axis(self.axis), axis=self.axis, inplace=True)
return result
- def _dir_additions(self):
+ def _dir_additions(self) -> Set[str]:
return self.obj._dir_additions() | self._apply_allowlist
def __getattr__(self, attr: str):
@@ -818,7 +821,7 @@ def get_group(self, name, obj=None):
return obj._take_with_is_copy(inds, axis=self.axis)
- def __iter__(self):
+ def __iter__(self) -> Iterator[Tuple[Label, FrameOrSeries]]:
"""
Groupby iterator.
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 1c18ef891b8c5..bca71b5c9646b 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -7,7 +7,17 @@
"""
import collections
-from typing import Dict, Generic, Hashable, List, Optional, Sequence, Tuple, Type
+from typing import (
+ Dict,
+ Generic,
+ Hashable,
+ Iterator,
+ List,
+ Optional,
+ Sequence,
+ Tuple,
+ Type,
+)
import numpy as np
@@ -116,7 +126,9 @@ def __iter__(self):
def nkeys(self) -> int:
return len(self.groupings)
- def get_iterator(self, data: FrameOrSeries, axis: int = 0):
+ def get_iterator(
+ self, data: FrameOrSeries, axis: int = 0
+ ) -> Iterator[Tuple[Label, FrameOrSeries]]:
"""
Groupby iterator
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/37066 | 2020-10-12T03:08:20Z | 2020-10-12T13:44:21Z | 2020-10-12T13:44:21Z | 2020-12-06T14:04:47Z |
REF: define NDFrame inplace ops non-dynamically | diff --git a/pandas/core/arraylike.py b/pandas/core/arraylike.py
index 553649212aa5f..da366c9abf0a4 100644
--- a/pandas/core/arraylike.py
+++ b/pandas/core/arraylike.py
@@ -6,8 +6,6 @@
"""
import operator
-from pandas.errors import AbstractMethodError
-
from pandas.core.ops import roperator
from pandas.core.ops.common import unpack_zerodim_and_defer
@@ -17,7 +15,7 @@ class OpsMixin:
# Comparisons
def _cmp_method(self, other, op):
- raise AbstractMethodError(self)
+ return NotImplemented
@unpack_zerodim_and_defer("__eq__")
def __eq__(self, other):
@@ -47,7 +45,7 @@ def __ge__(self, other):
# Logical Methods
def _logical_method(self, other, op):
- raise AbstractMethodError(self)
+ return NotImplemented
@unpack_zerodim_and_defer("__and__")
def __and__(self, other):
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index b1633cd6d8975..ba2f11c87369f 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -9366,7 +9366,6 @@ def _AXIS_NAMES(self) -> Dict[int, str]:
DataFrame._add_numeric_operations()
ops.add_flex_arithmetic_methods(DataFrame)
-ops.add_special_arithmetic_methods(DataFrame)
def _from_nested_dict(data) -> collections.defaultdict:
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 86b6c4a6cf575..aa688788c6838 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -9808,6 +9808,7 @@ def _tz_localize(ax, tz, ambiguous, nonexistent):
# ----------------------------------------------------------------------
# Numeric Methods
+
def abs(self: FrameOrSeries) -> FrameOrSeries:
"""
Return a Series/DataFrame with absolute numeric value of each element.
@@ -11097,6 +11098,55 @@ def ewm(
times=times,
)
+ # ----------------------------------------------------------------------
+ # Arithmetic Methods
+
+ def _inplace_method(self, other, op):
+ """
+ Wrap arithmetic method to operate inplace.
+ """
+ result = op(self, other)
+
+ # Delete cacher
+ self._reset_cacher()
+
+ # this makes sure that we are aligned like the input
+ # we are updating inplace so we want to ignore is_copy
+ self._update_inplace(
+ result.reindex_like(self, copy=False), verify_is_copy=False
+ )
+ return self
+
+ def __iadd__(self, other):
+ return self._inplace_method(other, type(self).__add__)
+
+ def __isub__(self, other):
+ return self._inplace_method(other, type(self).__sub__)
+
+ def __imul__(self, other):
+ return self._inplace_method(other, type(self).__mul__)
+
+ def __itruediv__(self, other):
+ return self._inplace_method(other, type(self).__truediv__)
+
+ def __ifloordiv__(self, other):
+ return self._inplace_method(other, type(self).__floordiv__)
+
+ def __imod__(self, other):
+ return self._inplace_method(other, type(self).__mod__)
+
+ def __ipow__(self, other):
+ return self._inplace_method(other, type(self).__pow__)
+
+ def __iand__(self, other):
+ return self._inplace_method(other, type(self).__and__)
+
+ def __ior__(self, other):
+ return self._inplace_method(other, type(self).__or__)
+
+ def __ixor__(self, other):
+ return self._inplace_method(other, type(self).__xor__)
+
# ----------------------------------------------------------------------
# Misc methods
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py
index 87da8f8fa146c..69b5abe65057a 100644
--- a/pandas/core/ops/__init__.py
+++ b/pandas/core/ops/__init__.py
@@ -33,10 +33,7 @@
)
from pandas.core.ops.invalid import invalid_comparison # noqa:F401
from pandas.core.ops.mask_ops import kleene_and, kleene_or, kleene_xor # noqa: F401
-from pandas.core.ops.methods import ( # noqa:F401
- add_flex_arithmetic_methods,
- add_special_arithmetic_methods,
-)
+from pandas.core.ops.methods import add_flex_arithmetic_methods # noqa:F401
from pandas.core.ops.roperator import ( # noqa:F401
radd,
rand_,
diff --git a/pandas/core/ops/methods.py b/pandas/core/ops/methods.py
index c05f457f1e4f5..96a691da38b99 100644
--- a/pandas/core/ops/methods.py
+++ b/pandas/core/ops/methods.py
@@ -49,62 +49,6 @@ def _get_method_wrappers(cls):
return arith_flex, comp_flex
-def add_special_arithmetic_methods(cls):
- """
- Adds the full suite of special arithmetic methods (``__add__``,
- ``__sub__``, etc.) to the class.
-
- Parameters
- ----------
- cls : class
- special methods will be defined and pinned to this class
- """
- new_methods = {}
-
- def _wrap_inplace_method(method):
- """
- return an inplace wrapper for this method
- """
-
- def f(self, other):
- result = method(self, other)
- # Delete cacher
- self._reset_cacher()
- # this makes sure that we are aligned like the input
- # we are updating inplace so we want to ignore is_copy
- self._update_inplace(
- result.reindex_like(self, copy=False), verify_is_copy=False
- )
-
- return self
-
- name = method.__name__.strip("__")
- f.__name__ = f"__i{name}__"
- return f
-
- # wrap methods that we get from OpsMixin
- new_methods.update(
- dict(
- __iadd__=_wrap_inplace_method(cls.__add__),
- __isub__=_wrap_inplace_method(cls.__sub__),
- __imul__=_wrap_inplace_method(cls.__mul__),
- __itruediv__=_wrap_inplace_method(cls.__truediv__),
- __ifloordiv__=_wrap_inplace_method(cls.__floordiv__),
- __imod__=_wrap_inplace_method(cls.__mod__),
- __ipow__=_wrap_inplace_method(cls.__pow__),
- )
- )
- new_methods.update(
- dict(
- __iand__=_wrap_inplace_method(cls.__and__),
- __ior__=_wrap_inplace_method(cls.__or__),
- __ixor__=_wrap_inplace_method(cls.__xor__),
- )
- )
-
- _add_methods(cls, new_methods=new_methods)
-
-
def add_flex_arithmetic_methods(cls):
"""
Adds the full suite of flex arithmetic methods (``pow``, ``mul``, ``add``)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index bddd400ff9449..fb684da20bac8 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -5005,17 +5005,8 @@ def _arith_method(self, other, op):
return self._construct_result(result, name=res_name)
- def __div__(self, other):
- # Alias for backward compat
- return self.__truediv__(other)
-
- def __rdiv__(self, other):
- # Alias for backward compat
- return self.__rtruediv__(other)
-
Series._add_numeric_operations()
# Add arithmetic!
ops.add_flex_arithmetic_methods(Series)
-ops.add_special_arithmetic_methods(Series)
| - [ ] 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/37065 | 2020-10-12T02:17:39Z | 2020-10-12T15:19:51Z | 2020-10-12T15:19:51Z | 2020-10-12T15:30:39Z |
PERF: ExpandingGroupby | diff --git a/asv_bench/benchmarks/rolling.py b/asv_bench/benchmarks/rolling.py
index f0dd908f81043..226b225b47591 100644
--- a/asv_bench/benchmarks/rolling.py
+++ b/asv_bench/benchmarks/rolling.py
@@ -76,12 +76,21 @@ class ExpandingMethods:
def setup(self, constructor, dtype, method):
N = 10 ** 5
+ N_groupby = 100
arr = (100 * np.random.random(N)).astype(dtype)
self.expanding = getattr(pd, constructor)(arr).expanding()
+ self.expanding_groupby = (
+ pd.DataFrame({"A": arr[:N_groupby], "B": range(N_groupby)})
+ .groupby("B")
+ .expanding()
+ )
def time_expanding(self, constructor, dtype, method):
getattr(self.expanding, method)()
+ def time_expanding_groupby(self, constructor, dtype, method):
+ getattr(self.expanding_groupby, method)()
+
class EWMMethods:
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index d08e8e009811a..9e17c940591fd 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -313,6 +313,7 @@ Performance improvements
avoiding creating these again, if created on either. This can speed up operations that depend on creating copies of existing indexes (:issue:`36840`)
- Performance improvement in :meth:`RollingGroupby.count` (:issue:`35625`)
- Small performance decrease to :meth:`Rolling.min` and :meth:`Rolling.max` for fixed windows (:issue:`36567`)
+- Performance improvement in :class:`ExpandingGroupby` (:issue:`37064`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx
index 937f7d8df7728..bba8b4b2432a9 100644
--- a/pandas/_libs/window/aggregations.pyx
+++ b/pandas/_libs/window/aggregations.pyx
@@ -302,7 +302,7 @@ cdef inline float64_t calc_var(int64_t minp, int ddof, float64_t nobs,
result = ssqdm_x / (nobs - <float64_t>ddof)
# Fix for numerical imprecision.
# Can be result < 0 once Kahan Summation is implemented
- if result < 1e-15:
+ if result < 1e-14:
result = 0
else:
result = NaN
diff --git a/pandas/core/window/common.py b/pandas/core/window/common.py
index aa71c44f75ead..938f1846230cb 100644
--- a/pandas/core/window/common.py
+++ b/pandas/core/window/common.py
@@ -1,13 +1,11 @@
"""Common utility functions for rolling operations"""
from collections import defaultdict
-from typing import Callable, Optional
import warnings
import numpy as np
from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries
-from pandas.core.groupby.base import GotItemMixin
from pandas.core.indexes.api import MultiIndex
from pandas.core.shared_docs import _shared_docs
@@ -27,69 +25,6 @@
"""
-def _dispatch(name: str, *args, **kwargs):
- """
- Dispatch to apply.
- """
-
- def outer(self, *args, **kwargs):
- def f(x):
- x = self._shallow_copy(x, groupby=self._groupby)
- return getattr(x, name)(*args, **kwargs)
-
- return self._groupby.apply(f)
-
- outer.__name__ = name
- return outer
-
-
-class WindowGroupByMixin(GotItemMixin):
- """
- Provide the groupby facilities.
- """
-
- def __init__(self, obj, *args, **kwargs):
- kwargs.pop("parent", None)
- groupby = kwargs.pop("groupby", None)
- if groupby is None:
- groupby, obj = obj, obj._selected_obj
- self._groupby = groupby
- self._groupby.mutated = True
- self._groupby.grouper.mutated = True
- super().__init__(obj, *args, **kwargs)
-
- corr = _dispatch("corr", other=None, pairwise=None)
- cov = _dispatch("cov", other=None, pairwise=None)
-
- def _apply(
- self,
- func: Callable,
- require_min_periods: int = 0,
- floor: int = 1,
- is_weighted: bool = False,
- name: Optional[str] = None,
- use_numba_cache: bool = False,
- **kwargs,
- ):
- """
- Dispatch to apply; we are stripping all of the _apply kwargs and
- performing the original function call on the grouped object.
- """
- kwargs.pop("floor", None)
- kwargs.pop("original_func", None)
-
- # TODO: can we de-duplicate with _dispatch?
- def f(x, name=name, *args):
- x = self._shallow_copy(x)
-
- if isinstance(name, str):
- return getattr(x, name)(*args, **kwargs)
-
- return x.apply(name, *args, **kwargs)
-
- return self._groupby.apply(f)
-
-
def flex_binary_moment(arg1, arg2, f, pairwise=False):
if not (
diff --git a/pandas/core/window/expanding.py b/pandas/core/window/expanding.py
index 319944fd48eae..c75e81fc8335a 100644
--- a/pandas/core/window/expanding.py
+++ b/pandas/core/window/expanding.py
@@ -4,8 +4,9 @@
from pandas.compat.numpy import function as nv
from pandas.util._decorators import Appender, Substitution, doc
-from pandas.core.window.common import WindowGroupByMixin, _doc_template, _shared_docs
-from pandas.core.window.rolling import RollingAndExpandingMixin
+from pandas.core.window.common import _doc_template, _shared_docs
+from pandas.core.window.indexers import ExpandingIndexer, GroupbyIndexer
+from pandas.core.window.rolling import BaseWindowGroupby, RollingAndExpandingMixin
class Expanding(RollingAndExpandingMixin):
@@ -248,11 +249,26 @@ def corr(self, other=None, pairwise=None, **kwargs):
return super().corr(other=other, pairwise=pairwise, **kwargs)
-class ExpandingGroupby(WindowGroupByMixin, Expanding):
+class ExpandingGroupby(BaseWindowGroupby, Expanding):
"""
Provide a expanding groupby implementation.
"""
- @property
- def _constructor(self):
- return Expanding
+ def _get_window_indexer(self, window: int) -> GroupbyIndexer:
+ """
+ Return an indexer class that will compute the window start and end bounds
+
+ Parameters
+ ----------
+ window : int
+ window size for FixedWindowIndexer (unused)
+
+ Returns
+ -------
+ GroupbyIndexer
+ """
+ window_indexer = GroupbyIndexer(
+ groupby_indicies=self._groupby.indices,
+ window_indexer=ExpandingIndexer,
+ )
+ return window_indexer
diff --git a/pandas/core/window/indexers.py b/pandas/core/window/indexers.py
index f2bc01438097c..71e77f97d8797 100644
--- a/pandas/core/window/indexers.py
+++ b/pandas/core/window/indexers.py
@@ -259,26 +259,38 @@ def get_window_bounds(
return start, end
-class GroupbyRollingIndexer(BaseIndexer):
+class GroupbyIndexer(BaseIndexer):
"""Calculate bounds to compute groupby rolling, mimicking df.groupby().rolling()"""
def __init__(
self,
- index_array: Optional[np.ndarray],
- window_size: int,
- groupby_indicies: Dict,
- rolling_indexer: Type[BaseIndexer],
- indexer_kwargs: Optional[Dict],
+ index_array: Optional[np.ndarray] = None,
+ window_size: int = 0,
+ groupby_indicies: Optional[Dict] = None,
+ window_indexer: Type[BaseIndexer] = BaseIndexer,
+ indexer_kwargs: Optional[Dict] = None,
**kwargs,
):
"""
Parameters
----------
+ index_array : np.ndarray or None
+ np.ndarray of the index of the original object that we are performing
+ a chained groupby operation over. This index has been pre-sorted relative to
+ the groups
+ window_size : int
+ window size during the windowing operation
+ groupby_indicies : dict or None
+ dict of {group label: [positional index of rows belonging to the group]}
+ window_indexer : BaseIndexer
+ BaseIndexer class determining the start and end bounds of each group
+ indexer_kwargs : dict or None
+ Custom kwargs to be passed to window_indexer
**kwargs :
keyword arguments that will be available when get_window_bounds is called
"""
- self.groupby_indicies = groupby_indicies
- self.rolling_indexer = rolling_indexer
+ self.groupby_indicies = groupby_indicies or {}
+ self.window_indexer = window_indexer
self.indexer_kwargs = indexer_kwargs or {}
super().__init__(
index_array, self.indexer_kwargs.pop("window_size", window_size), **kwargs
@@ -303,7 +315,7 @@ def get_window_bounds(
index_array = self.index_array.take(ensure_platform_int(indices))
else:
index_array = self.index_array
- indexer = self.rolling_indexer(
+ indexer = self.window_indexer(
index_array=index_array,
window_size=self.window_size,
**self.indexer_kwargs,
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index 9e829ef774d42..5a3996c94957a 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -51,11 +51,10 @@
from pandas.core.base import DataError, SelectionMixin
import pandas.core.common as com
from pandas.core.construction import extract_array
-from pandas.core.groupby.base import ShallowMixin
+from pandas.core.groupby.base import GotItemMixin, ShallowMixin
from pandas.core.indexes.api import Index, MultiIndex
from pandas.core.util.numba_ import NUMBA_FUNC_CACHE, maybe_use_numba
from pandas.core.window.common import (
- WindowGroupByMixin,
_doc_template,
_shared_docs,
flex_binary_moment,
@@ -64,7 +63,7 @@
from pandas.core.window.indexers import (
BaseIndexer,
FixedWindowIndexer,
- GroupbyRollingIndexer,
+ GroupbyIndexer,
VariableWindowIndexer,
)
from pandas.core.window.numba_ import generate_numba_apply_func
@@ -855,6 +854,111 @@ def aggregate(self, func, *args, **kwargs):
)
+def _dispatch(name: str, *args, **kwargs):
+ """
+ Dispatch to groupby apply.
+ """
+
+ def outer(self, *args, **kwargs):
+ def f(x):
+ x = self._shallow_copy(x, groupby=self._groupby)
+ return getattr(x, name)(*args, **kwargs)
+
+ return self._groupby.apply(f)
+
+ outer.__name__ = name
+ return outer
+
+
+class BaseWindowGroupby(GotItemMixin, BaseWindow):
+ """
+ Provide the groupby windowing facilities.
+ """
+
+ def __init__(self, obj, *args, **kwargs):
+ kwargs.pop("parent", None)
+ groupby = kwargs.pop("groupby", None)
+ if groupby is None:
+ groupby, obj = obj, obj._selected_obj
+ self._groupby = groupby
+ self._groupby.mutated = True
+ self._groupby.grouper.mutated = True
+ super().__init__(obj, *args, **kwargs)
+
+ corr = _dispatch("corr", other=None, pairwise=None)
+ cov = _dispatch("cov", other=None, pairwise=None)
+
+ def _apply(
+ self,
+ func: Callable,
+ require_min_periods: int = 0,
+ floor: int = 1,
+ is_weighted: bool = False,
+ name: Optional[str] = None,
+ use_numba_cache: bool = False,
+ **kwargs,
+ ):
+ result = super()._apply(
+ func,
+ require_min_periods,
+ floor,
+ is_weighted,
+ name,
+ use_numba_cache,
+ **kwargs,
+ )
+ # Compose MultiIndex result from grouping levels then rolling level
+ # Aggregate the MultiIndex data as tuples then the level names
+ grouped_object_index = self.obj.index
+ grouped_index_name = [*grouped_object_index.names]
+ groupby_keys = [grouping.name for grouping in self._groupby.grouper._groupings]
+ result_index_names = groupby_keys + grouped_index_name
+
+ result_index_data = []
+ for key, values in self._groupby.grouper.indices.items():
+ for value in values:
+ data = [
+ *com.maybe_make_list(key),
+ *com.maybe_make_list(grouped_object_index[value]),
+ ]
+ result_index_data.append(tuple(data))
+
+ result_index = MultiIndex.from_tuples(
+ result_index_data, names=result_index_names
+ )
+ result.index = result_index
+ return result
+
+ def _create_data(self, obj: FrameOrSeries) -> FrameOrSeries:
+ """
+ Split data into blocks & return conformed data.
+ """
+ # Ensure the object we're rolling over is monotonically sorted relative
+ # to the groups
+ # GH 36197
+ if not obj.empty:
+ groupby_order = np.concatenate(
+ list(self._groupby.grouper.indices.values())
+ ).astype(np.int64)
+ obj = obj.take(groupby_order)
+ return super()._create_data(obj)
+
+ def _gotitem(self, key, ndim, subset=None):
+ # we are setting the index on the actual object
+ # here so our index is carried through to the selected obj
+ # when we do the splitting for the groupby
+ if self.on is not None:
+ self.obj = self.obj.set_index(self._on)
+ self.on = None
+ return super()._gotitem(key, ndim, subset=subset)
+
+ def _validate_monotonic(self):
+ """
+ Validate that "on" is monotonic; already validated at a higher level.
+ """
+ pass
+
+
class Window(BaseWindow):
"""
Provide rolling window calculations.
@@ -1332,8 +1436,7 @@ def apply(
args = ()
if kwargs is None:
kwargs = {}
- kwargs.pop("_level", None)
- kwargs.pop("floor", None)
+
if not is_bool(raw):
raise ValueError("raw parameter must be `True` or `False`")
@@ -1348,13 +1451,10 @@ def apply(
else:
raise ValueError("engine must be either 'numba' or 'cython'")
- # name=func & raw=raw for WindowGroupByMixin._apply
return self._apply(
apply_func,
floor=0,
- name=func,
use_numba_cache=maybe_use_numba(engine),
- raw=raw,
original_func=func,
args=args,
kwargs=kwargs,
@@ -1381,7 +1481,6 @@ def apply_func(values, begin, end, min_periods, raw=raw):
def sum(self, *args, **kwargs):
nv.validate_window_func("sum", args, kwargs)
window_func = self._get_roll_func("roll_sum")
- kwargs.pop("floor", None)
return self._apply(window_func, floor=0, name="sum", **kwargs)
_shared_docs["max"] = dedent(
@@ -1492,31 +1591,25 @@ def median(self, **kwargs):
def std(self, ddof=1, *args, **kwargs):
nv.validate_window_func("std", args, kwargs)
- kwargs.pop("require_min_periods", None)
window_func = self._get_roll_func("roll_var")
def zsqrt_func(values, begin, end, min_periods):
return zsqrt(window_func(values, begin, end, min_periods, ddof=ddof))
- # ddof passed again for compat with groupby.rolling
return self._apply(
zsqrt_func,
require_min_periods=1,
name="std",
- ddof=ddof,
**kwargs,
)
def var(self, ddof=1, *args, **kwargs):
nv.validate_window_func("var", args, kwargs)
- kwargs.pop("require_min_periods", None)
window_func = partial(self._get_roll_func("roll_var"), ddof=ddof)
- # ddof passed again for compat with groupby.rolling
return self._apply(
window_func,
require_min_periods=1,
name="var",
- ddof=ddof,
**kwargs,
)
@@ -1533,7 +1626,6 @@ def var(self, ddof=1, *args, **kwargs):
def skew(self, **kwargs):
window_func = self._get_roll_func("roll_skew")
- kwargs.pop("require_min_periods", None)
return self._apply(
window_func,
require_min_periods=3,
@@ -1575,7 +1667,6 @@ def skew(self, **kwargs):
def kurt(self, **kwargs):
window_func = self._get_roll_func("roll_kurt")
- kwargs.pop("require_min_periods", None)
return self._apply(
window_func,
require_min_periods=4,
@@ -2134,73 +2225,12 @@ def corr(self, other=None, pairwise=None, **kwargs):
Rolling.__doc__ = Window.__doc__
-class RollingGroupby(WindowGroupByMixin, Rolling):
+class RollingGroupby(BaseWindowGroupby, Rolling):
"""
Provide a rolling groupby implementation.
"""
- def _apply(
- self,
- func: Callable,
- require_min_periods: int = 0,
- floor: int = 1,
- is_weighted: bool = False,
- name: Optional[str] = None,
- use_numba_cache: bool = False,
- **kwargs,
- ):
- result = Rolling._apply(
- self,
- func,
- require_min_periods,
- floor,
- is_weighted,
- name,
- use_numba_cache,
- **kwargs,
- )
- # Cannot use _wrap_outputs because we calculate the result all at once
- # Compose MultiIndex result from grouping levels then rolling level
- # Aggregate the MultiIndex data as tuples then the level names
- grouped_object_index = self.obj.index
- grouped_index_name = [*grouped_object_index.names]
- groupby_keys = [grouping.name for grouping in self._groupby.grouper._groupings]
- result_index_names = groupby_keys + grouped_index_name
-
- result_index_data = []
- for key, values in self._groupby.grouper.indices.items():
- for value in values:
- data = [
- *com.maybe_make_list(key),
- *com.maybe_make_list(grouped_object_index[value]),
- ]
- result_index_data.append(tuple(data))
-
- result_index = MultiIndex.from_tuples(
- result_index_data, names=result_index_names
- )
- result.index = result_index
- return result
-
- @property
- def _constructor(self):
- return Rolling
-
- def _create_data(self, obj: FrameOrSeries) -> FrameOrSeries:
- """
- Split data into blocks & return conformed data.
- """
- # Ensure the object we're rolling over is monotonically sorted relative
- # to the groups
- # GH 36197
- if not obj.empty:
- groupby_order = np.concatenate(
- list(self._groupby.grouper.indices.values())
- ).astype(np.int64)
- obj = obj.take(groupby_order)
- return super()._create_data(obj)
-
- def _get_window_indexer(self, window: int) -> GroupbyRollingIndexer:
+ def _get_window_indexer(self, window: int) -> GroupbyIndexer:
"""
Return an indexer class that will compute the window start and end bounds
@@ -2211,7 +2241,7 @@ def _get_window_indexer(self, window: int) -> GroupbyRollingIndexer:
Returns
-------
- GroupbyRollingIndexer
+ GroupbyIndexer
"""
rolling_indexer: Type[BaseIndexer]
indexer_kwargs: Optional[Dict] = None
@@ -2227,29 +2257,11 @@ def _get_window_indexer(self, window: int) -> GroupbyRollingIndexer:
else:
rolling_indexer = FixedWindowIndexer
index_array = None
- window_indexer = GroupbyRollingIndexer(
+ window_indexer = GroupbyIndexer(
index_array=index_array,
window_size=window,
groupby_indicies=self._groupby.indices,
- rolling_indexer=rolling_indexer,
+ window_indexer=rolling_indexer,
indexer_kwargs=indexer_kwargs,
)
return window_indexer
-
- def _gotitem(self, key, ndim, subset=None):
- # we are setting the index on the actual object
- # here so our index is carried thru to the selected obj
- # when we do the splitting for the groupby
- if self.on is not None:
- self.obj = self.obj.set_index(self._on)
- self.on = None
- return super()._gotitem(key, ndim, subset=subset)
-
- def _validate_monotonic(self):
- """
- Validate that on is monotonic;
- we don't care for groupby.rolling
- because we have already validated at a higher
- level.
- """
- pass
| - [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
```
before after ratio
[89cc5bf9] [6af880e7]
<master> <feature/groupby_expanding_indexer>
- 45.5±0.6ms 3.78±0.04ms 0.08 rolling.ExpandingMethods.time_expanding_groupby('Series', 'int', 'max')
- 46.5±0.5ms 3.86±0.06ms 0.08 rolling.ExpandingMethods.time_expanding_groupby('Series', 'int', 'mean')
- 45.4±0.4ms 3.74±0.05ms 0.08 rolling.ExpandingMethods.time_expanding_groupby('DataFrame', 'int', 'min')
- 45.5±0.4ms 3.73±0.06ms 0.08 rolling.ExpandingMethods.time_expanding_groupby('Series', 'int', 'min')
- 46.6±0.3ms 3.80±0.01ms 0.08 rolling.ExpandingMethods.time_expanding_groupby('Series', 'int', 'median')
- 46.7±1ms 3.77±0.05ms 0.08 rolling.ExpandingMethods.time_expanding_groupby('DataFrame', 'int', 'max')
- 46.3±0.6ms 3.73±0.02ms 0.08 rolling.ExpandingMethods.time_expanding_groupby('DataFrame', 'int', 'sum')
- 46.8±0.3ms 3.76±0.1ms 0.08 rolling.ExpandingMethods.time_expanding_groupby('Series', 'int', 'sum')
- 46.7±0.5ms 3.75±0.02ms 0.08 rolling.ExpandingMethods.time_expanding_groupby('DataFrame', 'int', 'mean')
- 47.2±0.3ms 3.78±0.04ms 0.08 rolling.ExpandingMethods.time_expanding_groupby('DataFrame', 'int', 'median')
- 51.2±0.7ms 3.89±0.1ms 0.08 rolling.ExpandingMethods.time_expanding_groupby('Series', 'int', 'std')
- 51.3±0.3ms 3.78±0.02ms 0.07 rolling.ExpandingMethods.time_expanding_groupby('DataFrame', 'int', 'std')
- 62.6±0.6ms 3.98±0.02ms 0.06 rolling.ExpandingMethods.time_expanding_groupby('Series', 'int', 'count')
- 62.2±0.7ms 3.91±0.03ms 0.06 rolling.ExpandingMethods.time_expanding_groupby('DataFrame', 'int', 'count')
- 64.3±0.7ms 3.98±0.05ms 0.06 rolling.ExpandingMethods.time_expanding_groupby('Series', 'float', 'sum')
- 63.5±0.7ms 3.92±0.01ms 0.06 rolling.ExpandingMethods.time_expanding_groupby('DataFrame', 'float', 'max')
- 63.6±0.6ms 3.91±0.03ms 0.06 rolling.ExpandingMethods.time_expanding_groupby('Series', 'float', 'min')
- 63.2±0.7ms 3.86±0.02ms 0.06 rolling.ExpandingMethods.time_expanding_groupby('DataFrame', 'float', 'min')
- 64.2±1ms 3.89±0.04ms 0.06 rolling.ExpandingMethods.time_expanding_groupby('Series', 'float', 'max')
- 64.8±0.8ms 3.91±0.06ms 0.06 rolling.ExpandingMethods.time_expanding_groupby('DataFrame', 'float', 'sum')
- 65.2±0.6ms 3.92±0.05ms 0.06 rolling.ExpandingMethods.time_expanding_groupby('DataFrame', 'float', 'mean')
- 65.2±0.9ms 3.90±0.05ms 0.06 rolling.ExpandingMethods.time_expanding_groupby('Series', 'float', 'median')
- 65.5±0.5ms 3.91±0.02ms 0.06 rolling.ExpandingMethods.time_expanding_groupby('DataFrame', 'float', 'median')
- 65.3±0.2ms 3.86±0.01ms 0.06 rolling.ExpandingMethods.time_expanding_groupby('Series', 'float', 'mean')
- 69.4±0.8ms 4.01±0.07ms 0.06 rolling.ExpandingMethods.time_expanding_groupby('Series', 'float', 'std')
- 69.8±0.6ms 3.93±0.01ms 0.06 rolling.ExpandingMethods.time_expanding_groupby('DataFrame', 'float', 'std')
- 80.1±0.2ms 4.24±0.1ms 0.05 rolling.ExpandingMethods.time_expanding_groupby('DataFrame', 'float', 'count')
- 80.5±0.9ms 4.14±0.02ms 0.05 rolling.ExpandingMethods.time_expanding_groupby('Series', 'float', 'count')
SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY.
PERFORMANCE INCREASED.
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/37064 | 2020-10-12T00:51:38Z | 2020-10-12T16:57:08Z | 2020-10-12T16:57:08Z | 2020-10-12T17:08:12Z |
TST: Verify functioning of histtype argument (GH23992) | diff --git a/pandas/tests/plotting/common.py b/pandas/tests/plotting/common.py
index c04b70f3c2953..82a62c4588b94 100644
--- a/pandas/tests/plotting/common.py
+++ b/pandas/tests/plotting/common.py
@@ -1,4 +1,5 @@
import os
+from typing import TYPE_CHECKING, Sequence, Union
import warnings
import numpy as np
@@ -12,6 +13,9 @@
from pandas import DataFrame, Series, to_datetime
import pandas._testing as tm
+if TYPE_CHECKING:
+ from matplotlib.axes import Axes
+
@td.skip_if_no_mpl
class TestPlotBase:
@@ -172,6 +176,24 @@ def _check_visible(self, collections, visible=True):
for patch in collections:
assert patch.get_visible() == visible
+ def _check_patches_all_filled(
+ self, axes: Union["Axes", Sequence["Axes"]], filled: bool = True
+ ) -> None:
+ """
+ Check for each artist whether it is filled or not
+
+ Parameters
+ ----------
+ axes : matplotlib Axes object, or its list-like
+ filled : bool
+ expected filling
+ """
+
+ axes = self._flatten_visible(axes)
+ for ax in axes:
+ for patch in ax.patches:
+ assert patch.fill == filled
+
def _get_colors_mapped(self, series, colors):
unique = series.unique()
# unique and colors length can be differed
diff --git a/pandas/tests/plotting/test_hist_method.py b/pandas/tests/plotting/test_hist_method.py
index 9775218e0dbf6..49335230171c6 100644
--- a/pandas/tests/plotting/test_hist_method.py
+++ b/pandas/tests/plotting/test_hist_method.py
@@ -128,6 +128,21 @@ def test_plot_fails_when_ax_differs_from_figure(self):
with pytest.raises(AssertionError):
self.ts.hist(ax=ax1, figure=fig2)
+ @pytest.mark.parametrize(
+ "histtype, expected",
+ [
+ ("bar", True),
+ ("barstacked", True),
+ ("step", False),
+ ("stepfilled", True),
+ ],
+ )
+ def test_histtype_argument(self, histtype, expected):
+ # GH23992 Verify functioning of histtype argument
+ ser = Series(np.random.randint(1, 10))
+ ax = ser.hist(histtype=histtype)
+ self._check_patches_all_filled(ax, filled=expected)
+
@pytest.mark.parametrize(
"by, expected_axes_num, expected_layout", [(None, 1, (1, 1)), ("b", 2, (1, 2))]
)
@@ -364,6 +379,21 @@ def test_hist_column_order_unchanged(self, column, expected):
assert result == expected
+ @pytest.mark.parametrize(
+ "histtype, expected",
+ [
+ ("bar", True),
+ ("barstacked", True),
+ ("step", False),
+ ("stepfilled", True),
+ ],
+ )
+ def test_histtype_argument(self, histtype, expected):
+ # GH23992 Verify functioning of histtype argument
+ df = DataFrame(np.random.randint(1, 10, size=(100, 2)), columns=["a", "b"])
+ ax = df.hist(histtype=histtype)
+ self._check_patches_all_filled(ax, filled=expected)
+
@pytest.mark.parametrize("by", [None, "c"])
@pytest.mark.parametrize("column", [None, "b"])
def test_hist_with_legend(self, by, column):
@@ -594,3 +624,18 @@ def test_axis_share_xy(self):
assert ax1._shared_y_axes.joined(ax1, ax2)
assert ax2._shared_y_axes.joined(ax1, ax2)
+
+ @pytest.mark.parametrize(
+ "histtype, expected",
+ [
+ ("bar", True),
+ ("barstacked", True),
+ ("step", False),
+ ("stepfilled", True),
+ ],
+ )
+ def test_histtype_argument(self, histtype, expected):
+ # GH23992 Verify functioning of histtype argument
+ df = DataFrame(np.random.randint(1, 10, size=(100, 2)), columns=["a", "b"])
+ ax = df.hist(by="a", histtype=histtype)
+ self._check_patches_all_filled(ax, filled=expected)
| - [x] closes #23992
- [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/37063 | 2020-10-11T23:27:19Z | 2020-11-01T06:31:43Z | 2020-11-01T06:31:43Z | 2020-11-01T06:31:43Z |
REF/TYP: use OpsMixin for StringArray | diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py
index 553ba25270943..8231a5fa0509b 100644
--- a/pandas/core/arrays/string_.py
+++ b/pandas/core/arrays/string_.py
@@ -1,4 +1,3 @@
-import operator
from typing import TYPE_CHECKING, Type, Union
import numpy as np
@@ -15,7 +14,6 @@
pandas_dtype,
)
-from pandas import compat
from pandas.core import ops
from pandas.core.arrays import IntegerArray, PandasArray
from pandas.core.arrays.integer import _IntegerDtype
@@ -344,26 +342,7 @@ def _cmp_method(self, other, op):
result[valid] = op(self._ndarray[valid], other)
return BooleanArray(result, mask)
- # Override parent because we have different return types.
- @classmethod
- def _create_arithmetic_method(cls, op):
- # Note: this handles both arithmetic and comparison methods.
-
- assert op.__name__ in ops.ARITHMETIC_BINOPS | ops.COMPARISON_BINOPS
-
- @ops.unpack_zerodim_and_defer(op.__name__)
- def method(self, other):
- return self._cmp_method(other, op)
-
- return compat.set_function_name(method, f"__{op.__name__}__", cls)
-
- @classmethod
- def _add_arithmetic_ops(cls):
- cls.__add__ = cls._create_arithmetic_method(operator.add)
- cls.__radd__ = cls._create_arithmetic_method(ops.radd)
-
- cls.__mul__ = cls._create_arithmetic_method(operator.mul)
- cls.__rmul__ = cls._create_arithmetic_method(ops.rmul)
+ _arith_method = _cmp_method
# ------------------------------------------------------------------------
# String methods interface
@@ -417,6 +396,3 @@ def _str_map(self, f, na_value=None, dtype=None):
# or .findall returns a list).
# -> We don't know the result type. E.g. `.get` can return anything.
return lib.map_infer_mask(arr, f, mask.view("uint8"))
-
-
-StringArray._add_arithmetic_ops()
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
its already mixed in, this just removes the leftover _create_arithmetic_method usage.
This is the last one outside of tests, for which we still have DecimalArray to do. | https://api.github.com/repos/pandas-dev/pandas/pulls/37061 | 2020-10-11T21:58:55Z | 2020-10-12T13:45:07Z | 2020-10-12T13:45:07Z | 2020-10-12T14:26:17Z |
TST/CLN: relocate tests for PyTables roundtrip of timezone-aware Index | diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py
index 1e1c9e91faa4b..e9cc1e6d5b1c3 100644
--- a/pandas/tests/io/pytables/test_store.py
+++ b/pandas/tests/io/pytables/test_store.py
@@ -2189,17 +2189,6 @@ def test_calendar_roundtrip_issue(self, setup_path):
result = store.select("table")
tm.assert_series_equal(result, s)
- def test_roundtrip_tz_aware_index(self, setup_path):
- # GH 17618
- time = pd.Timestamp("2000-01-01 01:00:00", tz="US/Eastern")
- df = pd.DataFrame(data=[0], index=[time])
-
- with ensure_clean_store(setup_path) as store:
- store.put("frame", df, format="fixed")
- recons = store["frame"]
- tm.assert_frame_equal(recons, df)
- assert recons.index[0].value == 946706400000000000
-
def test_append_with_timedelta(self, setup_path):
# GH 3577
# append timedelta
@@ -2554,18 +2543,6 @@ def test_store_index_name(self, setup_path):
recons = store["frame"]
tm.assert_frame_equal(recons, df)
- def test_store_index_name_with_tz(self, setup_path):
- # GH 13884
- df = pd.DataFrame({"A": [1, 2]})
- df.index = pd.DatetimeIndex([1234567890123456787, 1234567890123456788])
- df.index = df.index.tz_localize("UTC")
- df.index.name = "foo"
-
- with ensure_clean_store(setup_path) as store:
- store.put("frame", df, format="table")
- recons = store["frame"]
- tm.assert_frame_equal(recons, df)
-
@pytest.mark.parametrize("table_format", ["table", "fixed"])
def test_store_index_name_numpy_str(self, table_format, setup_path):
# GH #13492
diff --git a/pandas/tests/io/pytables/test_timezones.py b/pandas/tests/io/pytables/test_timezones.py
index 1c29928991cde..dc28e9543f19e 100644
--- a/pandas/tests/io/pytables/test_timezones.py
+++ b/pandas/tests/io/pytables/test_timezones.py
@@ -210,6 +210,31 @@ def test_append_with_timezones_pytz(setup_path):
tm.assert_frame_equal(result, df)
+def test_roundtrip_tz_aware_index(setup_path):
+ # GH 17618
+ time = pd.Timestamp("2000-01-01 01:00:00", tz="US/Eastern")
+ df = pd.DataFrame(data=[0], index=[time])
+
+ with ensure_clean_store(setup_path) as store:
+ store.put("frame", df, format="fixed")
+ recons = store["frame"]
+ tm.assert_frame_equal(recons, df)
+ assert recons.index[0].value == 946706400000000000
+
+
+def test_store_index_name_with_tz(setup_path):
+ # GH 13884
+ df = pd.DataFrame({"A": [1, 2]})
+ df.index = pd.DatetimeIndex([1234567890123456787, 1234567890123456788])
+ df.index = df.index.tz_localize("UTC")
+ df.index.name = "foo"
+
+ with ensure_clean_store(setup_path) as store:
+ store.put("frame", df, format="table")
+ recons = store["frame"]
+ tm.assert_frame_equal(recons, df)
+
+
def test_tseries_select_index_column(setup_path):
# GH7777
# selecting a UTC datetimeindex column did
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/37060 | 2020-10-11T20:45:07Z | 2020-10-12T05:45:23Z | 2020-10-12T05:45:23Z | 2020-10-13T02:44:43Z |
TYP: mostly io, plotting | diff --git a/pandas/core/base.py b/pandas/core/base.py
index 10b83116dee58..6af537dcd149a 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -4,12 +4,22 @@
import builtins
import textwrap
-from typing import Any, Callable, Dict, FrozenSet, Optional, TypeVar, Union
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Callable,
+ Dict,
+ FrozenSet,
+ Optional,
+ TypeVar,
+ Union,
+ cast,
+)
import numpy as np
import pandas._libs.lib as lib
-from pandas._typing import IndexLabel
+from pandas._typing import DtypeObj, IndexLabel
from pandas.compat import PYPY
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
@@ -33,6 +43,9 @@
from pandas.core.construction import create_series_with_explicit_dtype
import pandas.core.nanops as nanops
+if TYPE_CHECKING:
+ from pandas import Categorical
+
_shared_docs: Dict[str, str] = dict()
_indexops_doc_kwargs = dict(
klass="IndexOpsMixin",
@@ -238,7 +251,7 @@ def _gotitem(self, key, ndim: int, subset=None):
Parameters
----------
key : str / list of selections
- ndim : 1,2
+ ndim : {1, 2}
requested ndim of result
subset : object, default None
subset to act on
@@ -305,6 +318,11 @@ class IndexOpsMixin(OpsMixin):
["tolist"] # tolist is not deprecated, just suppressed in the __dir__
)
+ @property
+ def dtype(self) -> DtypeObj:
+ # must be defined here as a property for mypy
+ raise AbstractMethodError(self)
+
@property
def _values(self) -> Union[ExtensionArray, np.ndarray]:
# must be defined here as a property for mypy
@@ -832,6 +850,7 @@ def _map_values(self, mapper, na_action=None):
if is_categorical_dtype(self.dtype):
# use the built in categorical series mapper which saves
# time by mapping the categories instead of all values
+ self = cast("Categorical", self)
return self._values.map(mapper)
values = self._values
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index 8038bc6bf1c72..a5e8edca80873 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -164,6 +164,7 @@ class CategoricalIndex(ExtensionIndex, accessor.PandasDelegate):
codes: np.ndarray
categories: Index
_data: Categorical
+ _values: Categorical
@property
def _engine_type(self):
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index 604b7e12ec243..3461652f4ea24 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -785,14 +785,19 @@ def _value_with_fmt(self, val):
return val, fmt
@classmethod
- def check_extension(cls, ext):
+ def check_extension(cls, ext: str):
"""
checks that path's extension against the Writer's supported
extensions. If it isn't supported, raises UnsupportedFiletypeError.
"""
if ext.startswith("."):
ext = ext[1:]
- if not any(ext in extension for extension in cls.supported_extensions):
+ # error: "Callable[[ExcelWriter], Any]" has no attribute "__iter__"
+ # (not iterable) [attr-defined]
+ if not any(
+ ext in extension
+ for extension in cls.supported_extensions # type: ignore[attr-defined]
+ ):
raise ValueError(f"Invalid extension for engine '{cls.engine}': '{ext}'")
else:
return True
diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py
index 3e4780ec21378..2977a78f02785 100644
--- a/pandas/io/formats/format.py
+++ b/pandas/io/formats/format.py
@@ -1835,9 +1835,11 @@ def _make_fixed_width(
return strings
if adj is None:
- adj = get_adjustment()
+ adjustment = get_adjustment()
+ else:
+ adjustment = adj
- max_len = max(adj.len(x) for x in strings)
+ max_len = max(adjustment.len(x) for x in strings)
if minimum is not None:
max_len = max(minimum, max_len)
@@ -1846,14 +1848,14 @@ def _make_fixed_width(
if conf_max is not None and max_len > conf_max:
max_len = conf_max
- def just(x):
+ def just(x: str) -> str:
if conf_max is not None:
- if (conf_max > 3) & (adj.len(x) > max_len):
+ if (conf_max > 3) & (adjustment.len(x) > max_len):
x = x[: max_len - 3] + "..."
return x
strings = [just(x) for x in strings]
- result = adj.justify(strings, max_len, mode=justify)
+ result = adjustment.justify(strings, max_len, mode=justify)
return result
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 63c3f9899d915..1184b0436b93d 100644
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -1661,7 +1661,7 @@ def _get_name(icol):
return index
- def _agg_index(self, index, try_parse_dates=True):
+ def _agg_index(self, index, try_parse_dates=True) -> Index:
arrays = []
for i, arr in enumerate(index):
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 2903ede1d5c0b..5160773455067 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -565,6 +565,7 @@ def __fspath__(self):
def root(self):
""" return the root node """
self._check_if_open()
+ assert self._handle is not None # for mypy
return self._handle.root
@property
@@ -1393,6 +1394,8 @@ def groups(self):
"""
_tables()
self._check_if_open()
+ assert self._handle is not None # for mypy
+ assert _table_mod is not None # for mypy
return [
g
for g in self._handle.walk_groups()
@@ -1437,6 +1440,9 @@ def walk(self, where="/"):
"""
_tables()
self._check_if_open()
+ assert self._handle is not None # for mypy
+ assert _table_mod is not None # for mypy
+
for g in self._handle.walk_groups(where):
if getattr(g._v_attrs, "pandas_type", None) is not None:
continue
@@ -1862,6 +1868,8 @@ def __init__(
def __iter__(self):
# iterate
current = self.start
+ if self.coordinates is None:
+ raise ValueError("Cannot iterate until get_result is called.")
while current < self.stop:
stop = min(current + self.chunksize, self.stop)
value = self.func(None, None, self.coordinates[current:stop])
@@ -3196,7 +3204,7 @@ class Table(Fixed):
pandas_kind = "wide_table"
format_type: str = "table" # GH#30962 needed by dask
table_type: str
- levels = 1
+ levels: Union[int, List[Label]] = 1
is_table = True
index_axes: List[IndexCol]
@@ -3292,7 +3300,9 @@ def is_multi_index(self) -> bool:
"""the levels attribute is 1 or a list in the case of a multi-index"""
return isinstance(self.levels, list)
- def validate_multiindex(self, obj):
+ def validate_multiindex(
+ self, obj: FrameOrSeriesUnion
+ ) -> Tuple[DataFrame, List[Label]]:
"""
validate that we can store the multi-index; reset and return the
new object
@@ -3301,11 +3311,13 @@ def validate_multiindex(self, obj):
l if l is not None else f"level_{i}" for i, l in enumerate(obj.index.names)
]
try:
- return obj.reset_index(), levels
+ reset_obj = obj.reset_index()
except ValueError as err:
raise ValueError(
"duplicate names/columns in the multi-index when storing as a table"
) from err
+ assert isinstance(reset_obj, DataFrame) # for mypy
+ return reset_obj, levels
@property
def nrows_expected(self) -> int:
@@ -3433,7 +3445,7 @@ def get_attrs(self):
self.nan_rep = getattr(self.attrs, "nan_rep", None)
self.encoding = _ensure_encoding(getattr(self.attrs, "encoding", None))
self.errors = _ensure_decoded(getattr(self.attrs, "errors", "strict"))
- self.levels = getattr(self.attrs, "levels", None) or []
+ self.levels: List[Label] = getattr(self.attrs, "levels", None) or []
self.index_axes = [a for a in self.indexables if a.is_an_indexable]
self.values_axes = [a for a in self.indexables if not a.is_an_indexable]
@@ -4562,11 +4574,12 @@ class AppendableMultiSeriesTable(AppendableSeriesTable):
def write(self, obj, **kwargs):
""" we are going to write this as a frame table """
name = obj.name or "values"
- obj, self.levels = self.validate_multiindex(obj)
+ newobj, self.levels = self.validate_multiindex(obj)
+ assert isinstance(self.levels, list) # for mypy
cols = list(self.levels)
cols.append(name)
- obj.columns = cols
- return super().write(obj=obj, **kwargs)
+ newobj.columns = Index(cols)
+ return super().write(obj=newobj, **kwargs)
class GenericTable(AppendableFrameTable):
@@ -4576,6 +4589,7 @@ class GenericTable(AppendableFrameTable):
table_type = "generic_table"
ndim = 2
obj_type = DataFrame
+ levels: List[Label]
@property
def pandas_type(self) -> str:
@@ -4609,7 +4623,7 @@ def indexables(self):
name="index", axis=0, table=self.table, meta=meta, metadata=md
)
- _indexables = [index_col]
+ _indexables: List[Union[GenericIndexCol, GenericDataIndexableCol]] = [index_col]
for i, n in enumerate(d._v_names):
assert isinstance(n, str)
@@ -4652,6 +4666,7 @@ def write(self, obj, data_columns=None, **kwargs):
elif data_columns is True:
data_columns = obj.columns.tolist()
obj, self.levels = self.validate_multiindex(obj)
+ assert isinstance(self.levels, list) # for mypy
for n in self.levels:
if n not in data_columns:
data_columns.insert(0, n)
@@ -5173,7 +5188,7 @@ def select_coords(self):
start = 0
elif start < 0:
start += nrows
- if self.stop is None:
+ if stop is None:
stop = nrows
elif stop < 0:
stop += nrows
diff --git a/pandas/io/stata.py b/pandas/io/stata.py
index 55dde374048b6..c128c56f496cc 100644
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -378,8 +378,8 @@ def parse_dates_safe(dates, delta=False, year=False, days=False):
d["delta"] = time_delta._values.astype(np.int64) // 1000 # microseconds
if days or year:
date_index = DatetimeIndex(dates)
- d["year"] = date_index.year
- d["month"] = date_index.month
+ d["year"] = date_index._data.year
+ d["month"] = date_index._data.month
if days:
days_in_ns = dates.astype(np.int64) - to_datetime(
d["year"], format="%Y"
@@ -887,7 +887,9 @@ def __init__(self):
(65530, np.int8),
]
)
- self.TYPE_MAP = list(range(251)) + list("bhlfd")
+ # error: Argument 1 to "list" has incompatible type "str";
+ # expected "Iterable[int]" [arg-type]
+ self.TYPE_MAP = list(range(251)) + list("bhlfd") # type: ignore[arg-type]
self.TYPE_MAP_XML = dict(
[
# Not really a Q, unclear how to handle byteswap
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py
index f806325d60eca..a69767df267fc 100644
--- a/pandas/plotting/_matplotlib/core.py
+++ b/pandas/plotting/_matplotlib/core.py
@@ -82,6 +82,8 @@ def _kind(self):
_default_rot = 0
orientation: Optional[str] = None
+ axes: np.ndarray # of Axes objects
+
def __init__(
self,
data,
@@ -177,7 +179,7 @@ def __init__(
self.ax = ax
self.fig = fig
- self.axes = None
+ self.axes = np.array([], dtype=object) # "real" version get set in `generate`
# parse errorbar input if given
xerr = kwds.pop("xerr", None)
@@ -697,7 +699,7 @@ def _get_ax_layer(cls, ax, primary=True):
else:
return getattr(ax, "right_ax", ax)
- def _get_ax(self, i):
+ def _get_ax(self, i: int):
# get the twinx ax if appropriate
if self.subplots:
ax = self.axes[i]
diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py
index 832957dd73ec7..bec1f48f5e64a 100644
--- a/pandas/plotting/_matplotlib/tools.py
+++ b/pandas/plotting/_matplotlib/tools.py
@@ -401,11 +401,11 @@ def handle_shared_axes(
_remove_labels_from_axis(ax.yaxis)
-def flatten_axes(axes: Union["Axes", Sequence["Axes"]]) -> Sequence["Axes"]:
+def flatten_axes(axes: Union["Axes", Sequence["Axes"]]) -> np.ndarray:
if not is_list_like(axes):
return np.array([axes])
elif isinstance(axes, (np.ndarray, ABCIndexClass)):
- return axes.ravel()
+ return np.asarray(axes).ravel()
return np.array(axes)
diff --git a/setup.cfg b/setup.cfg
index 447adc9188951..ad72374fa325d 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -223,12 +223,6 @@ check_untyped_defs=False
[mypy-pandas.io.parsers]
check_untyped_defs=False
-[mypy-pandas.io.pytables]
-check_untyped_defs=False
-
-[mypy-pandas.io.stata]
-check_untyped_defs=False
-
[mypy-pandas.plotting._matplotlib.converter]
check_untyped_defs=False
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
cc @simonjayhawkins can i get your thoughts on two remaining mypy complaints
```
pandas/io/excel/_base.py:795: error: "Callable[[ExcelWriter], Tuple[str, ...]]" has no attribute "__iter__" (not iterable) [attr-defined]
pandas/io/stata.py:892: error: unused 'type: ignore' comment
```
The excel one is because it doesn't recognize
```
@property
@abstractmethod
def supported_extensions(self) -> Tuple[str, ...]:
```
as returning `Tuple[str, ...]`. I expect if that were resolved it would still complain bc subclasses just pin the tuple as a class attribute instead of a property (easy to make a property, but much more verbose which im not wild about)
The stata unused type:ignore becomes used once we remove stata from the setup.cfg exclusion. The only working way I've found to make mypy accept `TYPE_MAP: List[Union[int, str]] = list(range(251)) + list("abcd")` is with
```
TYPE_MAP: List[Union[int, str]] = cast(List[Union[int, str]], list(range(251))) + list("abcd")
```
which i find much less clear than the `# type:ignore`d version. | https://api.github.com/repos/pandas-dev/pandas/pulls/37059 | 2020-10-11T18:37:56Z | 2020-10-14T12:27:19Z | 2020-10-14T12:27:19Z | 2020-10-14T14:41:51Z |
TYP: core.internals | diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index 94d6428b44043..debfb50caeeaa 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -1081,6 +1081,19 @@ def _formatter(self, boxed: bool = False) -> Callable[[Any], Optional[str]]:
# Reshaping
# ------------------------------------------------------------------------
+ def transpose(self, *axes) -> "ExtensionArray":
+ """
+ Return a transposed view on this array.
+
+ Because ExtensionArrays are always 1D, this is a no-op. It is included
+ for compatibility with np.ndarray.
+ """
+ return self[:]
+
+ @property
+ def T(self) -> "ExtensionArray":
+ return self.transpose()
+
def ravel(self, order="C") -> "ExtensionArray":
"""
Return a flattened view on this array.
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index 480bae199683f..2e62fade93dcb 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -1310,19 +1310,6 @@ def mean(self, axis=0, *args, **kwargs):
nsparse = self.sp_index.ngaps
return (sp_sum + self.fill_value * nsparse) / (ct + nsparse)
- def transpose(self, *axes) -> "SparseArray":
- """
- Returns the SparseArray.
- """
- return self
-
- @property
- def T(self) -> "SparseArray":
- """
- Returns the SparseArray.
- """
- return self
-
# ------------------------------------------------------------------------
# Ufuncs
# ------------------------------------------------------------------------
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index ac210ecbaad5f..98ae52b04cee3 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -1,7 +1,7 @@
from datetime import datetime, timedelta
import inspect
import re
-from typing import TYPE_CHECKING, Any, List, Optional
+from typing import TYPE_CHECKING, Any, List, Optional, Type, Union, cast
import warnings
import numpy as np
@@ -93,6 +93,8 @@ class Block(PandasObject):
Index-ignorant; let the container take care of that
"""
+ values: Union[np.ndarray, ExtensionArray]
+
__slots__ = ["_mgr_locs", "values", "ndim"]
is_numeric = False
is_float = False
@@ -194,7 +196,9 @@ def _consolidate_key(self):
@property
def is_view(self) -> bool:
""" return a boolean if I am possibly a view """
- return self.values.base is not None
+ values = self.values
+ values = cast(np.ndarray, values)
+ return values.base is not None
@property
def is_categorical(self) -> bool:
@@ -1465,6 +1469,7 @@ def where_func(cond, values, other):
result_blocks: List["Block"] = []
for m in [mask, ~mask]:
if m.any():
+ result = cast(np.ndarray, result) # EABlock overrides where
taken = result.take(m.nonzero()[0], axis=axis)
r = maybe_downcast_numeric(taken, self.dtype)
nb = self.make_block(r.T, placement=self.mgr_locs[m])
@@ -1619,6 +1624,8 @@ class ExtensionBlock(Block):
_validate_ndim = False
is_extension = True
+ values: ExtensionArray
+
def __init__(self, values, placement, ndim=None):
"""
Initialize a non-consolidatable block.
@@ -2197,9 +2204,7 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"):
if copy:
# this should be the only copy
values = values.copy()
- if getattr(values, "tz", None) is None:
- values = DatetimeArray(values).tz_localize("UTC")
- values = values.tz_convert(dtype.tz)
+ values = DatetimeArray._simple_new(values.view("i8"), dtype=dtype)
return self.make_block(values)
# delegate
@@ -2243,6 +2248,8 @@ def set(self, locs, values):
class DatetimeTZBlock(ExtensionBlock, DatetimeBlock):
""" implement a datetime64 block with a tz attribute """
+ values: DatetimeArray
+
__slots__ = ()
is_datetimetz = True
is_extension = True
@@ -2670,6 +2677,8 @@ def get_block_type(values, dtype=None):
dtype = dtype or values.dtype
vtype = dtype.type
+ cls: Type[Block]
+
if is_sparse(dtype):
# Need this first(ish) so that Sparse[datetime] is sparse
cls = ExtensionBlock
diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py
index 6244f1bf0a2d2..bb8283604abb0 100644
--- a/pandas/core/internals/construction.py
+++ b/pandas/core/internals/construction.py
@@ -9,7 +9,7 @@
import numpy.ma as ma
from pandas._libs import lib
-from pandas._typing import Axis, DtypeObj, Scalar
+from pandas._typing import Axis, DtypeObj, Label, Scalar
from pandas.core.dtypes.cast import (
construct_1d_arraylike_from_scalar,
@@ -436,7 +436,7 @@ def get_names_from_index(data):
if not has_some_name:
return ibase.default_index(len(data))
- index = list(range(len(data)))
+ index: List[Label] = list(range(len(data)))
count = 0
for i, s in enumerate(data):
n = getattr(s, "name", None)
diff --git a/pandas/tests/extension/base/reshaping.py b/pandas/tests/extension/base/reshaping.py
index 7be50c5f8c305..44e3fc1eb56d8 100644
--- a/pandas/tests/extension/base/reshaping.py
+++ b/pandas/tests/extension/base/reshaping.py
@@ -333,6 +333,20 @@ def test_ravel(self, data):
assert data[0] == data[1]
def test_transpose(self, data):
+ result = data.transpose()
+ assert type(result) == type(data)
+
+ # check we get a new object
+ assert result is not data
+
+ # If we ever _did_ support 2D, shape should be reversed
+ assert result.shape == data.shape[::-1]
+
+ # Check that we have a view, not a copy
+ result[0] = result[1]
+ assert data[0] == data[1]
+
+ def test_transpose_frame(self, data):
df = pd.DataFrame({"A": data[:4], "B": data[:4]}, index=["a", "b", "c", "d"])
result = df.T
expected = pd.DataFrame(
diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py
index c4afcd7a536df..29790d14f93cc 100644
--- a/pandas/tests/extension/test_numpy.py
+++ b/pandas/tests/extension/test_numpy.py
@@ -377,8 +377,8 @@ def test_merge_on_extension_array_duplicates(self, data):
super().test_merge_on_extension_array_duplicates(data)
@skip_nested
- def test_transpose(self, data):
- super().test_transpose(data)
+ def test_transpose_frame(self, data):
+ super().test_transpose_frame(data)
class TestSetitem(BaseNumPyTests, base.BaseSetitemTests):
diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py
index d11cfd219a443..0751c37a7f439 100644
--- a/pandas/tests/extension/test_sparse.py
+++ b/pandas/tests/extension/test_sparse.py
@@ -155,6 +155,10 @@ def test_merge(self, data, na_value):
self._check_unsupported(data)
super().test_merge(data, na_value)
+ @pytest.mark.xfail(reason="SparseArray does not support setitem")
+ def test_transpose(self, data):
+ super().test_transpose(data)
+
class TestGetitem(BaseSparseTests, base.BaseGetitemTests):
def test_get(self, data):
diff --git a/setup.cfg b/setup.cfg
index 2ae00e0efeda4..447adc9188951 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -187,12 +187,6 @@ check_untyped_defs=False
[mypy-pandas.core.indexes.multi]
check_untyped_defs=False
-[mypy-pandas.core.internals.blocks]
-check_untyped_defs=False
-
-[mypy-pandas.core.internals.construction]
-check_untyped_defs=False
-
[mypy-pandas.core.resample]
check_untyped_defs=False
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Annotating Block as `Union[np.ndarray, ExtensionArray]`, mypy gives tons of complaints about EA not having `.T`, so this adds that, then updates tests as appropriate | https://api.github.com/repos/pandas-dev/pandas/pulls/37058 | 2020-10-11T18:04:07Z | 2020-10-12T15:05:16Z | 2020-10-12T15:05:15Z | 2020-10-12T17:01:31Z |
Write pickle to file-like without intermediate in-memory buffer | diff --git a/asv_bench/benchmarks/io/pickle.py b/asv_bench/benchmarks/io/pickle.py
index 4ca9a82ae4827..656fe2197bc8a 100644
--- a/asv_bench/benchmarks/io/pickle.py
+++ b/asv_bench/benchmarks/io/pickle.py
@@ -24,5 +24,11 @@ def time_read_pickle(self):
def time_write_pickle(self):
self.df.to_pickle(self.fname)
+ def peakmem_read_pickle(self):
+ read_pickle(self.fname)
+
+ def peakmem_write_pickle(self):
+ self.df.to_pickle(self.fname)
+
from ..pandas_vb_common import setup # noqa: F401 isort:skip
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index da7dcc6ab29b9..d84b7532060af 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -314,6 +314,7 @@ Performance improvements
avoiding creating these again, if created on either. This can speed up operations that depend on creating copies of existing indexes (:issue:`36840`)
- Performance improvement in :meth:`RollingGroupby.count` (:issue:`35625`)
- Small performance decrease to :meth:`Rolling.min` and :meth:`Rolling.max` for fixed windows (:issue:`36567`)
+- Reduced peak memory usage in :meth:`DataFrame.to_pickle` when using ``protocol=5`` in python 3.8+ (:issue:`34244`)
- Performance improvement in :class:`ExpandingGroupby` (:issue:`37064`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/io/pickle.py b/pandas/io/pickle.py
index 80baa6f78ddd7..426a40a65b522 100644
--- a/pandas/io/pickle.py
+++ b/pandas/io/pickle.py
@@ -98,7 +98,7 @@ def to_pickle(
if protocol < 0:
protocol = pickle.HIGHEST_PROTOCOL
try:
- f.write(pickle.dumps(obj, protocol=protocol))
+ pickle.dump(obj, f, protocol=protocol)
finally:
if f != filepath_or_buffer:
# do not close user-provided file objects GH 35679
diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py
index 2241fe7013568..a37349654b120 100644
--- a/pandas/tests/io/test_pickle.py
+++ b/pandas/tests/io/test_pickle.py
@@ -12,6 +12,7 @@
"""
import bz2
import datetime
+import functools
import glob
import gzip
import io
@@ -24,7 +25,7 @@
import pytest
-from pandas.compat import get_lzma_file, import_lzma, is_platform_little_endian
+from pandas.compat import PY38, get_lzma_file, import_lzma, is_platform_little_endian
import pandas.util._test_decorators as td
import pandas as pd
@@ -155,28 +156,43 @@ def test_pickles(current_pickle_data, legacy_pickle):
compare(current_pickle_data, legacy_pickle, version)
-def test_round_trip_current(current_pickle_data):
- def python_pickler(obj, path):
- with open(path, "wb") as fh:
- pickle.dump(obj, fh, protocol=-1)
+def python_pickler(obj, path):
+ with open(path, "wb") as fh:
+ pickle.dump(obj, fh, protocol=-1)
- def python_unpickler(path):
- with open(path, "rb") as fh:
- fh.seek(0)
- return pickle.load(fh)
+def python_unpickler(path):
+ with open(path, "rb") as fh:
+ fh.seek(0)
+ return pickle.load(fh)
+
+
+@pytest.mark.parametrize(
+ "pickle_writer",
+ [
+ pytest.param(python_pickler, id="python"),
+ pytest.param(pd.to_pickle, id="pandas_proto_default"),
+ pytest.param(
+ functools.partial(pd.to_pickle, protocol=pickle.HIGHEST_PROTOCOL),
+ id="pandas_proto_highest",
+ ),
+ pytest.param(functools.partial(pd.to_pickle, protocol=4), id="pandas_proto_4"),
+ pytest.param(
+ functools.partial(pd.to_pickle, protocol=5),
+ id="pandas_proto_5",
+ marks=pytest.mark.skipif(not PY38, reason="protocol 5 not supported"),
+ ),
+ ],
+)
+def test_round_trip_current(current_pickle_data, pickle_writer):
data = current_pickle_data
for typ, dv in data.items():
for dt, expected in dv.items():
for writer in [pd.to_pickle, python_pickler]:
- if writer is None:
- continue
-
with tm.ensure_clean() as path:
-
# test writing with each pickler
- writer(expected, path)
+ pickle_writer(expected, path)
# test reading with each unpickler
result = pd.read_pickle(path)
| Before this change, calling `pickle.dumps()` created an in-memory byte buffer, negating the advantage
of zero-copy pickle protocol 5. After this change, `pickle.dump` writes directly to open file(-like),
cutting peak memory in half in most cases.
Profiling was done with pandas@master and python 3.8.5
Related issues:
- https://github.com/pandas-dev/pandas/issues/34244

## Update: ASV results
`$ asv continuous -f 1.1 origin/master HEAD -b pickle` yields:
```
before after ratio
[58f74686] [3c1ee270]
<zero-copy-pickle>
- 91.9M 80.1M 0.87 io.pickle.Pickle.peakmem_write_pickle
SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY.
PERFORMANCE INCREASED.
```
- [ ] closes #34244
- [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/37056 | 2020-10-11T16:15:57Z | 2020-10-14T12:27:39Z | 2020-10-14T12:27:38Z | 2020-10-14T12:27:44Z |
ENH: Use Kahan summation and Welfords method to calculate rolling var and std | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index da7dcc6ab29b9..74534bc371094 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -192,6 +192,7 @@ Other enhancements
- Added methods :meth:`IntegerArray.prod`, :meth:`IntegerArray.min`, and :meth:`IntegerArray.max` (:issue:`33790`)
- Where possible :meth:`RangeIndex.difference` and :meth:`RangeIndex.symmetric_difference` will return :class:`RangeIndex` instead of :class:`Int64Index` (:issue:`36564`)
- Added :meth:`Rolling.sem()` and :meth:`Expanding.sem()` to compute the standard error of mean (:issue:`26476`).
+- :meth:`Rolling.var()` and :meth:`Rolling.std()` use Kahan summation and Welfords Method to avoid numerical issues (:issue:`37051`)
.. _whatsnew_120.api_breaking.python:
diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx
index bba8b4b2432a9..131e0154ce8fc 100644
--- a/pandas/_libs/window/aggregations.pyx
+++ b/pandas/_libs/window/aggregations.pyx
@@ -311,37 +311,46 @@ cdef inline float64_t calc_var(int64_t minp, int ddof, float64_t nobs,
cdef inline void add_var(float64_t val, float64_t *nobs, float64_t *mean_x,
- float64_t *ssqdm_x) nogil:
+ float64_t *ssqdm_x, float64_t *compensation) nogil:
""" add a value from the var calc """
cdef:
- float64_t delta
+ float64_t delta, prev_mean, y, t
# `isnan` instead of equality as fix for GH-21813, msvc 2017 bug
if isnan(val):
return
nobs[0] = nobs[0] + 1
- # a part of Welford's method for the online variance-calculation
+ # Welford's method for the online variance-calculation
+ # using Kahan summation
# https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
- delta = val - mean_x[0]
+ prev_mean = mean_x[0] - compensation[0]
+ y = val - compensation[0]
+ t = y - mean_x[0]
+ compensation[0] = t + mean_x[0] - y
+ delta = t
mean_x[0] = mean_x[0] + delta / nobs[0]
- ssqdm_x[0] = ssqdm_x[0] + ((nobs[0] - 1) * delta ** 2) / nobs[0]
+ ssqdm_x[0] = ssqdm_x[0] + (val - prev_mean) * (val - mean_x[0])
cdef inline void remove_var(float64_t val, float64_t *nobs, float64_t *mean_x,
- float64_t *ssqdm_x) nogil:
+ float64_t *ssqdm_x, float64_t *compensation) nogil:
""" remove a value from the var calc """
cdef:
- float64_t delta
-
+ float64_t delta, prev_mean, y, t
if notnan(val):
nobs[0] = nobs[0] - 1
if nobs[0]:
- # a part of Welford's method for the online variance-calculation
+ # Welford's method for the online variance-calculation
+ # using Kahan summation
# https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
- delta = val - mean_x[0]
+ prev_mean = mean_x[0] - compensation[0]
+ y = val - compensation[0]
+ t = y - mean_x[0]
+ compensation[0] = t + mean_x[0] - y
+ delta = t
mean_x[0] = mean_x[0] - delta / nobs[0]
- ssqdm_x[0] = ssqdm_x[0] - ((nobs[0] + 1) * delta ** 2) / nobs[0]
+ ssqdm_x[0] = ssqdm_x[0] - (val - prev_mean) * (val - mean_x[0])
else:
mean_x[0] = 0
ssqdm_x[0] = 0
@@ -353,7 +362,8 @@ def roll_var(ndarray[float64_t] values, ndarray[int64_t] start,
Numerically stable implementation using Welford's method.
"""
cdef:
- float64_t mean_x = 0, ssqdm_x = 0, nobs = 0,
+ float64_t mean_x = 0, ssqdm_x = 0, nobs = 0, compensation_add = 0,
+ float64_t compensation_remove = 0,
float64_t val, prev, delta, mean_x_old
int64_t s, e
Py_ssize_t i, j, N = len(values)
@@ -375,26 +385,28 @@ def roll_var(ndarray[float64_t] values, ndarray[int64_t] start,
if i == 0 or not is_monotonic_bounds:
for j in range(s, e):
- add_var(values[j], &nobs, &mean_x, &ssqdm_x)
+ add_var(values[j], &nobs, &mean_x, &ssqdm_x, &compensation_add)
else:
# After the first window, observations can both be added
# and removed
- # calculate adds
- for j in range(end[i - 1], e):
- add_var(values[j], &nobs, &mean_x, &ssqdm_x)
-
# calculate deletes
for j in range(start[i - 1], s):
- remove_var(values[j], &nobs, &mean_x, &ssqdm_x)
+ remove_var(values[j], &nobs, &mean_x, &ssqdm_x,
+ &compensation_remove)
+
+ # calculate adds
+ for j in range(end[i - 1], e):
+ add_var(values[j], &nobs, &mean_x, &ssqdm_x, &compensation_add)
output[i] = calc_var(minp, ddof, nobs, ssqdm_x)
if not is_monotonic_bounds:
for j in range(s, e):
- remove_var(values[j], &nobs, &mean_x, &ssqdm_x)
+ remove_var(values[j], &nobs, &mean_x, &ssqdm_x,
+ &compensation_remove)
return output
diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py
index a5fbc3c94786c..3d59f6cdd4996 100644
--- a/pandas/tests/window/test_rolling.py
+++ b/pandas/tests/window/test_rolling.py
@@ -879,3 +879,20 @@ def test_rolling_sem(constructor):
result = pd.Series(result[0].values)
expected = pd.Series([np.nan] + [0.707107] * 2)
tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ ("func", "third_value", "values"),
+ [
+ ("var", 1, [5e33, 0, 0.5, 0.5, 2, 0]),
+ ("std", 1, [7.071068e16, 0, 0.7071068, 0.7071068, 1.414214, 0]),
+ ("var", 2, [5e33, 0.5, 0, 0.5, 2, 0]),
+ ("std", 2, [7.071068e16, 0.7071068, 0, 0.7071068, 1.414214, 0]),
+ ],
+)
+def test_rolling_var_numerical_issues(func, third_value, values):
+ # GH: 37051
+ ds = pd.Series([99999999999999999, 1, third_value, 2, 3, 1, 1])
+ result = getattr(ds.rolling(2), func)()
+ expected = pd.Series([np.nan] + values)
+ tm.assert_series_equal(result, expected)
| - [x] xref #37051
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
As suggested by @mroeschke Kahan summation fixes the numerical problems. Additionally I used Welfords Method to calculate ``ssqdm``, because previously the tests I have added would return
```
0 NaN
1 3.500000e+34
2 3.000000e+34
3 3.000000e+34
4 3.000000e+34
5 3.000000e+34
6 3.000000e+34
7 3.000000e+34
8 3.000000e+34
9 3.000000e+34
dtype: float64
```
for ``var()``. I am running the asv and will post the results when available | https://api.github.com/repos/pandas-dev/pandas/pulls/37055 | 2020-10-11T15:56:35Z | 2020-10-12T22:53:38Z | 2020-10-12T22:53:38Z | 2020-10-14T20:04:13Z |
CI clean pre-commit: upgrade isort, use correct file types in flake8 | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 39fe509c6cd29..5b8b58a6a82f8 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -9,24 +9,23 @@ repos:
- id: flake8
additional_dependencies: [flake8-comprehensions>=3.1.0]
- id: flake8
- name: flake8-pyx
- files: \.(pyx|pxd)$
- types:
- - file
+ name: flake8 (cython)
+ types: [cython]
args: [--append-config=flake8/cython.cfg]
- id: flake8
- name: flake8-pxd
+ name: flake8 (cython template)
files: \.pxi\.in$
types:
- file
args: [--append-config=flake8/cython-template.cfg]
- repo: https://github.com/PyCQA/isort
- rev: 5.6.0
+ rev: 5.6.3
hooks:
- id: isort
- exclude: ^pandas/__init__\.py$|^pandas/core/api\.py$
- files: '.pxd$|.py$'
- types: [file]
+ name: isort (python)
+ - id: isort
+ name: isort (cython)
+ types: [cython]
- repo: https://github.com/asottile/pyupgrade
rev: v2.7.2
hooks:
| A few things here:
- updating isort version
- updating to use `types` instead of `files` (see https://github.com/pre-commit/pre-commit/issues/1436#issuecomment-624219819 and https://github.com/PyCQA/isort/pull/1549#issuecomment-706621474)
- removing `exclude: ^pandas/__init__\.py$|^pandas/core/api\.py$` as it's no longer necessary
- replacing `files: \.(pyx|pxd)$` with `types: [cython]`:
```bash
$ identify-cli pandas/_libs/groupby.pyx
["cython", "file", "non-executable", "text"]
$ identify-cli pandas/_libs/lib.pxd
["cython", "file", "non-executable", "text"]
```
- replacing the name `flake8-pxd` with `flake8 (cython template)`, as that hook wasn't actually checking `.pxd` files (the `flake8-pyx` one was) | https://api.github.com/repos/pandas-dev/pandas/pulls/37052 | 2020-10-11T14:13:19Z | 2020-10-11T16:05:13Z | 2020-10-11T16:05:13Z | 2020-10-11T16:08:26Z |
CLN: core/dtypes/cast.py::maybe_downcast_to_dtype | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index a7379376c2f78..336d33cd35d7a 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -2,6 +2,7 @@
Routines for casting.
"""
+from contextlib import suppress
from datetime import date, datetime, timedelta
from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Type
@@ -154,12 +155,20 @@ def maybe_downcast_to_dtype(result, dtype):
dtype = np.dtype(dtype)
+ elif dtype.type is Period:
+ from pandas.core.arrays import PeriodArray
+
+ with suppress(TypeError):
+ # e.g. TypeError: int() argument must be a string, a
+ # bytes-like object or a number, not 'Period
+ return PeriodArray(result, freq=dtype.freq)
+
converted = maybe_downcast_numeric(result, dtype, do_round)
if converted is not result:
return converted
# a datetimelike
- # GH12821, iNaT is casted to float
+ # GH12821, iNaT is cast to float
if dtype.kind in ["M", "m"] and result.dtype.kind in ["i", "f"]:
if hasattr(dtype, "tz"):
# not a numpy dtype
@@ -172,17 +181,6 @@ def maybe_downcast_to_dtype(result, dtype):
else:
result = result.astype(dtype)
- elif dtype.type is Period:
- # TODO(DatetimeArray): merge with previous elif
- from pandas.core.arrays import PeriodArray
-
- try:
- return PeriodArray(result, freq=dtype.freq)
- except TypeError:
- # e.g. TypeError: int() argument must be a string, a
- # bytes-like object or a number, not 'Period
- pass
-
return result
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/37050 | 2020-10-11T04:17:50Z | 2020-10-14T12:32:43Z | 2020-10-14T12:32:43Z | 2020-10-14T16:15:11Z |
REF: use OpsMixin in EAs | diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py
index 4dd117e407961..9ffe00cf3189a 100644
--- a/pandas/core/arrays/boolean.py
+++ b/pandas/core/arrays/boolean.py
@@ -6,7 +6,6 @@
from pandas._libs import lib, missing as libmissing
from pandas._typing import ArrayLike
-from pandas.compat import set_function_name
from pandas.compat.numpy import function as nv
from pandas.core.dtypes.common import (
@@ -23,7 +22,6 @@
from pandas.core.dtypes.missing import isna
from pandas.core import ops
-from pandas.core.arraylike import OpsMixin
from .masked import BaseMaskedArray, BaseMaskedDtype
@@ -203,7 +201,7 @@ def coerce_to_array(
return values, mask
-class BooleanArray(OpsMixin, BaseMaskedArray):
+class BooleanArray(BaseMaskedArray):
"""
Array of boolean (True/False) data with missing values.
@@ -561,48 +559,40 @@ def all(self, skipna: bool = True, **kwargs):
else:
return self.dtype.na_value
- @classmethod
- def _create_logical_method(cls, op):
- @ops.unpack_zerodim_and_defer(op.__name__)
- def logical_method(self, other):
-
- assert op.__name__ in {"or_", "ror_", "and_", "rand_", "xor", "rxor"}
- other_is_booleanarray = isinstance(other, BooleanArray)
- other_is_scalar = lib.is_scalar(other)
- mask = None
-
- if other_is_booleanarray:
- other, mask = other._data, other._mask
- elif is_list_like(other):
- other = np.asarray(other, dtype="bool")
- if other.ndim > 1:
- raise NotImplementedError(
- "can only perform ops with 1-d structures"
- )
- other, mask = coerce_to_array(other, copy=False)
- elif isinstance(other, np.bool_):
- other = other.item()
-
- if other_is_scalar and not (other is libmissing.NA or lib.is_bool(other)):
- raise TypeError(
- "'other' should be pandas.NA or a bool. "
- f"Got {type(other).__name__} instead."
- )
-
- if not other_is_scalar and len(self) != len(other):
- raise ValueError("Lengths must match to compare")
+ def _logical_method(self, other, op):
+
+ assert op.__name__ in {"or_", "ror_", "and_", "rand_", "xor", "rxor"}
+ other_is_booleanarray = isinstance(other, BooleanArray)
+ other_is_scalar = lib.is_scalar(other)
+ mask = None
+
+ if other_is_booleanarray:
+ other, mask = other._data, other._mask
+ elif is_list_like(other):
+ other = np.asarray(other, dtype="bool")
+ if other.ndim > 1:
+ raise NotImplementedError("can only perform ops with 1-d structures")
+ other, mask = coerce_to_array(other, copy=False)
+ elif isinstance(other, np.bool_):
+ other = other.item()
- if op.__name__ in {"or_", "ror_"}:
- result, mask = ops.kleene_or(self._data, other, self._mask, mask)
- elif op.__name__ in {"and_", "rand_"}:
- result, mask = ops.kleene_and(self._data, other, self._mask, mask)
- elif op.__name__ in {"xor", "rxor"}:
- result, mask = ops.kleene_xor(self._data, other, self._mask, mask)
+ if other_is_scalar and not (other is libmissing.NA or lib.is_bool(other)):
+ raise TypeError(
+ "'other' should be pandas.NA or a bool. "
+ f"Got {type(other).__name__} instead."
+ )
- return BooleanArray(result, mask)
+ if not other_is_scalar and len(self) != len(other):
+ raise ValueError("Lengths must match to compare")
- name = f"__{op.__name__}__"
- return set_function_name(logical_method, name, cls)
+ if op.__name__ in {"or_", "ror_"}:
+ result, mask = ops.kleene_or(self._data, other, self._mask, mask)
+ elif op.__name__ in {"and_", "rand_"}:
+ result, mask = ops.kleene_and(self._data, other, self._mask, mask)
+ elif op.__name__ in {"xor", "rxor"}:
+ result, mask = ops.kleene_xor(self._data, other, self._mask, mask)
+
+ return BooleanArray(result, mask)
def _cmp_method(self, other, op):
from pandas.arrays import FloatingArray, IntegerArray
@@ -643,6 +633,50 @@ def _cmp_method(self, other, op):
return BooleanArray(result, mask, copy=False)
+ def _arith_method(self, other, op):
+ mask = None
+ op_name = op.__name__
+
+ if isinstance(other, BooleanArray):
+ other, mask = other._data, other._mask
+
+ elif is_list_like(other):
+ other = np.asarray(other)
+ if other.ndim > 1:
+ raise NotImplementedError("can only perform ops with 1-d structures")
+ if len(self) != len(other):
+ raise ValueError("Lengths must match")
+
+ # nans propagate
+ if mask is None:
+ mask = self._mask
+ if other is libmissing.NA:
+ mask |= True
+ else:
+ mask = self._mask | mask
+
+ if other is libmissing.NA:
+ # if other is NA, the result will be all NA and we can't run the
+ # actual op, so we need to choose the resulting dtype manually
+ if op_name in {"floordiv", "rfloordiv", "mod", "rmod", "pow", "rpow"}:
+ dtype = "int8"
+ else:
+ dtype = "bool"
+ result = np.zeros(len(self._data), dtype=dtype)
+ else:
+ with np.errstate(all="ignore"):
+ result = op(self._data, other)
+
+ # divmod returns a tuple
+ if op_name == "divmod":
+ div, mod = result
+ return (
+ self._maybe_mask_result(div, mask, other, "floordiv"),
+ self._maybe_mask_result(mod, mask, other, "mod"),
+ )
+
+ return self._maybe_mask_result(result, mask, other, op_name)
+
def _reduce(self, name: str, skipna: bool = True, **kwargs):
if name in {"any", "all"}:
@@ -678,60 +712,3 @@ def _maybe_mask_result(self, result, mask, other, op_name: str):
else:
result[mask] = np.nan
return result
-
- @classmethod
- def _create_arithmetic_method(cls, op):
- op_name = op.__name__
-
- @ops.unpack_zerodim_and_defer(op_name)
- def boolean_arithmetic_method(self, other):
- mask = None
-
- if isinstance(other, BooleanArray):
- other, mask = other._data, other._mask
-
- elif is_list_like(other):
- other = np.asarray(other)
- if other.ndim > 1:
- raise NotImplementedError(
- "can only perform ops with 1-d structures"
- )
- if len(self) != len(other):
- raise ValueError("Lengths must match")
-
- # nans propagate
- if mask is None:
- mask = self._mask
- if other is libmissing.NA:
- mask |= True
- else:
- mask = self._mask | mask
-
- if other is libmissing.NA:
- # if other is NA, the result will be all NA and we can't run the
- # actual op, so we need to choose the resulting dtype manually
- if op_name in {"floordiv", "rfloordiv", "mod", "rmod", "pow", "rpow"}:
- dtype = "int8"
- else:
- dtype = "bool"
- result = np.zeros(len(self._data), dtype=dtype)
- else:
- with np.errstate(all="ignore"):
- result = op(self._data, other)
-
- # divmod returns a tuple
- if op_name == "divmod":
- div, mod = result
- return (
- self._maybe_mask_result(div, mask, other, "floordiv"),
- self._maybe_mask_result(mod, mask, other, "mod"),
- )
-
- return self._maybe_mask_result(result, mask, other, op_name)
-
- name = f"__{op_name}__"
- return set_function_name(boolean_arithmetic_method, name, cls)
-
-
-BooleanArray._add_logical_ops()
-BooleanArray._add_arithmetic_ops()
diff --git a/pandas/core/arrays/floating.py b/pandas/core/arrays/floating.py
index aa272f13b045c..02f434342191f 100644
--- a/pandas/core/arrays/floating.py
+++ b/pandas/core/arrays/floating.py
@@ -6,7 +6,6 @@
from pandas._libs import lib, missing as libmissing
from pandas._typing import ArrayLike, DtypeObj
-from pandas.compat import set_function_name
from pandas.compat.numpy import function as nv
from pandas.util._decorators import cache_readonly
@@ -26,9 +25,7 @@
from pandas.core.dtypes.missing import isna
from pandas.core import ops
-from pandas.core.arraylike import OpsMixin
from pandas.core.ops import invalid_comparison
-from pandas.core.ops.common import unpack_zerodim_and_defer
from pandas.core.tools.numeric import to_numeric
from .masked import BaseMaskedArray, BaseMaskedDtype
@@ -202,7 +199,7 @@ def coerce_to_array(
return values, mask
-class FloatingArray(OpsMixin, BaseMaskedArray):
+class FloatingArray(BaseMaskedArray):
"""
Array of floating (optional missing) values.
@@ -479,83 +476,70 @@ def _maybe_mask_result(self, result, mask, other, op_name: str):
return type(self)(result, mask, copy=False)
- @classmethod
- def _create_arithmetic_method(cls, op):
- op_name = op.__name__
-
- @unpack_zerodim_and_defer(op.__name__)
- def floating_arithmetic_method(self, other):
- from pandas.arrays import IntegerArray
-
- omask = None
+ def _arith_method(self, other, op):
+ from pandas.arrays import IntegerArray
- if getattr(other, "ndim", 0) > 1:
- raise NotImplementedError("can only perform ops with 1-d structures")
+ omask = None
- if isinstance(other, (IntegerArray, FloatingArray)):
- other, omask = other._data, other._mask
+ if getattr(other, "ndim", 0) > 1:
+ raise NotImplementedError("can only perform ops with 1-d structures")
- elif is_list_like(other):
- other = np.asarray(other)
- if other.ndim > 1:
- raise NotImplementedError(
- "can only perform ops with 1-d structures"
- )
- if len(self) != len(other):
- raise ValueError("Lengths must match")
- if not (is_float_dtype(other) or is_integer_dtype(other)):
- raise TypeError("can only perform ops with numeric values")
+ if isinstance(other, (IntegerArray, FloatingArray)):
+ other, omask = other._data, other._mask
- else:
- if not (is_float(other) or is_integer(other) or other is libmissing.NA):
- raise TypeError("can only perform ops with numeric values")
+ elif is_list_like(other):
+ other = np.asarray(other)
+ if other.ndim > 1:
+ raise NotImplementedError("can only perform ops with 1-d structures")
+ if len(self) != len(other):
+ raise ValueError("Lengths must match")
+ if not (is_float_dtype(other) or is_integer_dtype(other)):
+ raise TypeError("can only perform ops with numeric values")
- if omask is None:
- mask = self._mask.copy()
- if other is libmissing.NA:
- mask |= True
- else:
- mask = self._mask | omask
-
- if op_name == "pow":
- # 1 ** x is 1.
- mask = np.where((self._data == 1) & ~self._mask, False, mask)
- # x ** 0 is 1.
- if omask is not None:
- mask = np.where((other == 0) & ~omask, False, mask)
- elif other is not libmissing.NA:
- mask = np.where(other == 0, False, mask)
-
- elif op_name == "rpow":
- # 1 ** x is 1.
- if omask is not None:
- mask = np.where((other == 1) & ~omask, False, mask)
- elif other is not libmissing.NA:
- mask = np.where(other == 1, False, mask)
- # x ** 0 is 1.
- mask = np.where((self._data == 0) & ~self._mask, False, mask)
+ else:
+ if not (is_float(other) or is_integer(other) or other is libmissing.NA):
+ raise TypeError("can only perform ops with numeric values")
+ if omask is None:
+ mask = self._mask.copy()
if other is libmissing.NA:
- result = np.ones_like(self._data)
- else:
- with np.errstate(all="ignore"):
- result = op(self._data, other)
-
- # divmod returns a tuple
- if op_name == "divmod":
- div, mod = result
- return (
- self._maybe_mask_result(div, mask, other, "floordiv"),
- self._maybe_mask_result(mod, mask, other, "mod"),
- )
-
- return self._maybe_mask_result(result, mask, other, op_name)
-
- name = f"__{op.__name__}__"
- return set_function_name(floating_arithmetic_method, name, cls)
+ mask |= True
+ else:
+ mask = self._mask | omask
+
+ if op.__name__ == "pow":
+ # 1 ** x is 1.
+ mask = np.where((self._data == 1) & ~self._mask, False, mask)
+ # x ** 0 is 1.
+ if omask is not None:
+ mask = np.where((other == 0) & ~omask, False, mask)
+ elif other is not libmissing.NA:
+ mask = np.where(other == 0, False, mask)
+
+ elif op.__name__ == "rpow":
+ # 1 ** x is 1.
+ if omask is not None:
+ mask = np.where((other == 1) & ~omask, False, mask)
+ elif other is not libmissing.NA:
+ mask = np.where(other == 1, False, mask)
+ # x ** 0 is 1.
+ mask = np.where((self._data == 0) & ~self._mask, False, mask)
+ if other is libmissing.NA:
+ result = np.ones_like(self._data)
+ else:
+ with np.errstate(all="ignore"):
+ result = op(self._data, other)
+
+ # divmod returns a tuple
+ if op.__name__ == "divmod":
+ div, mod = result
+ return (
+ self._maybe_mask_result(div, mask, other, "floordiv"),
+ self._maybe_mask_result(mod, mask, other, "mod"),
+ )
-FloatingArray._add_arithmetic_ops()
+ return self._maybe_mask_result(result, mask, other, op.__name__)
_dtype_docstring = """
diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py
index 856b4bcbda048..88a5a88efe146 100644
--- a/pandas/core/arrays/integer.py
+++ b/pandas/core/arrays/integer.py
@@ -7,7 +7,6 @@
from pandas._libs import Timedelta, iNaT, lib, missing as libmissing
from pandas._typing import ArrayLike, DtypeObj
-from pandas.compat import set_function_name
from pandas.compat.numpy import function as nv
from pandas.util._decorators import cache_readonly
@@ -26,9 +25,7 @@
from pandas.core.dtypes.missing import isna
from pandas.core import ops
-from pandas.core.arraylike import OpsMixin
from pandas.core.ops import invalid_comparison
-from pandas.core.ops.common import unpack_zerodim_and_defer
from pandas.core.tools.numeric import to_numeric
from .masked import BaseMaskedArray, BaseMaskedDtype
@@ -266,7 +263,7 @@ def coerce_to_array(
return values, mask
-class IntegerArray(OpsMixin, BaseMaskedArray):
+class IntegerArray(BaseMaskedArray):
"""
Array of integer (optional missing) values.
@@ -539,6 +536,73 @@ def _cmp_method(self, other, op):
return BooleanArray(result, mask)
+ def _arith_method(self, other, op):
+ op_name = op.__name__
+ omask = None
+
+ if getattr(other, "ndim", 0) > 1:
+ raise NotImplementedError("can only perform ops with 1-d structures")
+
+ if isinstance(other, IntegerArray):
+ other, omask = other._data, other._mask
+
+ elif is_list_like(other):
+ other = np.asarray(other)
+ if other.ndim > 1:
+ raise NotImplementedError("can only perform ops with 1-d structures")
+ if len(self) != len(other):
+ raise ValueError("Lengths must match")
+ if not (is_float_dtype(other) or is_integer_dtype(other)):
+ raise TypeError("can only perform ops with numeric values")
+
+ elif isinstance(other, (timedelta, np.timedelta64)):
+ other = Timedelta(other)
+
+ else:
+ if not (is_float(other) or is_integer(other) or other is libmissing.NA):
+ raise TypeError("can only perform ops with numeric values")
+
+ if omask is None:
+ mask = self._mask.copy()
+ if other is libmissing.NA:
+ mask |= True
+ else:
+ mask = self._mask | omask
+
+ if op_name == "pow":
+ # 1 ** x is 1.
+ mask = np.where((self._data == 1) & ~self._mask, False, mask)
+ # x ** 0 is 1.
+ if omask is not None:
+ mask = np.where((other == 0) & ~omask, False, mask)
+ elif other is not libmissing.NA:
+ mask = np.where(other == 0, False, mask)
+
+ elif op_name == "rpow":
+ # 1 ** x is 1.
+ if omask is not None:
+ mask = np.where((other == 1) & ~omask, False, mask)
+ elif other is not libmissing.NA:
+ mask = np.where(other == 1, False, mask)
+ # x ** 0 is 1.
+ mask = np.where((self._data == 0) & ~self._mask, False, mask)
+
+ if other is libmissing.NA:
+ result = np.ones_like(self._data)
+ else:
+ with np.errstate(all="ignore"):
+ result = op(self._data, other)
+
+ # divmod returns a tuple
+ if op_name == "divmod":
+ div, mod = result
+ return (
+ self._maybe_mask_result(div, mask, other, "floordiv"),
+ self._maybe_mask_result(mod, mask, other, "mod"),
+ )
+
+ return self._maybe_mask_result(result, mask, other, op_name)
+
def sum(self, skipna=True, min_count=0, **kwargs):
nv.validate_sum((), kwargs)
return super()._reduce("sum", skipna=skipna, min_count=min_count)
@@ -581,86 +645,6 @@ def _maybe_mask_result(self, result, mask, other, op_name: str):
return type(self)(result, mask, copy=False)
- @classmethod
- def _create_arithmetic_method(cls, op):
- op_name = op.__name__
-
- @unpack_zerodim_and_defer(op.__name__)
- def integer_arithmetic_method(self, other):
-
- omask = None
-
- if getattr(other, "ndim", 0) > 1:
- raise NotImplementedError("can only perform ops with 1-d structures")
-
- if isinstance(other, IntegerArray):
- other, omask = other._data, other._mask
-
- elif is_list_like(other):
- other = np.asarray(other)
- if other.ndim > 1:
- raise NotImplementedError(
- "can only perform ops with 1-d structures"
- )
- if len(self) != len(other):
- raise ValueError("Lengths must match")
- if not (is_float_dtype(other) or is_integer_dtype(other)):
- raise TypeError("can only perform ops with numeric values")
-
- elif isinstance(other, (timedelta, np.timedelta64)):
- other = Timedelta(other)
-
- else:
- if not (is_float(other) or is_integer(other) or other is libmissing.NA):
- raise TypeError("can only perform ops with numeric values")
-
- if omask is None:
- mask = self._mask.copy()
- if other is libmissing.NA:
- mask |= True
- else:
- mask = self._mask | omask
-
- if op_name == "pow":
- # 1 ** x is 1.
- mask = np.where((self._data == 1) & ~self._mask, False, mask)
- # x ** 0 is 1.
- if omask is not None:
- mask = np.where((other == 0) & ~omask, False, mask)
- elif other is not libmissing.NA:
- mask = np.where(other == 0, False, mask)
-
- elif op_name == "rpow":
- # 1 ** x is 1.
- if omask is not None:
- mask = np.where((other == 1) & ~omask, False, mask)
- elif other is not libmissing.NA:
- mask = np.where(other == 1, False, mask)
- # x ** 0 is 1.
- mask = np.where((self._data == 0) & ~self._mask, False, mask)
-
- if other is libmissing.NA:
- result = np.ones_like(self._data)
- else:
- with np.errstate(all="ignore"):
- result = op(self._data, other)
-
- # divmod returns a tuple
- if op_name == "divmod":
- div, mod = result
- return (
- self._maybe_mask_result(div, mask, other, "floordiv"),
- self._maybe_mask_result(mod, mask, other, "mod"),
- )
-
- return self._maybe_mask_result(result, mask, other, op_name)
-
- name = f"__{op.__name__}__"
- return set_function_name(integer_arithmetic_method, name, cls)
-
-
-IntegerArray._add_arithmetic_ops()
-
_dtype_docstring = """
An ExtensionDtype for {dtype} integer data.
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index 97ade0dc70843..9febba0f544ac 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -19,7 +19,8 @@
from pandas.core import nanops
from pandas.core.algorithms import factorize_array, take
from pandas.core.array_algos import masked_reductions
-from pandas.core.arrays import ExtensionArray, ExtensionOpsMixin
+from pandas.core.arraylike import OpsMixin
+from pandas.core.arrays import ExtensionArray
from pandas.core.indexers import check_array_indexer
if TYPE_CHECKING:
@@ -66,7 +67,7 @@ def construct_array_type(cls) -> Type["BaseMaskedArray"]:
raise NotImplementedError
-class BaseMaskedArray(ExtensionArray, ExtensionOpsMixin):
+class BaseMaskedArray(OpsMixin, ExtensionArray):
"""
Base class for masked arrays (which use _data and _mask to store the data).
diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py
index b5103fb7f9d5d..810a2ce0cfde5 100644
--- a/pandas/core/arrays/numpy_.py
+++ b/pandas/core/arrays/numpy_.py
@@ -11,12 +11,10 @@
from pandas.core.dtypes.dtypes import ExtensionDtype
from pandas.core.dtypes.missing import isna
-from pandas import compat
from pandas.core import nanops, ops
from pandas.core.array_algos import masked_reductions
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays._mixins import NDArrayBackedExtensionArray
-from pandas.core.arrays.base import ExtensionOpsMixin
from pandas.core.strings.object_array import ObjectStringArrayMixin
@@ -118,7 +116,6 @@ def itemsize(self) -> int:
class PandasArray(
OpsMixin,
NDArrayBackedExtensionArray,
- ExtensionOpsMixin,
NDArrayOperatorsMixin,
ObjectStringArrayMixin,
):
@@ -393,15 +390,7 @@ def _cmp_method(self, other, op):
return self._wrap_ndarray_result(result)
return result
- @classmethod
- def _create_arithmetic_method(cls, op):
- @ops.unpack_zerodim_and_defer(op.__name__)
- def arithmetic_method(self, other):
- return self._cmp_method(other, op)
-
- return compat.set_function_name(arithmetic_method, f"__{op.__name__}__", cls)
-
- _create_comparison_method = _create_arithmetic_method
+ _arith_method = _cmp_method
def _wrap_ndarray_result(self, result: np.ndarray):
# If we have timedelta64[ns] result, return a TimedeltaArray instead
@@ -415,6 +404,3 @@ def _wrap_ndarray_result(self, result: np.ndarray):
# ------------------------------------------------------------------------
# String methods interface
_str_na_value = np.nan
-
-
-PandasArray._add_arithmetic_ops()
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py
index 5a66bf522215a..480bae199683f 100644
--- a/pandas/core/arrays/sparse/array.py
+++ b/pandas/core/arrays/sparse/array.py
@@ -14,7 +14,6 @@
from pandas._libs.sparse import BlockIndex, IntIndex, SparseIndex
from pandas._libs.tslibs import NaT
from pandas._typing import Scalar
-import pandas.compat as compat
from pandas.compat.numpy import function as nv
from pandas.errors import PerformanceWarning
@@ -41,7 +40,7 @@
import pandas.core.algorithms as algos
from pandas.core.arraylike import OpsMixin
-from pandas.core.arrays import ExtensionArray, ExtensionOpsMixin
+from pandas.core.arrays import ExtensionArray
from pandas.core.arrays.sparse.dtype import SparseDtype
from pandas.core.base import PandasObject
import pandas.core.common as com
@@ -50,7 +49,6 @@
from pandas.core.missing import interpolate_2d
from pandas.core.nanops import check_below_min_count
import pandas.core.ops as ops
-from pandas.core.ops.common import unpack_zerodim_and_defer
import pandas.io.formats.printing as printing
@@ -196,7 +194,7 @@ def _wrap_result(name, data, sparse_index, fill_value, dtype=None):
)
-class SparseArray(OpsMixin, PandasObject, ExtensionArray, ExtensionOpsMixin):
+class SparseArray(OpsMixin, PandasObject, ExtensionArray):
"""
An ExtensionArray for storing sparse data.
@@ -1388,48 +1386,39 @@ def __abs__(self):
# Ops
# ------------------------------------------------------------------------
- @classmethod
- def _create_arithmetic_method(cls, op):
+ def _arith_method(self, other, op):
op_name = op.__name__
- @unpack_zerodim_and_defer(op_name)
- def sparse_arithmetic_method(self, other):
+ if isinstance(other, SparseArray):
+ return _sparse_array_op(self, other, op, op_name)
- if isinstance(other, SparseArray):
- return _sparse_array_op(self, other, op, op_name)
+ elif is_scalar(other):
+ with np.errstate(all="ignore"):
+ fill = op(_get_fill(self), np.asarray(other))
+ result = op(self.sp_values, other)
- elif is_scalar(other):
- with np.errstate(all="ignore"):
- fill = op(_get_fill(self), np.asarray(other))
- result = op(self.sp_values, other)
-
- if op_name == "divmod":
- left, right = result
- lfill, rfill = fill
- return (
- _wrap_result(op_name, left, self.sp_index, lfill),
- _wrap_result(op_name, right, self.sp_index, rfill),
- )
+ if op_name == "divmod":
+ left, right = result
+ lfill, rfill = fill
+ return (
+ _wrap_result(op_name, left, self.sp_index, lfill),
+ _wrap_result(op_name, right, self.sp_index, rfill),
+ )
- return _wrap_result(op_name, result, self.sp_index, fill)
+ return _wrap_result(op_name, result, self.sp_index, fill)
- else:
- other = np.asarray(other)
- with np.errstate(all="ignore"):
- # TODO: look into _wrap_result
- if len(self) != len(other):
- raise AssertionError(
- f"length mismatch: {len(self)} vs. {len(other)}"
- )
- if not isinstance(other, SparseArray):
- dtype = getattr(other, "dtype", None)
- other = SparseArray(
- other, fill_value=self.fill_value, dtype=dtype
- )
- return _sparse_array_op(self, other, op, op_name)
-
- name = f"__{op.__name__}__"
- return compat.set_function_name(sparse_arithmetic_method, name, cls)
+ else:
+ other = np.asarray(other)
+ with np.errstate(all="ignore"):
+ # TODO: look into _wrap_result
+ if len(self) != len(other):
+ raise AssertionError(
+ f"length mismatch: {len(self)} vs. {len(other)}"
+ )
+ if not isinstance(other, SparseArray):
+ dtype = getattr(other, "dtype", None)
+ other = SparseArray(other, fill_value=self.fill_value, dtype=dtype)
+ return _sparse_array_op(self, other, op, op_name)
def _cmp_method(self, other, op) -> "SparseArray":
if not is_scalar(other) and not isinstance(other, type(self)):
@@ -1489,9 +1478,6 @@ def _formatter(self, boxed=False):
return None
-SparseArray._add_arithmetic_ops()
-
-
def make_sparse(arr: np.ndarray, kind="block", fill_value=None, dtype=None):
"""
Convert ndarray to sparse format
| - [ ] 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/37049 | 2020-10-11T03:15:15Z | 2020-10-11T20:03:29Z | 2020-10-11T20:03:29Z | 2020-10-11T20:19:31Z |
TST: Fix failing test from #37027 | diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index ef7c4be20e22e..63f9a2532fa73 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -832,7 +832,7 @@ def test_datetime_invalid_scalar(self, value, format, infer):
msg = (
"is a bad directive in format|"
- "second must be in 0..59: 00:01:99|"
+ "second must be in 0..59|"
"Given date string not likely a datetime"
)
with pytest.raises(ValueError, match=msg):
@@ -886,7 +886,7 @@ def test_datetime_invalid_index(self, values, format, infer):
msg = (
"is a bad directive in format|"
"Given date string not likely a datetime|"
- "second must be in 0..59: 00:01:99"
+ "second must be in 0..59"
)
with pytest.raises(ValueError, match=msg):
pd.to_datetime(
@@ -1660,7 +1660,11 @@ def test_to_datetime_overflow(self):
# gh-17637
# we are overflowing Timedelta range here
- msg = "Python int too large to convert to C long"
+ msg = (
+ "(Python int too large to convert to C long)|"
+ "(long too big to convert)|"
+ "(int too big to convert)"
+ )
with pytest.raises(OverflowError, match=msg):
date_range(start="1/1/1700", freq="B", periods=100000)
| Part of #30999
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` | https://api.github.com/repos/pandas-dev/pandas/pulls/37048 | 2020-10-11T03:11:57Z | 2020-10-11T13:32:59Z | 2020-10-11T13:32:58Z | 2020-10-11T13:33:48Z |
REF: back IntervalArray by a single ndarray | diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index a06e0c74ec03b..d943fe3df88c5 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -1,5 +1,6 @@
from operator import le, lt
import textwrap
+from typing import TYPE_CHECKING, Optional, Tuple, Union, cast
import numpy as np
@@ -11,6 +12,7 @@
IntervalMixin,
intervals_to_interval_bounds,
)
+from pandas._typing import ArrayLike, Dtype
from pandas.compat.numpy import function as nv
from pandas.util._decorators import Appender
@@ -18,7 +20,9 @@
from pandas.core.dtypes.common import (
is_categorical_dtype,
is_datetime64_any_dtype,
+ is_dtype_equal,
is_float_dtype,
+ is_integer,
is_integer_dtype,
is_interval_dtype,
is_list_like,
@@ -45,6 +49,10 @@
from pandas.core.indexers import check_array_indexer
from pandas.core.indexes.base import ensure_index
+if TYPE_CHECKING:
+ from pandas import Index
+ from pandas.core.arrays import DatetimeArray, TimedeltaArray
+
_interval_shared_docs = {}
_shared_docs_kwargs = dict(
@@ -169,6 +177,17 @@ def __new__(
left = data._left
right = data._right
closed = closed or data.closed
+
+ if dtype is None or data.dtype == dtype:
+ # This path will preserve id(result._combined)
+ # TODO: could also validate dtype before going to simple_new
+ combined = data._combined
+ if copy:
+ combined = combined.copy()
+ result = cls._simple_new(combined, closed=closed)
+ if verify_integrity:
+ result._validate()
+ return result
else:
# don't allow scalars
@@ -186,83 +205,22 @@ def __new__(
)
closed = closed or infer_closed
- return cls._simple_new(
- left,
- right,
- closed,
- copy=copy,
- dtype=dtype,
- verify_integrity=verify_integrity,
- )
+ closed = closed or "right"
+ left, right = _maybe_cast_inputs(left, right, copy, dtype)
+ combined = _get_combined_data(left, right)
+ result = cls._simple_new(combined, closed=closed)
+ if verify_integrity:
+ result._validate()
+ return result
@classmethod
- def _simple_new(
- cls, left, right, closed=None, copy=False, dtype=None, verify_integrity=True
- ):
+ def _simple_new(cls, data, closed="right"):
result = IntervalMixin.__new__(cls)
- closed = closed or "right"
- left = ensure_index(left, copy=copy)
- right = ensure_index(right, copy=copy)
-
- if dtype is not None:
- # GH 19262: dtype must be an IntervalDtype to override inferred
- dtype = pandas_dtype(dtype)
- if not is_interval_dtype(dtype):
- msg = f"dtype must be an IntervalDtype, got {dtype}"
- raise TypeError(msg)
- elif dtype.subtype is not None:
- left = left.astype(dtype.subtype)
- right = right.astype(dtype.subtype)
-
- # coerce dtypes to match if needed
- if is_float_dtype(left) and is_integer_dtype(right):
- right = right.astype(left.dtype)
- elif is_float_dtype(right) and is_integer_dtype(left):
- left = left.astype(right.dtype)
-
- if type(left) != type(right):
- msg = (
- f"must not have differing left [{type(left).__name__}] and "
- f"right [{type(right).__name__}] types"
- )
- raise ValueError(msg)
- elif is_categorical_dtype(left.dtype) or is_string_dtype(left.dtype):
- # GH 19016
- msg = (
- "category, object, and string subtypes are not supported "
- "for IntervalArray"
- )
- raise TypeError(msg)
- elif isinstance(left, ABCPeriodIndex):
- msg = "Period dtypes are not supported, use a PeriodIndex instead"
- raise ValueError(msg)
- elif isinstance(left, ABCDatetimeIndex) and str(left.tz) != str(right.tz):
- msg = (
- "left and right must have the same time zone, got "
- f"'{left.tz}' and '{right.tz}'"
- )
- raise ValueError(msg)
-
- # For dt64/td64 we want DatetimeArray/TimedeltaArray instead of ndarray
- from pandas.core.ops.array_ops import maybe_upcast_datetimelike_array
-
- left = maybe_upcast_datetimelike_array(left)
- left = extract_array(left, extract_numpy=True)
- right = maybe_upcast_datetimelike_array(right)
- right = extract_array(right, extract_numpy=True)
-
- lbase = getattr(left, "_ndarray", left).base
- rbase = getattr(right, "_ndarray", right).base
- if lbase is not None and lbase is rbase:
- # If these share data, then setitem could corrupt our IA
- right = right.copy()
-
- result._left = left
- result._right = right
+ result._combined = data
+ result._left = data[:, 0]
+ result._right = data[:, 1]
result._closed = closed
- if verify_integrity:
- result._validate()
return result
@classmethod
@@ -397,10 +355,16 @@ def from_breaks(cls, breaks, closed="right", copy=False, dtype=None):
def from_arrays(cls, left, right, closed="right", copy=False, dtype=None):
left = maybe_convert_platform_interval(left)
right = maybe_convert_platform_interval(right)
+ if len(left) != len(right):
+ raise ValueError("left and right must have the same length")
- return cls._simple_new(
- left, right, closed, copy=copy, dtype=dtype, verify_integrity=True
- )
+ closed = closed or "right"
+ left, right = _maybe_cast_inputs(left, right, copy, dtype)
+ combined = _get_combined_data(left, right)
+
+ result = cls._simple_new(combined, closed)
+ result._validate()
+ return result
_interval_shared_docs["from_tuples"] = textwrap.dedent(
"""
@@ -506,19 +470,6 @@ def _validate(self):
msg = "left side of interval must be <= right side"
raise ValueError(msg)
- def _shallow_copy(self, left, right):
- """
- Return a new IntervalArray with the replacement attributes
-
- Parameters
- ----------
- left : Index
- Values to be used for the left-side of the intervals.
- right : Index
- Values to be used for the right-side of the intervals.
- """
- return self._simple_new(left, right, closed=self.closed, verify_integrity=False)
-
# ---------------------------------------------------------------------
# Descriptive
@@ -546,18 +497,20 @@ def __len__(self) -> int:
def __getitem__(self, key):
key = check_array_indexer(self, key)
- left = self._left[key]
- right = self._right[key]
- if not isinstance(left, (np.ndarray, ExtensionArray)):
- # scalar
- if is_scalar(left) and isna(left):
+ result = self._combined[key]
+
+ if is_integer(key):
+ left, right = result[0], result[1]
+ if isna(left):
return self._fill_value
return Interval(left, right, self.closed)
- if np.ndim(left) > 1:
+
+ # TODO: need to watch out for incorrectly-reducing getitem
+ if np.ndim(result) > 2:
# GH#30588 multi-dimensional indexer disallowed
raise ValueError("multi-dimensional indexing not allowed")
- return self._shallow_copy(left, right)
+ return type(self)._simple_new(result, closed=self.closed)
def __setitem__(self, key, value):
value_left, value_right = self._validate_setitem_value(value)
@@ -651,7 +604,8 @@ def fillna(self, value=None, method=None, limit=None):
left = self.left.fillna(value=value_left)
right = self.right.fillna(value=value_right)
- return self._shallow_copy(left, right)
+ combined = _get_combined_data(left, right)
+ return type(self)._simple_new(combined, closed=self.closed)
def astype(self, dtype, copy=True):
"""
@@ -693,7 +647,9 @@ def astype(self, dtype, copy=True):
f"Cannot convert {self.dtype} to {dtype}; subtypes are incompatible"
)
raise TypeError(msg) from err
- return self._shallow_copy(new_left, new_right)
+ # TODO: do astype directly on self._combined
+ combined = _get_combined_data(new_left, new_right)
+ return type(self)._simple_new(combined, closed=self.closed)
elif is_categorical_dtype(dtype):
return Categorical(np.asarray(self))
elif isinstance(dtype, StringDtype):
@@ -734,9 +690,11 @@ def _concat_same_type(cls, to_concat):
raise ValueError("Intervals must all be closed on the same side.")
closed = closed.pop()
+ # TODO: will this mess up on dt64tz?
left = np.concatenate([interval.left for interval in to_concat])
right = np.concatenate([interval.right for interval in to_concat])
- return cls._simple_new(left, right, closed=closed, copy=False)
+ combined = _get_combined_data(left, right) # TODO: 1-stage concat
+ return cls._simple_new(combined, closed=closed)
def copy(self):
"""
@@ -746,11 +704,8 @@ def copy(self):
-------
IntervalArray
"""
- left = self._left.copy()
- right = self._right.copy()
- closed = self.closed
- # TODO: Could skip verify_integrity here.
- return type(self).from_arrays(left, right, closed=closed)
+ combined = self._combined.copy()
+ return type(self)._simple_new(combined, closed=self.closed)
def isna(self) -> np.ndarray:
return isna(self._left)
@@ -843,7 +798,8 @@ def take(self, indices, allow_fill=False, fill_value=None, axis=None, **kwargs):
self._right, indices, allow_fill=allow_fill, fill_value=fill_right
)
- return self._shallow_copy(left_take, right_take)
+ combined = _get_combined_data(left_take, right_take)
+ return type(self)._simple_new(combined, closed=self.closed)
def _validate_listlike(self, value):
# list-like of intervals
@@ -1170,10 +1126,7 @@ def set_closed(self, closed):
if closed not in VALID_CLOSED:
msg = f"invalid option for 'closed': {closed}"
raise ValueError(msg)
-
- return type(self)._simple_new(
- left=self._left, right=self._right, closed=closed, verify_integrity=False
- )
+ return type(self)._simple_new(self._combined, closed=closed)
_interval_shared_docs[
"is_non_overlapping_monotonic"
@@ -1314,9 +1267,8 @@ def to_tuples(self, na_tuple=True):
@Appender(_extension_array_shared_docs["repeat"] % _shared_docs_kwargs)
def repeat(self, repeats, axis=None):
nv.validate_repeat(tuple(), dict(axis=axis))
- left_repeat = self.left.repeat(repeats)
- right_repeat = self.right.repeat(repeats)
- return self._shallow_copy(left=left_repeat, right=right_repeat)
+ combined = self._combined.repeat(repeats, 0)
+ return type(self)._simple_new(combined, closed=self.closed)
_interval_shared_docs["contains"] = textwrap.dedent(
"""
@@ -1399,3 +1351,92 @@ def maybe_convert_platform_interval(values):
values = np.asarray(values)
return maybe_convert_platform(values)
+
+
+def _maybe_cast_inputs(
+ left_orig: Union["Index", ArrayLike],
+ right_orig: Union["Index", ArrayLike],
+ copy: bool,
+ dtype: Optional[Dtype],
+) -> Tuple["Index", "Index"]:
+ left = ensure_index(left_orig, copy=copy)
+ right = ensure_index(right_orig, copy=copy)
+
+ if dtype is not None:
+ # GH#19262: dtype must be an IntervalDtype to override inferred
+ dtype = pandas_dtype(dtype)
+ if not is_interval_dtype(dtype):
+ msg = f"dtype must be an IntervalDtype, got {dtype}"
+ raise TypeError(msg)
+ dtype = cast(IntervalDtype, dtype)
+ if dtype.subtype is not None:
+ left = left.astype(dtype.subtype)
+ right = right.astype(dtype.subtype)
+
+ # coerce dtypes to match if needed
+ if is_float_dtype(left) and is_integer_dtype(right):
+ right = right.astype(left.dtype)
+ elif is_float_dtype(right) and is_integer_dtype(left):
+ left = left.astype(right.dtype)
+
+ if type(left) != type(right):
+ msg = (
+ f"must not have differing left [{type(left).__name__}] and "
+ f"right [{type(right).__name__}] types"
+ )
+ raise ValueError(msg)
+ elif is_categorical_dtype(left.dtype) or is_string_dtype(left.dtype):
+ # GH#19016
+ msg = (
+ "category, object, and string subtypes are not supported "
+ "for IntervalArray"
+ )
+ raise TypeError(msg)
+ elif isinstance(left, ABCPeriodIndex):
+ msg = "Period dtypes are not supported, use a PeriodIndex instead"
+ raise ValueError(msg)
+ elif isinstance(left, ABCDatetimeIndex) and not is_dtype_equal(
+ left.dtype, right.dtype
+ ):
+ left_arr = cast("DatetimeArray", left._data)
+ right_arr = cast("DatetimeArray", right._data)
+ msg = (
+ "left and right must have the same time zone, got "
+ f"'{left_arr.tz}' and '{right_arr.tz}'"
+ )
+ raise ValueError(msg)
+
+ return left, right
+
+
+def _get_combined_data(
+ left: Union["Index", ArrayLike], right: Union["Index", ArrayLike]
+) -> Union[np.ndarray, "DatetimeArray", "TimedeltaArray"]:
+ # For dt64/td64 we want DatetimeArray/TimedeltaArray instead of ndarray
+ from pandas.core.ops.array_ops import maybe_upcast_datetimelike_array
+
+ left = maybe_upcast_datetimelike_array(left)
+ left = extract_array(left, extract_numpy=True)
+ right = maybe_upcast_datetimelike_array(right)
+ right = extract_array(right, extract_numpy=True)
+
+ lbase = getattr(left, "_ndarray", left).base
+ rbase = getattr(right, "_ndarray", right).base
+ if lbase is not None and lbase is rbase:
+ # If these share data, then setitem could corrupt our IA
+ right = right.copy()
+
+ if isinstance(left, np.ndarray):
+ assert isinstance(right, np.ndarray) # for mypy
+ combined = np.concatenate(
+ [left.reshape(-1, 1), right.reshape(-1, 1)],
+ axis=1,
+ )
+ else:
+ left = cast(Union["DatetimeArray", "TimedeltaArray"], left)
+ right = cast(Union["DatetimeArray", "TimedeltaArray"], right)
+ combined = type(left)._concat_same_type(
+ [left.reshape(-1, 1), right.reshape(-1, 1)],
+ axis=1,
+ )
+ return combined
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index cc47740dba5f2..cb25ef1241ce0 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -896,7 +896,7 @@ def delete(self, loc):
"""
new_left = self.left.delete(loc)
new_right = self.right.delete(loc)
- result = self._data._shallow_copy(new_left, new_right)
+ result = IntervalArray.from_arrays(new_left, new_right, closed=self.closed)
return self._shallow_copy(result)
def insert(self, loc, item):
@@ -918,7 +918,7 @@ def insert(self, loc, item):
new_left = self.left.insert(loc, left_insert)
new_right = self.right.insert(loc, right_insert)
- result = self._data._shallow_copy(new_left, new_right)
+ result = IntervalArray.from_arrays(new_left, new_right, closed=self.closed)
return self._shallow_copy(result)
@Appender(_index_shared_docs["take"] % _index_doc_kwargs)
diff --git a/pandas/tests/base/test_conversion.py b/pandas/tests/base/test_conversion.py
index b5595ba220a15..26ad6fc1c6572 100644
--- a/pandas/tests/base/test_conversion.py
+++ b/pandas/tests/base/test_conversion.py
@@ -241,7 +241,7 @@ def test_numpy_array_all_dtypes(any_numpy_dtype):
(pd.Categorical(["a", "b"]), "_codes"),
(pd.core.arrays.period_array(["2000", "2001"], freq="D"), "_data"),
(pd.core.arrays.integer_array([0, np.nan]), "_data"),
- (IntervalArray.from_breaks([0, 1]), "_left"),
+ (IntervalArray.from_breaks([0, 1]), "_combined"),
(SparseArray([0, 1]), "_sparse_values"),
(DatetimeArray(np.array([1, 2], dtype="datetime64[ns]")), "_data"),
# tz-aware Datetime
diff --git a/pandas/tests/indexes/interval/test_constructors.py b/pandas/tests/indexes/interval/test_constructors.py
index aec7de549744f..c0ca0b415ba8e 100644
--- a/pandas/tests/indexes/interval/test_constructors.py
+++ b/pandas/tests/indexes/interval/test_constructors.py
@@ -266,7 +266,11 @@ def test_left_right_dont_share_data(self):
# GH#36310
breaks = np.arange(5)
result = IntervalIndex.from_breaks(breaks)._data
- assert result._left.base is None or result._left.base is not result._right.base
+ left = result._left
+ right = result._right
+
+ left[:] = 10000
+ assert not (right == 10000).any()
class TestFromTuples(Base):
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
The main motivation here is for perf for methods that current cast to object dtype, including value_counts, set ops, values_for_(argsort|factorize)
Also we get an actually-simple simple_new | https://api.github.com/repos/pandas-dev/pandas/pulls/37047 | 2020-10-11T02:43:36Z | 2020-10-12T23:28:48Z | 2020-10-12T23:28:48Z | 2020-11-18T16:12:44Z |
DOC: Add whatsnew for #36727 | diff --git a/doc/source/whatsnew/v1.1.4.rst b/doc/source/whatsnew/v1.1.4.rst
index cd5f8d3f88466..aa2c77da4ee6f 100644
--- a/doc/source/whatsnew/v1.1.4.rst
+++ b/doc/source/whatsnew/v1.1.4.rst
@@ -19,6 +19,7 @@ Fixed regressions
- Fixed regression where :meth:`DataFrame.agg` would fail with :exc:`TypeError` when passed positional arguments to be passed on to the aggregation function (:issue:`36948`).
- Fixed regression in :class:`RollingGroupby` with ``sort=False`` not being respected (:issue:`36889`)
- Fixed regression in :meth:`Series.astype` converting ``None`` to ``"nan"`` when casting to string (:issue:`36904`)
+- Fixed regression in :class:`RollingGroupby` causing a segmentation fault with Index of dtype object (:issue:`36727`)
.. ---------------------------------------------------------------------------
| xref #36727
Was not quick enough to add a whatsnew with the PR when 1.1.4 whatsnew was merged. | https://api.github.com/repos/pandas-dev/pandas/pulls/37046 | 2020-10-10T23:40:39Z | 2020-10-11T13:44:10Z | 2020-10-11T13:44:10Z | 2020-10-12T19:01:29Z |
MYPY: Delete unnecessary unused type hint | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 3ad9f195c3cae..1cea817abbaa3 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -496,9 +496,7 @@ def maybe_casted_values(index, codes=None):
values, _ = maybe_upcast_putmask(values, mask, np.nan)
if issubclass(values_type, DatetimeLikeArrayMixin):
- values = values_type(
- values, dtype=values_dtype
- ) # type: ignore[call-arg]
+ values = values_type(values, dtype=values_dtype)
return values
| cc @jreback | https://api.github.com/repos/pandas-dev/pandas/pulls/37045 | 2020-10-10T23:29:24Z | 2020-10-11T02:21:54Z | 2020-10-11T02:21:53Z | 2020-10-11T09:55:51Z |
REF/TYP: use OpsMixin for DataFrame | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 0314bdc4ee8ed..43c87cc919980 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -124,6 +124,7 @@
relabel_result,
transform,
)
+from pandas.core.arraylike import OpsMixin
from pandas.core.arrays import Categorical, ExtensionArray
from pandas.core.arrays.sparse import SparseFrameAccessor
from pandas.core.construction import extract_array
@@ -336,7 +337,7 @@
# DataFrame class
-class DataFrame(NDFrame):
+class DataFrame(NDFrame, OpsMixin):
"""
Two-dimensional, size-mutable, potentially heterogeneous tabular data.
@@ -5838,7 +5839,87 @@ def reorder_levels(self, order, axis=0) -> DataFrame:
return result
# ----------------------------------------------------------------------
- # Arithmetic / combination related
+ # Arithmetic Methods
+
+ def _cmp_method(self, other, op):
+ axis = 1 # only relevant for Series other case
+
+ self, other = ops.align_method_FRAME(self, other, axis, flex=False, level=None)
+
+ # See GH#4537 for discussion of scalar op behavior
+ new_data = self._dispatch_frame_op(other, op, axis=axis)
+ return self._construct_result(new_data)
+
+ def _arith_method(self, other, op):
+ if ops.should_reindex_frame_op(self, other, op, 1, 1, None, None):
+ return ops.frame_arith_method_with_reindex(self, other, op)
+
+ axis = 1 # only relevant for Series other case
+
+ self, other = ops.align_method_FRAME(self, other, axis, flex=True, level=None)
+
+ new_data = self._dispatch_frame_op(other, op, axis=axis)
+ return self._construct_result(new_data)
+
+ _logical_method = _arith_method
+
+ def _dispatch_frame_op(self, right, func, axis: Optional[int] = None):
+ """
+ Evaluate the frame operation func(left, right) by evaluating
+ column-by-column, dispatching to the Series implementation.
+
+ Parameters
+ ----------
+ right : scalar, Series, or DataFrame
+ func : arithmetic or comparison operator
+ axis : {None, 0, 1}
+
+ Returns
+ -------
+ DataFrame
+ """
+ # Get the appropriate array-op to apply to each column/block's values.
+ array_op = ops.get_array_op(func)
+
+ right = lib.item_from_zerodim(right)
+ if not is_list_like(right):
+ # i.e. scalar, faster than checking np.ndim(right) == 0
+ bm = self._mgr.apply(array_op, right=right)
+ return type(self)(bm)
+
+ elif isinstance(right, DataFrame):
+ assert self.index.equals(right.index)
+ assert self.columns.equals(right.columns)
+ # TODO: The previous assertion `assert right._indexed_same(self)`
+ # fails in cases with empty columns reached via
+ # _frame_arith_method_with_reindex
+
+ bm = self._mgr.operate_blockwise(right._mgr, array_op)
+ return type(self)(bm)
+
+ elif isinstance(right, Series) and axis == 1:
+ # axis=1 means we want to operate row-by-row
+ assert right.index.equals(self.columns)
+
+ right = right._values
+ # maybe_align_as_frame ensures we do not have an ndarray here
+ assert not isinstance(right, np.ndarray)
+
+ arrays = [array_op(l, r) for l, r in zip(self._iter_column_arrays(), right)]
+
+ elif isinstance(right, Series):
+ assert right.index.equals(self.index) # Handle other cases later
+ right = right._values
+
+ arrays = [array_op(l, right) for l in self._iter_column_arrays()]
+
+ else:
+ # Remaining cases have less-obvious dispatch rules
+ raise NotImplementedError(right)
+
+ return type(self)._from_arrays(
+ arrays, self.columns, self.index, verify_integrity=False
+ )
def _combine_frame(self, other: DataFrame, func, fill_value=None):
# at this point we have `self._indexed_same(other)`
@@ -5857,7 +5938,7 @@ def _arith_op(left, right):
left, right = ops.fill_binop(left, right, fill_value)
return func(left, right)
- new_data = ops.dispatch_to_series(self, other, _arith_op)
+ new_data = self._dispatch_frame_op(other, _arith_op)
return new_data
def _construct_result(self, result) -> DataFrame:
@@ -5879,6 +5960,9 @@ def _construct_result(self, result) -> DataFrame:
out.index = self.index
return out
+ # ----------------------------------------------------------------------
+ # Combination-Related
+
@Appender(
"""
Returns
@@ -7254,7 +7338,7 @@ def diff(self, periods: int = 1, axis: Axis = 0) -> DataFrame:
bm_axis = self._get_block_manager_axis(axis)
if bm_axis == 0 and periods != 0:
- return self - self.shift(periods, axis=axis) # type: ignore[operator]
+ return self - self.shift(periods, axis=axis)
new_data = self._mgr.diff(n=periods, axis=bm_axis)
return self._constructor(new_data)
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py
index b656aef64cde9..87da8f8fa146c 100644
--- a/pandas/core/ops/__init__.py
+++ b/pandas/core/ops/__init__.py
@@ -4,12 +4,11 @@
This is not a public API.
"""
import operator
-from typing import TYPE_CHECKING, Optional, Set, Type
+from typing import TYPE_CHECKING, Optional, Set
import warnings
import numpy as np
-from pandas._libs import lib
from pandas._libs.ops_dispatch import maybe_dispatch_ufunc_to_dunder_op # noqa:F401
from pandas._typing import Level
from pandas.util._decorators import Appender
@@ -28,7 +27,6 @@
)
from pandas.core.ops.common import unpack_zerodim_and_defer # noqa:F401
from pandas.core.ops.docstrings import (
- _arith_doc_FRAME,
_flex_comp_doc_FRAME,
_make_flex_doc,
_op_descriptions,
@@ -143,29 +141,6 @@ def _maybe_match_name(a, b):
return None
-# -----------------------------------------------------------------------------
-
-
-def _get_op_name(op, special: bool) -> str:
- """
- Find the name to attach to this method according to conventions
- for special and non-special methods.
-
- Parameters
- ----------
- op : binary operator
- special : bool
-
- Returns
- -------
- op_name : str
- """
- opname = op.__name__.strip("_")
- if special:
- opname = f"__{opname}__"
- return opname
-
-
# -----------------------------------------------------------------------------
# Masking NA values and fallbacks for operations numpy does not support
@@ -211,70 +186,6 @@ def fill_binop(left, right, fill_value):
return left, right
-# -----------------------------------------------------------------------------
-# Dispatch logic
-
-
-def dispatch_to_series(left, right, func, axis: Optional[int] = None):
- """
- Evaluate the frame operation func(left, right) by evaluating
- column-by-column, dispatching to the Series implementation.
-
- Parameters
- ----------
- left : DataFrame
- right : scalar, Series, or DataFrame
- func : arithmetic or comparison operator
- axis : {None, 0, 1}
-
- Returns
- -------
- DataFrame
- """
- # Get the appropriate array-op to apply to each column/block's values.
- array_op = get_array_op(func)
-
- right = lib.item_from_zerodim(right)
- if not is_list_like(right):
- # i.e. scalar, faster than checking np.ndim(right) == 0
- bm = left._mgr.apply(array_op, right=right)
- return type(left)(bm)
-
- elif isinstance(right, ABCDataFrame):
- assert left.index.equals(right.index)
- assert left.columns.equals(right.columns)
- # TODO: The previous assertion `assert right._indexed_same(left)`
- # fails in cases with empty columns reached via
- # _frame_arith_method_with_reindex
-
- bm = left._mgr.operate_blockwise(right._mgr, array_op)
- return type(left)(bm)
-
- elif isinstance(right, ABCSeries) and axis == 1:
- # axis=1 means we want to operate row-by-row
- assert right.index.equals(left.columns)
-
- right = right._values
- # maybe_align_as_frame ensures we do not have an ndarray here
- assert not isinstance(right, np.ndarray)
-
- arrays = [array_op(l, r) for l, r in zip(left._iter_column_arrays(), right)]
-
- elif isinstance(right, ABCSeries):
- assert right.index.equals(left.index) # Handle other cases later
- right = right._values
-
- arrays = [array_op(l, right) for l in left._iter_column_arrays()]
-
- else:
- # Remaining cases have less-obvious dispatch rules
- raise NotImplementedError(right)
-
- return type(left)._from_arrays(
- arrays, left.columns, left.index, verify_integrity=False
- )
-
-
# -----------------------------------------------------------------------------
# Series
@@ -299,9 +210,8 @@ def align_method_SERIES(left: "Series", right, align_asobject: bool = False):
return left, right
-def flex_method_SERIES(cls, op, special):
- assert not special # "special" also means "not flex"
- name = _get_op_name(op, special)
+def flex_method_SERIES(op):
+ name = op.__name__.strip("_")
doc = _make_flex_doc(name, "series")
@Appender(doc)
@@ -427,7 +337,7 @@ def to_series(right):
"Do `left, right = left.align(right, axis=1, copy=False)` "
"before e.g. `left == right`",
FutureWarning,
- stacklevel=3,
+ stacklevel=5,
)
left, right = left.align(
@@ -438,7 +348,7 @@ def to_series(right):
return left, right
-def _should_reindex_frame_op(
+def should_reindex_frame_op(
left: "DataFrame", right, op, axis, default_axis, fill_value, level
) -> bool:
"""
@@ -464,7 +374,7 @@ def _should_reindex_frame_op(
return False
-def _frame_arith_method_with_reindex(
+def frame_arith_method_with_reindex(
left: "DataFrame", right: "DataFrame", op
) -> "DataFrame":
"""
@@ -533,10 +443,9 @@ def _maybe_align_series_as_frame(frame: "DataFrame", series: "Series", axis: int
return type(frame)(rvalues, index=frame.index, columns=frame.columns)
-def flex_arith_method_FRAME(cls: Type["DataFrame"], op, special: bool):
- assert not special
- op_name = _get_op_name(op, special)
- default_axis = None if special else "columns"
+def flex_arith_method_FRAME(op):
+ op_name = op.__name__.strip("_")
+ default_axis = "columns"
na_op = get_array_op(op)
doc = _make_flex_doc(op_name, "dataframe")
@@ -544,10 +453,10 @@ def flex_arith_method_FRAME(cls: Type["DataFrame"], op, special: bool):
@Appender(doc)
def f(self, other, axis=default_axis, level=None, fill_value=None):
- if _should_reindex_frame_op(
+ if should_reindex_frame_op(
self, other, op, axis, default_axis, fill_value, level
):
- return _frame_arith_method_with_reindex(self, other, op)
+ return frame_arith_method_with_reindex(self, other, op)
if isinstance(other, ABCSeries) and fill_value is not None:
# TODO: We could allow this in cases where we end up going
@@ -563,37 +472,14 @@ def f(self, other, axis=default_axis, level=None, fill_value=None):
new_data = self._combine_frame(other, na_op, fill_value)
elif isinstance(other, ABCSeries):
- new_data = dispatch_to_series(self, other, op, axis=axis)
+ new_data = self._dispatch_frame_op(other, op, axis=axis)
else:
# in this case we always have `np.ndim(other) == 0`
if fill_value is not None:
self = self.fillna(fill_value)
- new_data = dispatch_to_series(self, other, op)
-
- return self._construct_result(new_data)
-
- f.__name__ = op_name
-
- return f
-
+ new_data = self._dispatch_frame_op(other, op)
-def arith_method_FRAME(cls: Type["DataFrame"], op, special: bool):
- assert special
- op_name = _get_op_name(op, special)
- doc = _arith_doc_FRAME % op_name
-
- @Appender(doc)
- def f(self, other):
-
- if _should_reindex_frame_op(self, other, op, 1, 1, None, None):
- return _frame_arith_method_with_reindex(self, other, op)
-
- axis = 1 # only relevant for Series other case
-
- self, other = align_method_FRAME(self, other, axis, flex=True, level=None)
-
- new_data = dispatch_to_series(self, other, op, axis=axis)
return self._construct_result(new_data)
f.__name__ = op_name
@@ -601,9 +487,8 @@ def f(self, other):
return f
-def flex_comp_method_FRAME(cls: Type["DataFrame"], op, special: bool):
- assert not special # "special" also means "not flex"
- op_name = _get_op_name(op, special)
+def flex_comp_method_FRAME(op):
+ op_name = op.__name__.strip("_")
default_axis = "columns" # because we are "flex"
doc = _flex_comp_doc_FRAME.format(
@@ -616,26 +501,7 @@ def f(self, other, axis=default_axis, level=None):
self, other = align_method_FRAME(self, other, axis, flex=True, level=level)
- new_data = dispatch_to_series(self, other, op, axis=axis)
- return self._construct_result(new_data)
-
- f.__name__ = op_name
-
- return f
-
-
-def comp_method_FRAME(cls: Type["DataFrame"], op, special: bool):
- assert special # "special" also means "not flex"
- op_name = _get_op_name(op, special)
-
- @Appender(f"Wrapper for comparison method {op_name}")
- def f(self, other):
- axis = 1 # only relevant for Series other case
-
- self, other = align_method_FRAME(self, other, axis, flex=False, level=None)
-
- # See GH#4537 for discussion of scalar op behavior
- new_data = dispatch_to_series(self, other, op, axis=axis)
+ new_data = self._dispatch_frame_op(other, op, axis=axis)
return self._construct_result(new_data)
f.__name__ = op_name
diff --git a/pandas/core/ops/methods.py b/pandas/core/ops/methods.py
index 86981f007a678..c05f457f1e4f5 100644
--- a/pandas/core/ops/methods.py
+++ b/pandas/core/ops/methods.py
@@ -7,16 +7,13 @@
from pandas.core.ops.roperator import (
radd,
- rand_,
rdivmod,
rfloordiv,
rmod,
rmul,
- ror_,
rpow,
rsub,
rtruediv,
- rxor,
)
@@ -33,19 +30,10 @@ def _get_method_wrappers(cls):
-------
arith_flex : function or None
comp_flex : function or None
- arith_special : function
- comp_special : function
- bool_special : function
-
- Notes
- -----
- None is only returned for SparseArray
"""
# TODO: make these non-runtime imports once the relevant functions
# are no longer in __init__
from pandas.core.ops import (
- arith_method_FRAME,
- comp_method_FRAME,
flex_arith_method_FRAME,
flex_comp_method_FRAME,
flex_method_SERIES,
@@ -55,16 +43,10 @@ def _get_method_wrappers(cls):
# Just Series
arith_flex = flex_method_SERIES
comp_flex = flex_method_SERIES
- arith_special = None
- comp_special = None
- bool_special = None
elif issubclass(cls, ABCDataFrame):
arith_flex = flex_arith_method_FRAME
comp_flex = flex_comp_method_FRAME
- arith_special = arith_method_FRAME
- comp_special = comp_method_FRAME
- bool_special = arith_method_FRAME
- return arith_flex, comp_flex, arith_special, comp_special, bool_special
+ return arith_flex, comp_flex
def add_special_arithmetic_methods(cls):
@@ -77,12 +59,7 @@ def add_special_arithmetic_methods(cls):
cls : class
special methods will be defined and pinned to this class
"""
- _, _, arith_method, comp_method, bool_method = _get_method_wrappers(cls)
- new_methods = _create_methods(
- cls, arith_method, comp_method, bool_method, special=True
- )
- # inplace operators (I feel like these should get passed an `inplace=True`
- # or just be removed
+ new_methods = {}
def _wrap_inplace_method(method):
"""
@@ -105,45 +82,25 @@ def f(self, other):
f.__name__ = f"__i{name}__"
return f
- if bool_method is None:
- # Series gets bool_method, arith_method via OpsMixin
- new_methods.update(
- dict(
- __iadd__=_wrap_inplace_method(cls.__add__),
- __isub__=_wrap_inplace_method(cls.__sub__),
- __imul__=_wrap_inplace_method(cls.__mul__),
- __itruediv__=_wrap_inplace_method(cls.__truediv__),
- __ifloordiv__=_wrap_inplace_method(cls.__floordiv__),
- __imod__=_wrap_inplace_method(cls.__mod__),
- __ipow__=_wrap_inplace_method(cls.__pow__),
- )
- )
- new_methods.update(
- dict(
- __iand__=_wrap_inplace_method(cls.__and__),
- __ior__=_wrap_inplace_method(cls.__or__),
- __ixor__=_wrap_inplace_method(cls.__xor__),
- )
- )
- else:
- new_methods.update(
- dict(
- __iadd__=_wrap_inplace_method(new_methods["__add__"]),
- __isub__=_wrap_inplace_method(new_methods["__sub__"]),
- __imul__=_wrap_inplace_method(new_methods["__mul__"]),
- __itruediv__=_wrap_inplace_method(new_methods["__truediv__"]),
- __ifloordiv__=_wrap_inplace_method(new_methods["__floordiv__"]),
- __imod__=_wrap_inplace_method(new_methods["__mod__"]),
- __ipow__=_wrap_inplace_method(new_methods["__pow__"]),
- )
+ # wrap methods that we get from OpsMixin
+ new_methods.update(
+ dict(
+ __iadd__=_wrap_inplace_method(cls.__add__),
+ __isub__=_wrap_inplace_method(cls.__sub__),
+ __imul__=_wrap_inplace_method(cls.__mul__),
+ __itruediv__=_wrap_inplace_method(cls.__truediv__),
+ __ifloordiv__=_wrap_inplace_method(cls.__floordiv__),
+ __imod__=_wrap_inplace_method(cls.__mod__),
+ __ipow__=_wrap_inplace_method(cls.__pow__),
)
- new_methods.update(
- dict(
- __iand__=_wrap_inplace_method(new_methods["__and__"]),
- __ior__=_wrap_inplace_method(new_methods["__or__"]),
- __ixor__=_wrap_inplace_method(new_methods["__xor__"]),
- )
+ )
+ new_methods.update(
+ dict(
+ __iand__=_wrap_inplace_method(cls.__and__),
+ __ior__=_wrap_inplace_method(cls.__or__),
+ __ixor__=_wrap_inplace_method(cls.__xor__),
)
+ )
_add_methods(cls, new_methods=new_methods)
@@ -158,10 +115,8 @@ def add_flex_arithmetic_methods(cls):
cls : class
flex methods will be defined and pinned to this class
"""
- flex_arith_method, flex_comp_method, _, _, _ = _get_method_wrappers(cls)
- new_methods = _create_methods(
- cls, flex_arith_method, flex_comp_method, bool_method=None, special=False
- )
+ flex_arith_method, flex_comp_method = _get_method_wrappers(cls)
+ new_methods = _create_methods(cls, flex_arith_method, flex_comp_method)
new_methods.update(
dict(
multiply=new_methods["mul"],
@@ -175,72 +130,52 @@ def add_flex_arithmetic_methods(cls):
_add_methods(cls, new_methods=new_methods)
-def _create_methods(cls, arith_method, comp_method, bool_method, special):
- # creates actual methods based upon arithmetic, comp and bool method
+def _create_methods(cls, arith_method, comp_method):
+ # creates actual flex methods based upon arithmetic, and comp method
# constructors.
have_divmod = issubclass(cls, ABCSeries)
# divmod is available for Series
new_methods = {}
- if arith_method is not None:
- new_methods.update(
- dict(
- add=arith_method(cls, operator.add, special),
- radd=arith_method(cls, radd, special),
- sub=arith_method(cls, operator.sub, special),
- mul=arith_method(cls, operator.mul, special),
- truediv=arith_method(cls, operator.truediv, special),
- floordiv=arith_method(cls, operator.floordiv, special),
- mod=arith_method(cls, operator.mod, special),
- pow=arith_method(cls, operator.pow, special),
- # not entirely sure why this is necessary, but previously was included
- # so it's here to maintain compatibility
- rmul=arith_method(cls, rmul, special),
- rsub=arith_method(cls, rsub, special),
- rtruediv=arith_method(cls, rtruediv, special),
- rfloordiv=arith_method(cls, rfloordiv, special),
- rpow=arith_method(cls, rpow, special),
- rmod=arith_method(cls, rmod, special),
- )
- )
- new_methods["div"] = new_methods["truediv"]
- new_methods["rdiv"] = new_methods["rtruediv"]
- if have_divmod:
- # divmod doesn't have an op that is supported by numexpr
- new_methods["divmod"] = arith_method(cls, divmod, special)
- new_methods["rdivmod"] = arith_method(cls, rdivmod, special)
-
- if comp_method is not None:
- # Series already has this pinned
- new_methods.update(
- dict(
- eq=comp_method(cls, operator.eq, special),
- ne=comp_method(cls, operator.ne, special),
- lt=comp_method(cls, operator.lt, special),
- gt=comp_method(cls, operator.gt, special),
- le=comp_method(cls, operator.le, special),
- ge=comp_method(cls, operator.ge, special),
- )
+
+ new_methods.update(
+ dict(
+ add=arith_method(operator.add),
+ radd=arith_method(radd),
+ sub=arith_method(operator.sub),
+ mul=arith_method(operator.mul),
+ truediv=arith_method(operator.truediv),
+ floordiv=arith_method(operator.floordiv),
+ mod=arith_method(operator.mod),
+ pow=arith_method(operator.pow),
+ rmul=arith_method(rmul),
+ rsub=arith_method(rsub),
+ rtruediv=arith_method(rtruediv),
+ rfloordiv=arith_method(rfloordiv),
+ rpow=arith_method(rpow),
+ rmod=arith_method(rmod),
)
+ )
+ new_methods["div"] = new_methods["truediv"]
+ new_methods["rdiv"] = new_methods["rtruediv"]
+ if have_divmod:
+ # divmod doesn't have an op that is supported by numexpr
+ new_methods["divmod"] = arith_method(divmod)
+ new_methods["rdivmod"] = arith_method(rdivmod)
- if bool_method is not None:
- new_methods.update(
- dict(
- and_=bool_method(cls, operator.and_, special),
- or_=bool_method(cls, operator.or_, special),
- xor=bool_method(cls, operator.xor, special),
- rand_=bool_method(cls, rand_, special),
- ror_=bool_method(cls, ror_, special),
- rxor=bool_method(cls, rxor, special),
- )
+ new_methods.update(
+ dict(
+ eq=comp_method(operator.eq),
+ ne=comp_method(operator.ne),
+ lt=comp_method(operator.lt),
+ gt=comp_method(operator.gt),
+ le=comp_method(operator.le),
+ ge=comp_method(operator.ge),
)
+ )
- if special:
- dunderize = lambda x: f"__{x.strip('_')}__"
- else:
- dunderize = lambda x: x
- new_methods = {dunderize(k): v for k, v in new_methods.items()}
+ new_methods = {k.strip("_"): v for k, v in new_methods.items()}
return new_methods
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
made possible by #36483 | https://api.github.com/repos/pandas-dev/pandas/pulls/37044 | 2020-10-10T22:53:56Z | 2020-10-11T21:00:37Z | 2020-10-11T21:00:37Z | 2020-10-11T21:57:38Z |
ENH: Implement sem for Rolling and Expanding | diff --git a/doc/source/reference/window.rst b/doc/source/reference/window.rst
index 611c0e0f7f160..77697b966df18 100644
--- a/doc/source/reference/window.rst
+++ b/doc/source/reference/window.rst
@@ -32,6 +32,7 @@ Standard moving window functions
Rolling.apply
Rolling.aggregate
Rolling.quantile
+ Rolling.sem
Window.mean
Window.sum
Window.var
@@ -61,6 +62,7 @@ Standard expanding window functions
Expanding.apply
Expanding.aggregate
Expanding.quantile
+ Expanding.sem
Exponentially-weighted moving window functions
----------------------------------------------
diff --git a/doc/source/user_guide/computation.rst b/doc/source/user_guide/computation.rst
index 75fb3380821d8..b24020848b363 100644
--- a/doc/source/user_guide/computation.rst
+++ b/doc/source/user_guide/computation.rst
@@ -328,6 +328,7 @@ We provide a number of common statistical functions:
:meth:`~Rolling.apply`, Generic apply
:meth:`~Rolling.cov`, Sample covariance (binary)
:meth:`~Rolling.corr`, Sample correlation (binary)
+ :meth:`~Rolling.sem`, Standard error of mean
.. _computation.window_variance.caveats:
@@ -938,6 +939,7 @@ Method summary
:meth:`~Expanding.apply`, Generic apply
:meth:`~Expanding.cov`, Sample covariance (binary)
:meth:`~Expanding.corr`, Sample correlation (binary)
+ :meth:`~Expanding.sem`, Standard error of mean
.. note::
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index 2b4b10c39602a..a99ba437b854a 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -191,6 +191,7 @@ Other enhancements
- :meth:`DatetimeIndex.searchsorted`, :meth:`TimedeltaIndex.searchsorted`, :meth:`PeriodIndex.searchsorted`, and :meth:`Series.searchsorted` with datetimelike dtypes will now try to cast string arguments (listlike and scalar) to the matching datetimelike type (:issue:`36346`)
- Added methods :meth:`IntegerArray.prod`, :meth:`IntegerArray.min`, and :meth:`IntegerArray.max` (:issue:`33790`)
- Where possible :meth:`RangeIndex.difference` and :meth:`RangeIndex.symmetric_difference` will return :class:`RangeIndex` instead of :class:`Int64Index` (:issue:`36564`)
+- Added :meth:`Rolling.sem()` and :meth:`Expanding.sem()` to compute the standard error of mean (:issue:`26476`).
.. _whatsnew_120.api_breaking.python:
diff --git a/pandas/core/window/expanding.py b/pandas/core/window/expanding.py
index 319944fd48eae..c24c5d5702764 100644
--- a/pandas/core/window/expanding.py
+++ b/pandas/core/window/expanding.py
@@ -192,6 +192,11 @@ def var(self, ddof=1, *args, **kwargs):
nv.validate_expanding_func("var", args, kwargs)
return super().var(ddof=ddof, **kwargs)
+ @Substitution(name="expanding")
+ @Appender(_shared_docs["sem"])
+ def sem(self, ddof=1, *args, **kwargs):
+ return super().sem(ddof=ddof, **kwargs)
+
@Substitution(name="expanding", func_name="skew")
@Appender(_doc_template)
@Appender(_shared_docs["skew"])
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index 9e829ef774d42..5398c14c8774a 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -1573,6 +1573,59 @@ def skew(self, **kwargs):
"""
)
+ def sem(self, ddof=1, *args, **kwargs):
+ return self.std(*args, **kwargs) / (self.count() - ddof).pow(0.5)
+
+ _shared_docs["sem"] = dedent(
+ """
+ Compute %(name)s standard error of mean.
+
+ Parameters
+ ----------
+
+ ddof : int, default 1
+ Delta Degrees of Freedom. The divisor used in calculations
+ is ``N - ddof``, where ``N`` represents the number of elements.
+
+ *args, **kwargs
+ For NumPy compatibility. No additional arguments are used.
+
+ Returns
+ -------
+ Series or DataFrame
+ Returned object type is determined by the caller of the %(name)s
+ calculation.
+
+ See Also
+ --------
+ pandas.Series.%(name)s : Calling object with Series data.
+ pandas.DataFrame.%(name)s : Calling object with DataFrames.
+ pandas.Series.sem : Equivalent method for Series.
+ pandas.DataFrame.sem : Equivalent method for DataFrame.
+
+ Notes
+ -----
+ A minimum of one period is required for the rolling calculation.
+
+ Examples
+ --------
+ >>> s = pd.Series([0, 1, 2, 3])
+ >>> s.rolling(2, min_periods=1).sem()
+ 0 NaN
+ 1 0.707107
+ 2 0.707107
+ 3 0.707107
+ dtype: float64
+
+ >>> s.expanding().sem()
+ 0 NaN
+ 1 0.707107
+ 2 0.707107
+ 3 0.745356
+ dtype: float64
+ """
+ )
+
def kurt(self, **kwargs):
window_func = self._get_roll_func("roll_kurt")
kwargs.pop("require_min_periods", None)
@@ -2081,6 +2134,11 @@ def var(self, ddof=1, *args, **kwargs):
def skew(self, **kwargs):
return super().skew(**kwargs)
+ @Substitution(name="rolling")
+ @Appender(_shared_docs["sem"])
+ def sem(self, ddof=1, *args, **kwargs):
+ return self.std(*args, **kwargs) / (self.count() - ddof).pow(0.5)
+
_agg_doc = dedent(
"""
Examples
diff --git a/pandas/tests/window/test_expanding.py b/pandas/tests/window/test_expanding.py
index e5006fd391f90..b06a506281047 100644
--- a/pandas/tests/window/test_expanding.py
+++ b/pandas/tests/window/test_expanding.py
@@ -236,3 +236,14 @@ def test_center_deprecate_warning():
with tm.assert_produces_warning(None):
df.expanding()
+
+
+@pytest.mark.parametrize("constructor", ["DataFrame", "Series"])
+def test_expanding_sem(constructor):
+ # GH: 26476
+ obj = getattr(pd, constructor)([0, 1, 2])
+ result = obj.expanding().sem()
+ if isinstance(result, DataFrame):
+ result = pd.Series(result[0].values)
+ expected = pd.Series([np.nan] + [0.707107] * 2)
+ tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/window/test_grouper.py b/pandas/tests/window/test_grouper.py
index 6b80f65c16fa6..034f941462bb5 100644
--- a/pandas/tests/window/test_grouper.py
+++ b/pandas/tests/window/test_grouper.py
@@ -531,3 +531,21 @@ def test_groupby_rolling_count_closed_on(self):
),
)
tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ ("func", "kwargs"),
+ [("rolling", {"window": 2, "min_periods": 1}), ("expanding", {})],
+ )
+ def test_groupby_rolling_sem(self, func, kwargs):
+ # GH: 26476
+ df = pd.DataFrame(
+ [["a", 1], ["a", 2], ["b", 1], ["b", 2], ["b", 3]], columns=["a", "b"]
+ )
+ result = getattr(df.groupby("a"), func)(**kwargs).sem()
+ expected = pd.DataFrame(
+ {"a": [np.nan] * 5, "b": [np.nan, 0.70711, np.nan, 0.70711, 0.70711]},
+ index=pd.MultiIndex.from_tuples(
+ [("a", 0), ("a", 1), ("b", 2), ("b", 3), ("b", 4)], names=["a", None]
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py
index 73831d518032d..a5fbc3c94786c 100644
--- a/pandas/tests/window/test_rolling.py
+++ b/pandas/tests/window/test_rolling.py
@@ -868,3 +868,14 @@ def test_rolling_period_index(index, window, func, values):
result = getattr(ds.rolling(window, closed="left"), func)()
expected = pd.Series(values, index=index)
tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("constructor", ["DataFrame", "Series"])
+def test_rolling_sem(constructor):
+ # GH: 26476
+ obj = getattr(pd, constructor)([0, 1, 2])
+ result = obj.rolling(2, min_periods=1).sem()
+ if isinstance(result, DataFrame):
+ result = pd.Series(result[0].values)
+ expected = pd.Series([np.nan] + [0.707107] * 2)
+ tm.assert_series_equal(result, expected)
| - [x] closes #26476
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
I added sem to the Rolling and Expanding API as mentioned in the issue linked above. | https://api.github.com/repos/pandas-dev/pandas/pulls/37043 | 2020-10-10T22:39:15Z | 2020-10-12T15:30:03Z | 2020-10-12T15:30:03Z | 2020-10-12T19:01:47Z |
DOC: Add summary to interpolate | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 86b6c4a6cf575..5e5a77fe24cb5 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -6838,6 +6838,8 @@ def interpolate(
**kwargs,
) -> Optional[FrameOrSeries]:
"""
+ Fill NaN values using an interpolation method.
+
Please note that only ``method='linear'`` is supported for
DataFrame/Series with a MultiIndex.
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
The interpolate method was missing a short summary. I hope this addition is reasonable. Happy to change it with feedback. | https://api.github.com/repos/pandas-dev/pandas/pulls/37042 | 2020-10-10T22:35:53Z | 2020-10-15T01:45:10Z | 2020-10-15T01:45:10Z | 2020-10-15T01:45:22Z |
CLN: remove unnecessary DatetimeTZBlock.fillna | diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 8346b48539887..ac210ecbaad5f 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -2090,13 +2090,7 @@ def _can_hold_element(self, element: Any) -> bool:
class DatetimeLikeBlockMixin(Block):
"""Mixin class for DatetimeBlock, DatetimeTZBlock, and TimedeltaBlock."""
- @property
- def _holder(self):
- return DatetimeArray
-
- @property
- def fill_value(self):
- return np.datetime64("NaT", "ns")
+ _can_hold_na = True
def get_values(self, dtype=None):
"""
@@ -2162,10 +2156,8 @@ def to_native_types(self, na_rep="NaT", **kwargs):
class DatetimeBlock(DatetimeLikeBlockMixin):
__slots__ = ()
is_datetime = True
-
- @property
- def _can_hold_na(self):
- return True
+ _holder = DatetimeArray
+ fill_value = np.datetime64("NaT", "ns")
def _maybe_coerce_values(self, values):
"""
@@ -2256,15 +2248,16 @@ class DatetimeTZBlock(ExtensionBlock, DatetimeBlock):
is_extension = True
internal_values = Block.internal_values
+
+ _holder = DatetimeBlock._holder
_can_hold_element = DatetimeBlock._can_hold_element
to_native_types = DatetimeBlock.to_native_types
diff = DatetimeBlock.diff
- fill_value = np.datetime64("NaT", "ns")
- array_values = ExtensionBlock.array_values
+ fillna = DatetimeBlock.fillna # i.e. Block.fillna
+ fill_value = DatetimeBlock.fill_value
+ _can_hold_na = DatetimeBlock._can_hold_na
- @property
- def _holder(self):
- return DatetimeArray
+ array_values = ExtensionBlock.array_values
def _maybe_coerce_values(self, values):
"""
@@ -2330,17 +2323,6 @@ def external_values(self):
# return an object-dtype ndarray of Timestamps.
return np.asarray(self.values.astype("datetime64[ns]", copy=False))
- def fillna(self, value, limit=None, inplace=False, downcast=None):
- # We support filling a DatetimeTZ with a `value` whose timezone
- # is different by coercing to object.
- if self._can_hold_element(value):
- return super().fillna(value, limit, inplace, downcast)
-
- # different timezones, or a non-tz
- return self.astype(object).fillna(
- value, limit=limit, inplace=inplace, downcast=downcast
- )
-
def quantile(self, qs, interpolation="linear", axis=0):
naive = self.values.view("M8[ns]")
@@ -2355,11 +2337,9 @@ def quantile(self, qs, interpolation="linear", axis=0):
return self.make_block_same_class(aware, ndim=res_blk.ndim)
-class TimeDeltaBlock(DatetimeLikeBlockMixin, IntBlock):
+class TimeDeltaBlock(DatetimeLikeBlockMixin):
__slots__ = ()
is_timedelta = True
- _can_hold_na = True
- is_numeric = False
fill_value = np.timedelta64("NaT", "ns")
def _maybe_coerce_values(self, values):
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py
index d8ede501568c0..a1b255640a37d 100644
--- a/pandas/core/internals/managers.py
+++ b/pandas/core/internals/managers.py
@@ -1875,7 +1875,7 @@ def _consolidate(blocks):
merged_blocks = _merge_blocks(
list(group_blocks), dtype=dtype, can_consolidate=_can_consolidate
)
- new_blocks = extend_blocks(merged_blocks, new_blocks)
+ new_blocks.extend(merged_blocks)
return new_blocks
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `black pandas`
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
and no need to have TimeDeltaBlock inherit from IntBlock | https://api.github.com/repos/pandas-dev/pandas/pulls/37040 | 2020-10-10T22:14:54Z | 2020-10-11T16:32:34Z | 2020-10-11T16:32:34Z | 2020-10-11T17:36:16Z |
CI: move py39 build to conda #33948 | diff --git a/.travis.yml b/.travis.yml
index 2bf72bd159fc2..1ddd886699d38 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -35,11 +35,6 @@ matrix:
fast_finish: true
include:
- - dist: bionic
- python: 3.9-dev
- env:
- - JOB="3.9-dev" PATTERN="(not slow and not network and not clipboard)"
-
- env:
- JOB="3.8, slow" ENV_FILE="ci/deps/travis-38-slow.yaml" PATTERN="slow" SQL="1"
services:
@@ -94,7 +89,7 @@ install:
script:
- echo "script start"
- echo "$JOB"
- - if [ "$JOB" != "3.9-dev" ]; then source activate pandas-dev; fi
+ - source activate pandas-dev
- ci/run_tests.sh
after_script:
diff --git a/ci/azure/posix.yml b/ci/azure/posix.yml
index 3a9bb14470692..8e44db0b4bcd4 100644
--- a/ci/azure/posix.yml
+++ b/ci/azure/posix.yml
@@ -61,6 +61,11 @@ jobs:
PANDAS_TESTING_MODE: "deprecate"
EXTRA_APT: "xsel"
+ py39:
+ ENV_FILE: ci/deps/azure-39.yaml
+ CONDA_PY: "39"
+ PATTERN: "not slow and not network and not clipboard"
+
steps:
- script: |
if [ "$(uname)" == "Linux" ]; then
diff --git a/ci/build39.sh b/ci/build39.sh
deleted file mode 100755
index faef2be03c2bb..0000000000000
--- a/ci/build39.sh
+++ /dev/null
@@ -1,12 +0,0 @@
-#!/bin/bash -e
-# Special build for python3.9 until numpy puts its own wheels up
-
-pip install --no-deps -U pip wheel setuptools
-pip install cython numpy python-dateutil pytz pytest pytest-xdist hypothesis
-
-python setup.py build_ext -inplace
-python -m pip install --no-build-isolation -e .
-
-python -c "import sys; print(sys.version_info)"
-python -c "import pandas as pd"
-python -c "import hypothesis"
diff --git a/ci/deps/azure-39.yaml b/ci/deps/azure-39.yaml
new file mode 100644
index 0000000000000..67edc83a9d738
--- /dev/null
+++ b/ci/deps/azure-39.yaml
@@ -0,0 +1,17 @@
+name: pandas-dev
+channels:
+ - conda-forge
+dependencies:
+ - python=3.9.*
+
+ # tools
+ - cython>=0.29.21
+ - pytest>=5.0.1
+ - pytest-xdist>=1.21
+ - hypothesis>=3.58.0
+ - pytest-azurepipelines
+
+ # pandas dependencies
+ - numpy
+ - python-dateutil
+ - pytz
diff --git a/ci/setup_env.sh b/ci/setup_env.sh
index 247f809c5fe63..8984fa2d9a9be 100755
--- a/ci/setup_env.sh
+++ b/ci/setup_env.sh
@@ -1,10 +1,5 @@
#!/bin/bash -e
-if [ "$JOB" == "3.9-dev" ]; then
- /bin/bash ci/build39.sh
- exit 0
-fi
-
# edit the locale file if needed
if [[ "$(uname)" == "Linux" && -n "$LC_ALL" ]]; then
echo "Adding locale to the first line of pandas/__init__.py"
| - [x] closes #33948
| https://api.github.com/repos/pandas-dev/pandas/pulls/37039 | 2020-10-10T21:20:55Z | 2020-11-14T02:27:33Z | 2020-11-14T02:27:33Z | 2020-12-05T18:51:43Z |
REF/TYP: define Index methods non-dynamically | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index aece69d49a68b..b3f5fb6f0291a 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -5418,29 +5418,23 @@ def _arith_method(self, other, op):
return (Index(result[0]), Index(result[1]))
return Index(result)
- @classmethod
- def _add_numeric_methods_unary(cls):
- """
- Add in numeric unary methods.
- """
+ def _unary_method(self, op):
+ result = op(self._values)
+ return Index(result, name=self.name)
- def _make_evaluate_unary(op, opstr: str_t):
- def _evaluate_numeric_unary(self):
+ def __abs__(self):
+ return self._unary_method(operator.abs)
- attrs = self._get_attributes_dict()
- return Index(op(self.values), **attrs)
+ def __neg__(self):
+ return self._unary_method(operator.neg)
- _evaluate_numeric_unary.__name__ = opstr
- return _evaluate_numeric_unary
+ def __pos__(self):
+ return self._unary_method(operator.pos)
- setattr(cls, "__neg__", _make_evaluate_unary(operator.neg, "__neg__"))
- setattr(cls, "__pos__", _make_evaluate_unary(operator.pos, "__pos__"))
- setattr(cls, "__abs__", _make_evaluate_unary(np.abs, "__abs__"))
- setattr(cls, "__inv__", _make_evaluate_unary(lambda x: -x, "__inv__"))
-
- @classmethod
- def _add_numeric_methods(cls):
- cls._add_numeric_methods_unary()
+ def __inv__(self):
+ # TODO: why not operator.inv?
+ # TODO: __inv__ vs __invert__?
+ return self._unary_method(lambda x: -x)
def any(self, *args, **kwargs):
"""
@@ -5565,9 +5559,6 @@ def shape(self):
return self._values.shape
-Index._add_numeric_methods()
-
-
def ensure_index_from_sequences(sequences, names=None):
"""
Construct an index from sequences of data.
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 41f046a7f5f8a..2ce4538a63d25 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -3688,43 +3688,32 @@ def isin(self, values, level=None):
return np.zeros(len(levs), dtype=np.bool_)
return levs.isin(values)
- @classmethod
- def _add_numeric_methods_add_sub_disabled(cls):
- """
- Add in the numeric add/sub methods to disable.
- """
- cls.__add__ = make_invalid_op("__add__")
- cls.__radd__ = make_invalid_op("__radd__")
- cls.__iadd__ = make_invalid_op("__iadd__")
- cls.__sub__ = make_invalid_op("__sub__")
- cls.__rsub__ = make_invalid_op("__rsub__")
- cls.__isub__ = make_invalid_op("__isub__")
-
- @classmethod
- def _add_numeric_methods_disabled(cls):
- """
- Add in numeric methods to disable other than add/sub.
- """
- cls.__pow__ = make_invalid_op("__pow__")
- cls.__rpow__ = make_invalid_op("__rpow__")
- cls.__mul__ = make_invalid_op("__mul__")
- cls.__rmul__ = make_invalid_op("__rmul__")
- cls.__floordiv__ = make_invalid_op("__floordiv__")
- cls.__rfloordiv__ = make_invalid_op("__rfloordiv__")
- cls.__truediv__ = make_invalid_op("__truediv__")
- cls.__rtruediv__ = make_invalid_op("__rtruediv__")
- cls.__mod__ = make_invalid_op("__mod__")
- cls.__rmod__ = make_invalid_op("__rmod__")
- cls.__divmod__ = make_invalid_op("__divmod__")
- cls.__rdivmod__ = make_invalid_op("__rdivmod__")
- cls.__neg__ = make_invalid_op("__neg__")
- cls.__pos__ = make_invalid_op("__pos__")
- cls.__abs__ = make_invalid_op("__abs__")
- cls.__inv__ = make_invalid_op("__inv__")
-
-
-MultiIndex._add_numeric_methods_disabled()
-MultiIndex._add_numeric_methods_add_sub_disabled()
+ # ---------------------------------------------------------------
+ # Arithmetic/Numeric Methods - Disabled
+
+ __add__ = make_invalid_op("__add__")
+ __radd__ = make_invalid_op("__radd__")
+ __iadd__ = make_invalid_op("__iadd__")
+ __sub__ = make_invalid_op("__sub__")
+ __rsub__ = make_invalid_op("__rsub__")
+ __isub__ = make_invalid_op("__isub__")
+ __pow__ = make_invalid_op("__pow__")
+ __rpow__ = make_invalid_op("__rpow__")
+ __mul__ = make_invalid_op("__mul__")
+ __rmul__ = make_invalid_op("__rmul__")
+ __floordiv__ = make_invalid_op("__floordiv__")
+ __rfloordiv__ = make_invalid_op("__rfloordiv__")
+ __truediv__ = make_invalid_op("__truediv__")
+ __rtruediv__ = make_invalid_op("__rtruediv__")
+ __mod__ = make_invalid_op("__mod__")
+ __rmod__ = make_invalid_op("__rmod__")
+ __divmod__ = make_invalid_op("__divmod__")
+ __rdivmod__ = make_invalid_op("__rdivmod__")
+ # Unary methods disabled
+ __neg__ = make_invalid_op("__neg__")
+ __pos__ = make_invalid_op("__pos__")
+ __abs__ = make_invalid_op("__abs__")
+ __inv__ = make_invalid_op("__inv__")
def sparsify_labels(label_list, start: int = 0, sentinel=""):
diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py
index 60a206a5344de..385bffa4bc315 100644
--- a/pandas/core/indexes/numeric.py
+++ b/pandas/core/indexes/numeric.py
@@ -275,8 +275,6 @@ def _can_union_without_object_cast(self, other) -> bool:
return other.dtype == "f8" or other.dtype == self.dtype
-Int64Index._add_numeric_methods()
-
_uint64_descr_args = dict(
klass="UInt64Index", ltype="unsigned integer", dtype="uint64", extra=""
)
@@ -321,8 +319,6 @@ def _can_union_without_object_cast(self, other) -> bool:
return other.dtype == "f8" or other.dtype == self.dtype
-UInt64Index._add_numeric_methods()
-
_float64_descr_args = dict(
klass="Float64Index", dtype="float64", ltype="float", extra=""
)
@@ -425,6 +421,3 @@ def isin(self, values, level=None):
def _can_union_without_object_cast(self, other) -> bool:
# See GH#26778, further casting may occur in NumericIndex._union
return is_numeric_dtype(other.dtype)
-
-
-Float64Index._add_numeric_methods()
| - [ ] 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/37038 | 2020-10-10T20:51:01Z | 2020-10-12T15:31:19Z | 2020-10-12T15:31:19Z | 2020-10-12T15:35:13Z |
Fixed metadata propagation in DataFrame.__getitem__ | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index 09cb024cbd95c..b01df3c693b97 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -591,6 +591,7 @@ Other
- Bug in :meth:`DataFrame.replace` and :meth:`Series.replace` incorrectly casting from ``PeriodDtype`` to object dtype (:issue:`34871`)
- Fixed bug in metadata propagation incorrectly copying DataFrame columns as metadata when the column name overlaps with the metadata name (:issue:`37037`)
- Fixed metadata propagation in the :class:`Series.dt`, :class:`Series.str` accessors, :class:`DataFrame.duplicated`, :class:`DataFrame.stack`, :class:`DataFrame.unstack`, :class:`DataFrame.pivot`, :class:`DataFrame.append`, :class:`DataFrame.diff`, :class:`DataFrame.applymap` and :class:`DataFrame.update` methods (:issue:`28283`) (:issue:`37381`)
+- Fixed metadata propagation when selecting columns from a DataFrame with ``DataFrame.__getitem__`` (:issue:`28283`)
- Bug in :meth:`Index.union` behaving differently depending on whether operand is a :class:`Index` or other list-like (:issue:`36384`)
- Passing an array with 2 or more dimensions to the :class:`Series` constructor now raises the more specific ``ValueError``, from a bare ``Exception`` previously (:issue:`35744`)
- Bug in ``accessor.DirNamesMixin``, where ``dir(obj)`` wouldn't show attributes defined on the instance (:issue:`37173`).
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 49e992b14293e..86df327a62b73 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -3777,7 +3777,7 @@ def _get_item_cache(self, item):
loc = self.columns.get_loc(item)
values = self._mgr.iget(loc)
- res = self._box_col_values(values, loc)
+ res = self._box_col_values(values, loc).__finalize__(self)
cache[item] = res
res._set_as_cached(item, self)
diff --git a/pandas/tests/generic/test_duplicate_labels.py b/pandas/tests/generic/test_duplicate_labels.py
index 42745d2a69375..3f7bebd86e983 100644
--- a/pandas/tests/generic/test_duplicate_labels.py
+++ b/pandas/tests/generic/test_duplicate_labels.py
@@ -312,9 +312,7 @@ def test_series_raises(self, func):
pytest.param(
operator.itemgetter(("a", ["A", "A"])), "loc", marks=not_implemented
),
- pytest.param(
- operator.itemgetter((["a", "a"], "A")), "loc", marks=not_implemented
- ),
+ (operator.itemgetter((["a", "a"], "A")), "loc"),
# iloc
(operator.itemgetter([0, 0]), "iloc"),
pytest.param(
diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py
index e38936baca758..ecd70bb415334 100644
--- a/pandas/tests/generic/test_finalize.py
+++ b/pandas/tests/generic/test_finalize.py
@@ -85,18 +85,12 @@
marks=pytest.mark.xfail(reason="Implement binary finalize"),
),
(pd.DataFrame, frame_data, operator.methodcaller("transpose")),
- pytest.param(
- (pd.DataFrame, frame_data, operator.methodcaller("__getitem__", "A")),
- marks=not_implemented_mark,
- ),
+ (pd.DataFrame, frame_data, operator.methodcaller("__getitem__", "A")),
(pd.DataFrame, frame_data, operator.methodcaller("__getitem__", ["A"])),
(pd.DataFrame, frame_data, operator.methodcaller("__getitem__", np.array([True]))),
(pd.DataFrame, ({("A", "a"): [1]},), operator.methodcaller("__getitem__", ["A"])),
(pd.DataFrame, frame_data, operator.methodcaller("query", "A == 1")),
- pytest.param(
- (pd.DataFrame, frame_data, operator.methodcaller("eval", "A + 1")),
- marks=not_implemented_mark,
- ),
+ (pd.DataFrame, frame_data, operator.methodcaller("eval", "A + 1", engine="python")),
(pd.DataFrame, frame_data, operator.methodcaller("select_dtypes", include="int")),
(pd.DataFrame, frame_data, operator.methodcaller("assign", b=1)),
(pd.DataFrame, frame_data, operator.methodcaller("set_axis", ["A"])),
@@ -289,10 +283,7 @@
),
(pd.DataFrame, frame_data, operator.methodcaller("swapaxes", 0, 1)),
(pd.DataFrame, frame_mi_data, operator.methodcaller("droplevel", "A")),
- pytest.param(
- (pd.DataFrame, frame_data, operator.methodcaller("pop", "A")),
- marks=not_implemented_mark,
- ),
+ (pd.DataFrame, frame_data, operator.methodcaller("pop", "A")),
pytest.param(
(pd.DataFrame, frame_data, operator.methodcaller("squeeze")),
marks=not_implemented_mark,
@@ -317,10 +308,7 @@
(pd.DataFrame, frame_data, operator.methodcaller("take", [0, 0])),
(pd.DataFrame, frame_mi_data, operator.methodcaller("xs", "a")),
(pd.Series, (1, mi), operator.methodcaller("xs", "a")),
- pytest.param(
- (pd.DataFrame, frame_data, operator.methodcaller("get", "A")),
- marks=not_implemented_mark,
- ),
+ (pd.DataFrame, frame_data, operator.methodcaller("get", "A")),
(
pd.DataFrame,
frame_data,
@@ -532,6 +520,15 @@ def test_finalize_called(ndframe_method):
assert result.attrs == {"a": 1}
+@not_implemented_mark
+def test_finalize_called_eval_numexpr():
+ pytest.importorskip("numexpr")
+ df = pd.DataFrame({"A": [1, 2]})
+ df.attrs["A"] = 1
+ result = df.eval("A + 1", engine="numexpr")
+ assert result.attrs == {"A": 1}
+
+
# ----------------------------------------------------------------------------
# Binary operations
| xref #28283 | https://api.github.com/repos/pandas-dev/pandas/pulls/37037 | 2020-10-10T18:58:19Z | 2020-11-15T17:27:49Z | 2020-11-15T17:27:49Z | 2020-11-15T17:27:53Z |
CLN: clean libreduction | diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx
index 3a0fda5aed620..9459cd297c758 100644
--- a/pandas/_libs/reduction.pyx
+++ b/pandas/_libs/reduction.pyx
@@ -1,7 +1,5 @@
from copy import copy
-from cython import Py_ssize_t
-
from libc.stdlib cimport free, malloc
import numpy as np
@@ -11,14 +9,14 @@ from numpy cimport int64_t, ndarray
cnp.import_array()
-from pandas._libs cimport util
+from pandas._libs.util cimport is_array, set_array_not_contiguous
from pandas._libs.lib import is_scalar, maybe_convert_objects
cpdef check_result_array(object obj, Py_ssize_t cnt):
- if (util.is_array(obj) or
+ if (is_array(obj) or
(isinstance(obj, list) and len(obj) == cnt) or
getattr(obj, 'shape', None) == (cnt,)):
raise ValueError('Must produce aggregated value')
@@ -33,7 +31,7 @@ cdef class _BaseGrouper:
if (dummy.dtype != self.arr.dtype
and values.dtype != self.arr.dtype):
raise ValueError('Dummy array must be same dtype')
- if util.is_array(values) and not values.flags.contiguous:
+ if is_array(values) and not values.flags.contiguous:
# e.g. Categorical has no `flags` attribute
values = values.copy()
index = dummy.index.values
@@ -106,7 +104,7 @@ cdef class SeriesBinGrouper(_BaseGrouper):
self.f = f
values = series.values
- if util.is_array(values) and not values.flags.c_contiguous:
+ if is_array(values) and not values.flags.c_contiguous:
# e.g. Categorical has no `flags` attribute
values = values.copy('C')
self.arr = values
@@ -204,7 +202,7 @@ cdef class SeriesGrouper(_BaseGrouper):
self.f = f
values = series.values
- if util.is_array(values) and not values.flags.c_contiguous:
+ if is_array(values) and not values.flags.c_contiguous:
# e.g. Categorical has no `flags` attribute
values = values.copy('C')
self.arr = values
@@ -288,9 +286,9 @@ cpdef inline extract_result(object res, bint squeeze=True):
res = res._values
if squeeze and res.ndim == 1 and len(res) == 1:
res = res[0]
- if hasattr(res, 'values') and util.is_array(res.values):
+ if hasattr(res, 'values') and is_array(res.values):
res = res.values
- if util.is_array(res):
+ if is_array(res):
if res.ndim == 0:
res = res.item()
elif squeeze and res.ndim == 1 and len(res) == 1:
@@ -304,7 +302,7 @@ cdef class Slider:
"""
cdef:
ndarray values, buf
- Py_ssize_t stride, orig_len, orig_stride
+ Py_ssize_t stride
char *orig_data
def __init__(self, ndarray values, ndarray buf):
@@ -316,11 +314,9 @@ cdef class Slider:
self.values = values
self.buf = buf
- self.stride = values.strides[0]
+ self.stride = values.strides[0]
self.orig_data = self.buf.data
- self.orig_len = self.buf.shape[0]
- self.orig_stride = self.buf.strides[0]
self.buf.data = self.values.data
self.buf.strides[0] = self.stride
@@ -333,10 +329,8 @@ cdef class Slider:
self.buf.shape[0] = end - start
cdef reset(self):
-
- self.buf.shape[0] = self.orig_len
self.buf.data = self.orig_data
- self.buf.strides[0] = self.orig_stride
+ self.buf.shape[0] = 0
class InvalidApply(Exception):
@@ -408,39 +402,34 @@ cdef class BlockSlider:
"""
Only capable of sliding on axis=0
"""
-
- cdef public:
- object frame, dummy, index
- int nblocks
- Slider idx_slider
- list blocks
-
cdef:
+ object frame, dummy, index, block
+ list blk_values
+ ndarray values
+ Slider idx_slider
char **base_ptrs
+ int nblocks
+ Py_ssize_t i
def __init__(self, object frame):
- cdef:
- Py_ssize_t i
- object b
-
self.frame = frame
self.dummy = frame[:0]
self.index = self.dummy.index
- self.blocks = [b.values for b in self.dummy._mgr.blocks]
+ self.blk_values = [block.values for block in self.dummy._mgr.blocks]
- for x in self.blocks:
- util.set_array_not_contiguous(x)
+ for values in self.blk_values:
+ set_array_not_contiguous(values)
- self.nblocks = len(self.blocks)
+ self.nblocks = len(self.blk_values)
# See the comment in indexes/base.py about _index_data.
# We need this for EA-backed indexes that have a reference to a 1-d
# ndarray like datetime / timedelta / period.
self.idx_slider = Slider(
self.frame.index._index_data, self.dummy.index._index_data)
- self.base_ptrs = <char**>malloc(sizeof(char*) * len(self.blocks))
- for i, block in enumerate(self.blocks):
+ self.base_ptrs = <char**>malloc(sizeof(char*) * self.nblocks)
+ for i, block in enumerate(self.blk_values):
self.base_ptrs[i] = (<ndarray>block).data
def __dealloc__(self):
@@ -450,10 +439,9 @@ cdef class BlockSlider:
cdef:
ndarray arr
Py_ssize_t i
-
# move blocks
for i in range(self.nblocks):
- arr = self.blocks[i]
+ arr = self.blk_values[i]
# axis=1 is the frame's axis=0
arr.data = self.base_ptrs[i] + arr.strides[1] * start
@@ -470,10 +458,8 @@ cdef class BlockSlider:
cdef:
ndarray arr
Py_ssize_t i
-
- # reset blocks
for i in range(self.nblocks):
- arr = self.blocks[i]
+ arr = self.blk_values[i]
# axis=1 is the frame's axis=0
arr.data = self.base_ptrs[i]
| https://api.github.com/repos/pandas-dev/pandas/pulls/37036 | 2020-10-10T18:26:25Z | 2020-10-10T22:21:15Z | 2020-10-10T22:21:15Z | 2022-11-18T02:21:11Z | |
API: reimplement FixedWindowIndexer.get_window_bounds | diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst
index 57e3c9dd66afb..a2067cf78315c 100644
--- a/doc/source/whatsnew/v1.2.0.rst
+++ b/doc/source/whatsnew/v1.2.0.rst
@@ -444,6 +444,7 @@ Groupby/resample/rolling
- Bug in :meth:`Rolling.count` returned ``np.nan`` with :class:`pandas.api.indexers.FixedForwardWindowIndexer` as window, ``min_periods=0`` and only missing values in window (:issue:`35579`)
- Bug where :class:`pandas.core.window.Rolling` produces incorrect window sizes when using a ``PeriodIndex`` (:issue:`34225`)
- Bug in :meth:`RollingGroupby.count` where a ``ValueError`` was raised when specifying the ``closed`` parameter (:issue:`35869`)
+- Bug in :meth:`DataFrame.groupby.rolling` returning wrong values with partial centered window (:issue:`36040`).
Reshaping
^^^^^^^^^
diff --git a/pandas/core/window/indexers.py b/pandas/core/window/indexers.py
index 023f598f606f3..f2bc01438097c 100644
--- a/pandas/core/window/indexers.py
+++ b/pandas/core/window/indexers.py
@@ -78,30 +78,16 @@ def get_window_bounds(
closed: Optional[str] = None,
) -> Tuple[np.ndarray, np.ndarray]:
- start_s = np.zeros(self.window_size, dtype="int64")
- start_e = (
- np.arange(self.window_size, num_values, dtype="int64")
- - self.window_size
- + 1
- )
- start = np.concatenate([start_s, start_e])[:num_values]
-
- end_s = np.arange(self.window_size, dtype="int64") + 1
- end_e = start_e + self.window_size
- end = np.concatenate([end_s, end_e])[:num_values]
-
- if center and self.window_size > 2:
- offset = min((self.window_size - 1) // 2, num_values - 1)
- start_s_buffer = np.roll(start, -offset)[: num_values - offset]
- end_s_buffer = np.roll(end, -offset)[: num_values - offset]
+ if center:
+ offset = (self.window_size - 1) // 2
+ else:
+ offset = 0
- start_e_buffer = np.arange(
- start[-1] + 1, start[-1] + 1 + offset, dtype="int64"
- )
- end_e_buffer = np.array([end[-1]] * offset, dtype="int64")
+ end = np.arange(1 + offset, num_values + 1 + offset, dtype="int64")
+ start = end - self.window_size
- start = np.concatenate([start_s_buffer, start_e_buffer])
- end = np.concatenate([end_s_buffer, end_e_buffer])
+ end = np.clip(end, 0, num_values)
+ start = np.clip(start, 0, num_values)
return start, end
diff --git a/pandas/tests/window/test_grouper.py b/pandas/tests/window/test_grouper.py
index 63bf731e95096..6b80f65c16fa6 100644
--- a/pandas/tests/window/test_grouper.py
+++ b/pandas/tests/window/test_grouper.py
@@ -297,6 +297,33 @@ def test_groupby_rolling_center_center(self):
)
tm.assert_frame_equal(result, expected)
+ @pytest.mark.parametrize("min_periods", [5, 4, 3])
+ def test_groupby_rolling_center_min_periods(self, min_periods):
+ # GH 36040
+ df = pd.DataFrame({"group": ["A"] * 10 + ["B"] * 10, "data": range(20)})
+
+ window_size = 5
+ result = (
+ df.groupby("group")
+ .rolling(window_size, center=True, min_periods=min_periods)
+ .mean()
+ )
+ result = result.reset_index()[["group", "data"]]
+
+ grp_A_mean = [1.0, 1.5, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 7.5, 8.0]
+ grp_B_mean = [x + 10.0 for x in grp_A_mean]
+
+ num_nans = max(0, min_periods - 3) # For window_size of 5
+ nans = [np.nan] * num_nans
+ grp_A_expected = nans + grp_A_mean[num_nans : 10 - num_nans] + nans
+ grp_B_expected = nans + grp_B_mean[num_nans : 10 - num_nans] + nans
+
+ expected = pd.DataFrame(
+ {"group": ["A"] * 10 + ["B"] * 10, "data": grp_A_expected + grp_B_expected}
+ )
+
+ tm.assert_frame_equal(result, expected)
+
def test_groupby_subselect_rolling(self):
# GH 35486
df = DataFrame(
| - [x] closes #36040
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
This PR replaces [36132](https://github.com/pandas-dev/pandas/pull/36132) following @mroeschke's [36567](https://github.com/pandas-dev/pandas/pull/36567).
Originally, my PR was to fix Issue [36040](https://github.com/pandas-dev/pandas/issues/36040). But it appears that Matthew's PR already fixed it! Nonetheless, I still included two things from my previous PR:
1. I added tests to cover the bug outlined in Issue [36040](https://github.com/pandas-dev/pandas/issues/36040).
2. I reimplemented FixedWindowIndexer.get_window_bounds in a way that I believe if a lot more intuitive and simple. Please lmk if you disagree, in which case I could remove this from the PR.
I don't believe any functionality was altered by this PR so I did not include a whatsnew entry | https://api.github.com/repos/pandas-dev/pandas/pulls/37035 | 2020-10-10T15:54:29Z | 2020-10-10T22:30:51Z | 2020-10-10T22:30:51Z | 2020-10-10T22:30:54Z |
REGR: Fix casting of None to str during astype | diff --git a/doc/source/whatsnew/v1.1.4.rst b/doc/source/whatsnew/v1.1.4.rst
index 3ad8d981be2c9..ca58239dccb8d 100644
--- a/doc/source/whatsnew/v1.1.4.rst
+++ b/doc/source/whatsnew/v1.1.4.rst
@@ -17,6 +17,7 @@ Fixed regressions
- Fixed regression where attempting to mutate a :class:`DateOffset` object would no longer raise an ``AttributeError`` (:issue:`36940`)
- Fixed regression where :meth:`DataFrame.agg` would fail with :exc:`TypeError` when passed positional arguments to be passed on to the aggregation function (:issue:`36948`).
- Fixed regression in :class:`RollingGroupby` with ``sort=False`` not being respected (:issue:`36889`)
+- Fixed regression in :meth:`Series.astype` converting ``None`` to ``"nan"`` when casting to string (:issue:`36904`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 48391ab7d9373..e8b72b997cd5d 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -921,7 +921,9 @@ def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
dtype = pandas_dtype(dtype)
if issubclass(dtype.type, str):
- return lib.ensure_string_array(arr.ravel(), skipna=skipna).reshape(arr.shape)
+ return lib.ensure_string_array(
+ arr.ravel(), skipna=skipna, convert_na_value=False
+ ).reshape(arr.shape)
elif is_datetime64_dtype(arr):
if is_object_dtype(dtype):
diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py
index 7449d8d65ef96..eea839c380f0b 100644
--- a/pandas/tests/series/methods/test_astype.py
+++ b/pandas/tests/series/methods/test_astype.py
@@ -1,7 +1,7 @@
import numpy as np
import pytest
-from pandas import Interval, Series, Timestamp, date_range
+from pandas import NA, Interval, Series, Timestamp, date_range
import pandas._testing as tm
@@ -55,3 +55,18 @@ def test_astype_from_float_to_str(self, dtype):
result = s.astype(str)
expected = Series(["0.1"])
tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "value, string_value",
+ [
+ (None, "None"),
+ (np.nan, "nan"),
+ (NA, "<NA>"),
+ ],
+ )
+ def test_astype_to_str_preserves_na(self, value, string_value):
+ # https://github.com/pandas-dev/pandas/issues/36904
+ s = Series(["a", "b", value], dtype=object)
+ result = s.astype(str)
+ expected = Series(["a", "b", string_value], dtype=object)
+ tm.assert_series_equal(result, expected)
| - [x] closes #36904
- [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/37034 | 2020-10-10T15:45:00Z | 2020-10-10T18:24:59Z | 2020-10-10T18:24:59Z | 2020-10-12T14:00:04Z |
CLN: Simplify aggregation.aggregate | diff --git a/pandas/core/aggregation.py b/pandas/core/aggregation.py
index 74359c8831745..ba7638e269fc0 100644
--- a/pandas/core/aggregation.py
+++ b/pandas/core/aggregation.py
@@ -608,92 +608,41 @@ def aggregate(obj, arg: AggFuncType, *args, **kwargs):
from pandas.core.reshape.concat import concat
- def _agg_1dim(name, how, subset=None):
- """
- aggregate a 1-dim with how
- """
- colg = obj._gotitem(name, ndim=1, subset=subset)
- if colg.ndim != 1:
- raise SpecificationError(
- "nested dictionary is ambiguous in aggregation"
- )
- return colg.aggregate(how)
-
- def _agg_2dim(how):
- """
- aggregate a 2-dim with how
- """
- colg = obj._gotitem(obj._selection, ndim=2, subset=selected_obj)
- return colg.aggregate(how)
-
- def _agg(arg, func):
- """
- run the aggregations over the arg with func
- return a dict
- """
- result = {}
- for fname, agg_how in arg.items():
- result[fname] = func(fname, agg_how)
- return result
+ if selected_obj.ndim == 1:
+ # key only used for output
+ colg = obj._gotitem(obj._selection, ndim=1)
+ results = {key: colg.agg(how) for key, how in arg.items()}
+ else:
+ # key used for column selection and output
+ results = {
+ key: obj._gotitem(key, ndim=1).agg(how) for key, how in arg.items()
+ }
# set the final keys
keys = list(arg.keys())
- if obj._selection is not None:
-
- sl = set(obj._selection_list)
-
- # we are a Series like object,
- # but may have multiple aggregations
- if len(sl) == 1:
-
- result = _agg(
- arg, lambda fname, agg_how: _agg_1dim(obj._selection, agg_how)
- )
-
- # we are selecting the same set as we are aggregating
- elif not len(sl - set(keys)):
-
- result = _agg(arg, _agg_1dim)
-
- # we are a DataFrame, with possibly multiple aggregations
- else:
-
- result = _agg(arg, _agg_2dim)
-
- # no selection
- else:
-
- try:
- result = _agg(arg, _agg_1dim)
- except SpecificationError:
-
- # we are aggregating expecting all 1d-returns
- # but we have 2d
- result = _agg(arg, _agg_2dim)
-
# combine results
def is_any_series() -> bool:
# return a boolean if we have *any* nested series
- return any(isinstance(r, ABCSeries) for r in result.values())
+ return any(isinstance(r, ABCSeries) for r in results.values())
def is_any_frame() -> bool:
# return a boolean if we have *any* nested series
- return any(isinstance(r, ABCDataFrame) for r in result.values())
+ return any(isinstance(r, ABCDataFrame) for r in results.values())
- if isinstance(result, list):
- return concat(result, keys=keys, axis=1, sort=True), True
+ if isinstance(results, list):
+ return concat(results, keys=keys, axis=1, sort=True), True
elif is_any_frame():
# we have a dict of DataFrames
# return a MI DataFrame
- keys_to_use = [k for k in keys if not result[k].empty]
+ keys_to_use = [k for k in keys if not results[k].empty]
# Have to check, if at least one DataFrame is not empty.
keys_to_use = keys_to_use if keys_to_use != [] else keys
return (
- concat([result[k] for k in keys_to_use], keys=keys_to_use, axis=1),
+ concat([results[k] for k in keys_to_use], keys=keys_to_use, axis=1),
True,
)
@@ -702,7 +651,7 @@ def is_any_frame() -> bool:
# we have a dict of Series
# return a MI Series
try:
- result = concat(result)
+ result = concat(results)
except TypeError as err:
# we want to give a nice error here if
# we have non-same sized objects, so
@@ -720,7 +669,7 @@ def is_any_frame() -> bool:
from pandas import DataFrame, Series
try:
- result = DataFrame(result)
+ result = DataFrame(results)
except ValueError:
# we have a dict of scalars
@@ -731,7 +680,7 @@ def is_any_frame() -> bool:
else:
name = None
- result = Series(result, name=name)
+ result = Series(results, name=name)
return result, True
elif is_list_like(arg):
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/37033 | 2020-10-10T15:29:54Z | 2020-10-10T23:25:34Z | 2020-10-10T23:25:34Z | 2020-10-11T13:15:21Z |
DOC: Group relevant df.mask/df.where examples together | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 338b45b5503dc..cf9b90ef83749 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -9088,7 +9088,6 @@ def where(
3 3.0
4 4.0
dtype: float64
-
>>> s.mask(s > 0)
0 0.0
1 NaN
@@ -9104,6 +9103,13 @@ def where(
3 3
4 4
dtype: int64
+ >>> s.mask(s > 1, 10)
+ 0 0
+ 1 1
+ 2 10
+ 3 10
+ 4 10
+ dtype: int64
>>> df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B'])
>>> df
| df.mask() and df.where() are complementary and so they share docs, see [here](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.mask.html). I grouped related examples together.
- [x] Close #25187
- [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/37032 | 2020-10-10T15:02:19Z | 2020-10-10T17:26:25Z | 2020-10-10T17:26:25Z | 2020-10-11T02:35:32Z |
DOC: Clarify display.precision | diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py
index bfe20551cbcfc..541ecd9df6fc7 100644
--- a/pandas/core/config_init.py
+++ b/pandas/core/config_init.py
@@ -85,8 +85,9 @@ def use_numba_cb(key):
pc_precision_doc = """
: int
- Floating point output precision (number of significant digits). This is
- only a suggestion
+ Floating point output precision in terms of number of places after the
+ decimal, for regular formatting as well as scientific notation. Similar
+ to ``precision`` in :meth:`numpy.set_printoptions`.
"""
pc_colspace_doc = """
@@ -249,7 +250,7 @@ def use_numba_cb(key):
pc_max_seq_items = """
: int or None
- when pretty-printing a long sequence, no more then `max_seq_items`
+ When pretty-printing a long sequence, no more then `max_seq_items`
will be printed. If items are omitted, they will be denoted by the
addition of "..." to the resulting string.
| - [x] closes #21004
- [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/37030 | 2020-10-10T14:36:37Z | 2020-10-12T15:09:05Z | 2020-10-12T15:09:05Z | 2020-10-17T02:51:06Z |
DOC: Improve what the `axis=` kwarg does for generic methods | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 86b6c4a6cf575..dd1e03056b702 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -10732,7 +10732,7 @@ def all(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs):
@doc(
desc="Return the mean absolute deviation of the values "
- "for the requested axis.",
+ "over the requested axis.",
name1=name1,
name2=name2,
axis_descr=axis_descr,
@@ -10868,7 +10868,7 @@ def cumprod(self, axis=None, skipna=True, *args, **kwargs):
@doc(
_num_doc,
- desc="Return the sum of the values for the requested axis.\n\n"
+ desc="Return the sum of the values over the requested axis.\n\n"
"This is equivalent to the method ``numpy.sum``.",
name1=name1,
name2=name2,
@@ -10894,7 +10894,7 @@ def sum(
@doc(
_num_doc,
- desc="Return the product of the values for the requested axis.",
+ desc="Return the product of the values over the requested axis.",
name1=name1,
name2=name2,
axis_descr=axis_descr,
@@ -10920,7 +10920,7 @@ def prod(
@doc(
_num_doc,
- desc="Return the mean of the values for the requested axis.",
+ desc="Return the mean of the values over the requested axis.",
name1=name1,
name2=name2,
axis_descr=axis_descr,
@@ -10969,7 +10969,7 @@ def kurt(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs):
@doc(
_num_doc,
- desc="Return the median of the values for the requested axis.",
+ desc="Return the median of the values over the requested axis.",
name1=name1,
name2=name2,
axis_descr=axis_descr,
@@ -10986,7 +10986,7 @@ def median(
@doc(
_num_doc,
- desc="Return the maximum of the values for the requested axis.\n\n"
+ desc="Return the maximum of the values over the requested axis.\n\n"
"If you want the *index* of the maximum, use ``idxmax``. This is"
"the equivalent of the ``numpy.ndarray`` method ``argmax``.",
name1=name1,
@@ -11003,7 +11003,7 @@ def max(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs):
@doc(
_num_doc,
- desc="Return the minimum of the values for the requested axis.\n\n"
+ desc="Return the minimum of the values over the requested axis.\n\n"
"If you want the *index* of the minimum, use ``idxmin``. This is"
"the equivalent of the ``numpy.ndarray`` method ``argmin``.",
name1=name1,
| ### [`axis=0` or `axis=1`, which is it?](https://github.com/pandas-dev/pandas/issues/29203#issue-511923432)
Opening a PR to discuss #29203 on what it means to do `df.sum(axis=0)` versus `df.sum(axis=1)`. The docs does not make it intuitively clear to the user. I propose a simple change where **"summing across`axis=0`"** makes it clear that you're summing across indexes (i.e. **column sums**).
- [x] Closes #29203
- [x] Passes pytest
- [x] Passes `black pandas`
- [x] Passes `git diff upstream/master -u -- "*.py" | flake8 --diff` | https://api.github.com/repos/pandas-dev/pandas/pulls/37029 | 2020-10-10T13:04:41Z | 2020-10-12T15:35:01Z | 2020-10-12T15:35:00Z | 2020-10-12T15:35:49Z |
TST: insert 'match' to bare pytest raises in pandas/tests/tools/test_… | diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index 819474e1f32e7..ef7c4be20e22e 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -349,7 +349,9 @@ def test_to_datetime_parse_tzname_or_tzoffset_different_tz_to_utc(self):
def test_to_datetime_parse_timezone_malformed(self, offset):
fmt = "%Y-%m-%d %H:%M:%S %z"
date = "2010-01-01 12:00:00 " + offset
- with pytest.raises(ValueError):
+
+ msg = "does not match format|unconverted data remains"
+ with pytest.raises(ValueError, match=msg):
pd.to_datetime([date], format=fmt)
def test_to_datetime_parse_timezone_keeps_name(self):
@@ -784,17 +786,19 @@ def test_to_datetime_tz_psycopg2(self, cache):
@pytest.mark.parametrize("cache", [True, False])
def test_datetime_bool(self, cache):
# GH13176
- with pytest.raises(TypeError):
+ msg = r"dtype bool cannot be converted to datetime64\[ns\]"
+ with pytest.raises(TypeError, match=msg):
to_datetime(False)
assert to_datetime(False, errors="coerce", cache=cache) is NaT
assert to_datetime(False, errors="ignore", cache=cache) is False
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError, match=msg):
to_datetime(True)
assert to_datetime(True, errors="coerce", cache=cache) is NaT
assert to_datetime(True, errors="ignore", cache=cache) is True
- with pytest.raises(TypeError):
+ msg = f"{type(cache)} is not convertible to datetime"
+ with pytest.raises(TypeError, match=msg):
to_datetime([False, datetime.today()], cache=cache)
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError, match=msg):
to_datetime(["20130101", True], cache=cache)
tm.assert_index_equal(
to_datetime([0, False, NaT, 0.0], errors="coerce", cache=cache),
@@ -805,10 +809,10 @@ def test_datetime_bool(self, cache):
def test_datetime_invalid_datatype(self):
# GH13176
-
- with pytest.raises(TypeError):
+ msg = "is not convertible to datetime"
+ with pytest.raises(TypeError, match=msg):
pd.to_datetime(bool)
- with pytest.raises(TypeError):
+ with pytest.raises(TypeError, match=msg):
pd.to_datetime(pd.to_datetime)
@pytest.mark.parametrize("value", ["a", "00:01:99"])
@@ -826,7 +830,12 @@ def test_datetime_invalid_scalar(self, value, format, infer):
)
assert res is pd.NaT
- with pytest.raises(ValueError):
+ msg = (
+ "is a bad directive in format|"
+ "second must be in 0..59: 00:01:99|"
+ "Given date string not likely a datetime"
+ )
+ with pytest.raises(ValueError, match=msg):
pd.to_datetime(
value, errors="raise", format=format, infer_datetime_format=infer
)
@@ -847,12 +856,14 @@ def test_datetime_outofbounds_scalar(self, value, format, infer):
assert res is pd.NaT
if format is not None:
- with pytest.raises(ValueError):
+ msg = "is a bad directive in format|Out of bounds nanosecond timestamp"
+ with pytest.raises(ValueError, match=msg):
pd.to_datetime(
value, errors="raise", format=format, infer_datetime_format=infer
)
else:
- with pytest.raises(OutOfBoundsDatetime):
+ msg = "Out of bounds nanosecond timestamp"
+ with pytest.raises(OutOfBoundsDatetime, match=msg):
pd.to_datetime(
value, errors="raise", format=format, infer_datetime_format=infer
)
@@ -872,7 +883,12 @@ def test_datetime_invalid_index(self, values, format, infer):
)
tm.assert_index_equal(res, pd.DatetimeIndex([pd.NaT] * len(values)))
- with pytest.raises(ValueError):
+ msg = (
+ "is a bad directive in format|"
+ "Given date string not likely a datetime|"
+ "second must be in 0..59: 00:01:99"
+ )
+ with pytest.raises(ValueError, match=msg):
pd.to_datetime(
values, errors="raise", format=format, infer_datetime_format=infer
)
@@ -1070,7 +1086,8 @@ def test_timestamp_utc_true(self, ts, expected):
@pytest.mark.parametrize("dt_str", ["00010101", "13000101", "30000101", "99990101"])
def test_to_datetime_with_format_out_of_bounds(self, dt_str):
# GH 9107
- with pytest.raises(OutOfBoundsDatetime):
+ msg = "Out of bounds nanosecond timestamp"
+ with pytest.raises(OutOfBoundsDatetime, match=msg):
pd.to_datetime(dt_str, format="%Y%m%d")
def test_to_datetime_utc(self):
@@ -1096,8 +1113,8 @@ class TestToDatetimeUnit:
def test_unit(self, cache):
# GH 11758
# test proper behavior with errors
-
- with pytest.raises(ValueError):
+ msg = "cannot specify both format and unit"
+ with pytest.raises(ValueError, match=msg):
to_datetime([1], unit="D", format="%Y%m%d", cache=cache)
values = [11111111, 1, 1.0, iNaT, NaT, np.nan, "NaT", ""]
@@ -1123,7 +1140,8 @@ def test_unit(self, cache):
)
tm.assert_index_equal(result, expected)
- with pytest.raises(tslib.OutOfBoundsDatetime):
+ msg = "cannot convert input 11111111 with the unit 'D'"
+ with pytest.raises(tslib.OutOfBoundsDatetime, match=msg):
to_datetime(values, unit="D", errors="raise", cache=cache)
values = [1420043460000, iNaT, NaT, np.nan, "NaT"]
@@ -1136,7 +1154,8 @@ def test_unit(self, cache):
expected = DatetimeIndex(["NaT", "NaT", "NaT", "NaT", "NaT"])
tm.assert_index_equal(result, expected)
- with pytest.raises(tslib.OutOfBoundsDatetime):
+ msg = "cannot convert input 1420043460000 with the unit 's'"
+ with pytest.raises(tslib.OutOfBoundsDatetime, match=msg):
to_datetime(values, errors="raise", unit="s", cache=cache)
# if we have a string, then we raise a ValueError
@@ -1204,7 +1223,8 @@ def test_unit_mixed(self, cache):
result = pd.to_datetime(arr, errors="coerce", cache=cache)
tm.assert_index_equal(result, expected)
- with pytest.raises(ValueError):
+ msg = "mixed datetimes and integers in passed array"
+ with pytest.raises(ValueError, match=msg):
pd.to_datetime(arr, errors="raise", cache=cache)
expected = DatetimeIndex(["NaT", "NaT", "2013-01-01"])
@@ -1212,7 +1232,7 @@ def test_unit_mixed(self, cache):
result = pd.to_datetime(arr, errors="coerce", cache=cache)
tm.assert_index_equal(result, expected)
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=msg):
pd.to_datetime(arr, errors="raise", cache=cache)
@pytest.mark.parametrize("cache", [True, False])
@@ -1392,7 +1412,8 @@ def test_dataframe_dtypes(self, cache):
# float
df = DataFrame({"year": [2000, 2001], "month": [1.5, 1], "day": [1, 1]})
- with pytest.raises(ValueError):
+ msg = "cannot assemble the datetimes: unconverted data remains: 1"
+ with pytest.raises(ValueError, match=msg):
to_datetime(df, cache=cache)
def test_dataframe_utc_true(self):
@@ -1500,7 +1521,8 @@ def test_to_datetime_barely_out_of_bounds(self):
# in an in-bounds datetime
arr = np.array(["2262-04-11 23:47:16.854775808"], dtype=object)
- with pytest.raises(OutOfBoundsDatetime):
+ msg = "Out of bounds nanosecond timestamp"
+ with pytest.raises(OutOfBoundsDatetime, match=msg):
to_datetime(arr)
@pytest.mark.parametrize("cache", [True, False])
@@ -1638,7 +1660,8 @@ def test_to_datetime_overflow(self):
# gh-17637
# we are overflowing Timedelta range here
- with pytest.raises(OverflowError):
+ msg = "Python int too large to convert to C long"
+ with pytest.raises(OverflowError, match=msg):
date_range(start="1/1/1700", freq="B", periods=100000)
@pytest.mark.parametrize("cache", [True, False])
@@ -2265,23 +2288,26 @@ def test_julian_round_trip(self):
assert result.to_julian_date() == 2456658
# out-of-bounds
- with pytest.raises(ValueError):
+ msg = "1 is Out of Bounds for origin='julian'"
+ with pytest.raises(ValueError, match=msg):
pd.to_datetime(1, origin="julian", unit="D")
def test_invalid_unit(self, units, julian_dates):
# checking for invalid combination of origin='julian' and unit != D
if units != "D":
- with pytest.raises(ValueError):
+ msg = "unit must be 'D' for origin='julian'"
+ with pytest.raises(ValueError, match=msg):
pd.to_datetime(julian_dates, unit=units, origin="julian")
def test_invalid_origin(self):
# need to have a numeric specified
- with pytest.raises(ValueError):
+ msg = "it must be numeric with a unit specified"
+ with pytest.raises(ValueError, match=msg):
pd.to_datetime("2005-01-01", origin="1960-01-01")
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=msg):
pd.to_datetime("2005-01-01", origin="1960-01-01", unit="D")
def test_epoch(self, units, epochs, epoch_1960, units_from_epochs):
@@ -2304,12 +2330,13 @@ def test_epoch(self, units, epochs, epoch_1960, units_from_epochs):
)
def test_invalid_origins(self, origin, exc, units, units_from_epochs):
- with pytest.raises(exc):
+ msg = f"origin {origin} (is Out of Bounds|cannot be converted to a Timestamp)"
+ with pytest.raises(exc, match=msg):
pd.to_datetime(units_from_epochs, unit=units, origin=origin)
def test_invalid_origins_tzinfo(self):
# GH16842
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match="must be tz-naive"):
pd.to_datetime(1, unit="D", origin=datetime(2000, 1, 1, tzinfo=pytz.utc))
@pytest.mark.parametrize("format", [None, "%Y-%m-%d %H:%M:%S"])
| - [ ] ref https://github.com/pandas-dev/pandas/issues/30999
- [ ] 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/37027 | 2020-10-10T11:22:23Z | 2020-10-10T16:02:08Z | 2020-10-10T16:02:07Z | 2020-10-11T03:12:26Z |
TST: insert 'match' to bare pytest raises in pandas/tests/test_flags.py | diff --git a/pandas/tests/test_flags.py b/pandas/tests/test_flags.py
index f6e3ae4980afb..9294b3fc3319b 100644
--- a/pandas/tests/test_flags.py
+++ b/pandas/tests/test_flags.py
@@ -41,8 +41,8 @@ def test_getitem(self):
flags["allows_duplicate_labels"] = False
assert flags["allows_duplicate_labels"] is False
- with pytest.raises(KeyError):
+ with pytest.raises(KeyError, match="a"):
flags["a"]
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match="a"):
flags["a"] = 10
| - [ ] ref https://github.com/pandas-dev/pandas/issues/30999
- [ ] 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/37026 | 2020-10-10T09:02:17Z | 2020-10-10T16:02:57Z | 2020-10-10T16:02:57Z | 2020-10-10T16:03:01Z |
DOC: Clarified pandas_version in to_json | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 338b45b5503dc..0290f74eb41df 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2274,6 +2274,10 @@ def to_json(
and the default ``indent=None`` are equivalent in pandas, though this
may change in a future release.
+ ``orient='table'`` contains a 'pandas_version' field under 'schema'.
+ This stores the version of `pandas` used in the latest revision of the
+ schema.
+
Examples
--------
>>> import json
| - [X] closes #26637
- [ ] 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/37025 | 2020-10-10T08:35:54Z | 2020-10-14T12:33:58Z | 2020-10-14T12:33:58Z | 2020-10-14T12:46:19Z |
TYP: core/dtypes/cast.py | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index a7379376c2f78..1dce5c2be809b 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -3,7 +3,18 @@
"""
from datetime import date, datetime, timedelta
-from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Type
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ List,
+ Optional,
+ Sequence,
+ Set,
+ Sized,
+ Tuple,
+ Type,
+ Union,
+)
import numpy as np
@@ -18,7 +29,7 @@
ints_to_pydatetime,
)
from pandas._libs.tslibs.timezones import tz_compare
-from pandas._typing import ArrayLike, Dtype, DtypeObj
+from pandas._typing import AnyArrayLike, ArrayLike, Dtype, DtypeObj, Scalar
from pandas.util._validators import validate_bool_kwarg
from pandas.core.dtypes.common import (
@@ -83,6 +94,8 @@
if TYPE_CHECKING:
from pandas import Series
from pandas.core.arrays import ExtensionArray
+ from pandas.core.indexes.base import Index
+ from pandas.core.indexes.datetimes import DatetimeIndex
_int8_max = np.iinfo(np.int8).max
_int16_max = np.iinfo(np.int16).max
@@ -118,7 +131,7 @@ def is_nested_object(obj) -> bool:
return False
-def maybe_downcast_to_dtype(result, dtype):
+def maybe_downcast_to_dtype(result, dtype: Dtype):
"""
try to cast to the specified dtype (e.g. convert back to bool/int
or could be an astype of float64->float32
@@ -186,7 +199,7 @@ def maybe_downcast_to_dtype(result, dtype):
return result
-def maybe_downcast_numeric(result, dtype, do_round: bool = False):
+def maybe_downcast_numeric(result, dtype: DtypeObj, do_round: bool = False):
"""
Subset of maybe_downcast_to_dtype restricted to numeric dtypes.
@@ -329,7 +342,9 @@ def maybe_cast_result_dtype(dtype: DtypeObj, how: str) -> DtypeObj:
return dtype
-def maybe_cast_to_extension_array(cls: Type["ExtensionArray"], obj, dtype=None):
+def maybe_cast_to_extension_array(
+ cls: Type["ExtensionArray"], obj: ArrayLike, dtype: Optional[ExtensionDtype] = None
+) -> ArrayLike:
"""
Call to `_from_sequence` that returns the object unchanged on Exception.
@@ -362,7 +377,9 @@ def maybe_cast_to_extension_array(cls: Type["ExtensionArray"], obj, dtype=None):
return result
-def maybe_upcast_putmask(result: np.ndarray, mask: np.ndarray, other):
+def maybe_upcast_putmask(
+ result: np.ndarray, mask: np.ndarray, other: Scalar
+) -> Tuple[np.ndarray, bool]:
"""
A safe version of putmask that potentially upcasts the result.
@@ -444,7 +461,9 @@ def changeit():
return result, False
-def maybe_casted_values(index, codes=None):
+def maybe_casted_values(
+ index: "Index", codes: Optional[np.ndarray] = None
+) -> ArrayLike:
"""
Convert an index, given directly or as a pair (level, code), to a 1D array.
@@ -468,7 +487,7 @@ def maybe_casted_values(index, codes=None):
# if we have the codes, extract the values with a mask
if codes is not None:
- mask = codes == -1
+ mask: np.ndarray = codes == -1
# we can have situations where the whole mask is -1,
# meaning there is nothing found in codes, so make all nan's
@@ -660,7 +679,7 @@ def maybe_promote(dtype, fill_value=np.nan):
return dtype, fill_value
-def _ensure_dtype_type(value, dtype):
+def _ensure_dtype_type(value, dtype: DtypeObj):
"""
Ensure that the given value is an instance of the given dtype.
@@ -786,8 +805,9 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> Tuple[DtypeObj,
return dtype, val
-# 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]:
+def infer_dtype_from_array(
+ arr, pandas_dtype: bool = False
+) -> Tuple[DtypeObj, ArrayLike]:
"""
Infer the dtype from an array.
@@ -875,7 +895,12 @@ def maybe_infer_dtype_type(element):
return tipo
-def maybe_upcast(values, fill_value=np.nan, dtype=None, copy: bool = False):
+def maybe_upcast(
+ values: ArrayLike,
+ fill_value: Scalar = np.nan,
+ dtype: Dtype = None,
+ copy: bool = False,
+) -> Tuple[ArrayLike, Scalar]:
"""
Provide explicit type promotion and coercion.
@@ -887,6 +912,13 @@ def maybe_upcast(values, fill_value=np.nan, dtype=None, copy: bool = False):
dtype : if None, then use the dtype of the values, else coerce to this type
copy : bool, default True
If True always make a copy even if no upcast is required.
+
+ Returns
+ -------
+ values: ndarray or ExtensionArray
+ the original array, possibly upcast
+ fill_value:
+ the fill value, possibly upcast
"""
if not is_scalar(fill_value) and not is_object_dtype(values.dtype):
# We allow arbitrary fill values for object dtype
@@ -907,7 +939,7 @@ def maybe_upcast(values, fill_value=np.nan, dtype=None, copy: bool = False):
return values, fill_value
-def invalidate_string_dtypes(dtype_set):
+def invalidate_string_dtypes(dtype_set: Set[DtypeObj]):
"""
Change string like dtypes to object for
``DataFrame.select_dtypes()``.
@@ -929,7 +961,7 @@ def coerce_indexer_dtype(indexer, categories):
return ensure_int64(indexer)
-def coerce_to_dtypes(result, dtypes):
+def coerce_to_dtypes(result: Sequence[Scalar], dtypes: Sequence[Dtype]) -> List[Scalar]:
"""
given a dtypes and a result set, coerce the result elements to the
dtypes
@@ -959,7 +991,9 @@ def conv(r, dtype):
return [conv(r, dtype) for r, dtype in zip(result, dtypes)]
-def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
+def astype_nansafe(
+ arr, dtype: DtypeObj, copy: bool = True, skipna: bool = False
+) -> ArrayLike:
"""
Cast the elements of an array to a given dtype a nan-safe manner.
@@ -1063,7 +1097,9 @@ def astype_nansafe(arr, dtype, copy: bool = True, skipna: bool = False):
return arr.view(dtype)
-def maybe_convert_objects(values: np.ndarray, convert_numeric: bool = True):
+def maybe_convert_objects(
+ values: np.ndarray, convert_numeric: bool = True
+) -> Union[np.ndarray, "DatetimeIndex"]:
"""
If we have an object dtype array, try to coerce dates and/or numbers.
@@ -1184,7 +1220,7 @@ def soft_convert_objects(
def convert_dtypes(
- input_array,
+ input_array: AnyArrayLike,
convert_string: bool = True,
convert_integer: bool = True,
convert_boolean: bool = True,
@@ -1195,7 +1231,7 @@ def convert_dtypes(
Parameters
----------
- input_array : ExtensionArray or PandasArray
+ input_array : ExtensionArray, Index, Series or np.ndarray
convert_string : bool, default True
Whether object dtypes should be converted to ``StringDtype()``.
convert_integer : bool, default True
@@ -1250,9 +1286,11 @@ def convert_dtypes(
return inferred_dtype
-def maybe_castable(arr) -> bool:
+def maybe_castable(arr: np.ndarray) -> bool:
# return False to force a non-fastpath
+ assert isinstance(arr, np.ndarray) # GH 37024
+
# check datetime64[ns]/timedelta64[ns] are valid
# otherwise try to coerce
kind = arr.dtype.kind
@@ -1264,7 +1302,9 @@ def maybe_castable(arr) -> bool:
return arr.dtype.name not in POSSIBLY_CAST_DTYPES
-def maybe_infer_to_datetimelike(value, convert_dates: bool = False):
+def maybe_infer_to_datetimelike(
+ value: Union[ArrayLike, Scalar], convert_dates: bool = False
+):
"""
we might have a array (or single object) that is datetime like,
and no dtype is passed don't change the value unless we find a
@@ -1373,7 +1413,7 @@ def try_timedelta(v):
return value
-def maybe_cast_to_datetime(value, dtype, errors: str = "raise"):
+def maybe_cast_to_datetime(value, dtype: DtypeObj, errors: str = "raise"):
"""
try to cast the array/value to a datetimelike dtype, converting float
nan to iNaT
@@ -1566,7 +1606,9 @@ def find_common_type(types: List[DtypeObj]) -> DtypeObj:
return np.find_common_type(types, [])
-def cast_scalar_to_array(shape, value, dtype: Optional[DtypeObj] = None) -> np.ndarray:
+def cast_scalar_to_array(
+ shape: Tuple, value: Scalar, dtype: Optional[DtypeObj] = None
+) -> np.ndarray:
"""
Create np.ndarray of specified shape and dtype, filled with values.
@@ -1594,7 +1636,7 @@ def cast_scalar_to_array(shape, value, dtype: Optional[DtypeObj] = None) -> np.n
def construct_1d_arraylike_from_scalar(
- value, length: int, dtype: DtypeObj
+ value: Scalar, length: int, dtype: DtypeObj
) -> ArrayLike:
"""
create a np.ndarray / pandas type of specified shape and dtype
@@ -1638,7 +1680,7 @@ def construct_1d_arraylike_from_scalar(
return subarr
-def construct_1d_object_array_from_listlike(values) -> np.ndarray:
+def construct_1d_object_array_from_listlike(values: Sized) -> np.ndarray:
"""
Transform any list-like object in a 1-dimensional numpy array of object
dtype.
@@ -1664,7 +1706,7 @@ def construct_1d_object_array_from_listlike(values) -> np.ndarray:
def construct_1d_ndarray_preserving_na(
- values, dtype: Optional[DtypeObj] = None, copy: bool = False
+ values: Sequence, dtype: Optional[DtypeObj] = None, copy: bool = False
) -> np.ndarray:
"""
Construct a new ndarray, coercing `values` to `dtype`, preserving NA.
@@ -1698,7 +1740,7 @@ def construct_1d_ndarray_preserving_na(
return subarr
-def maybe_cast_to_integer_array(arr, dtype, copy: bool = False):
+def maybe_cast_to_integer_array(arr, dtype: Dtype, copy: bool = False):
"""
Takes any dtype and returns the casted version, raising for when data is
incompatible with integer/unsigned integer dtypes.
@@ -1768,7 +1810,7 @@ def maybe_cast_to_integer_array(arr, dtype, copy: bool = False):
raise ValueError("Trying to coerce float values to integers")
-def convert_scalar_for_putitemlike(scalar, dtype: np.dtype):
+def convert_scalar_for_putitemlike(scalar: Scalar, dtype: np.dtype) -> Scalar:
"""
Convert datetimelike scalar if we are setting into a datetime64
or timedelta64 ndarray.
@@ -1799,7 +1841,7 @@ def convert_scalar_for_putitemlike(scalar, dtype: np.dtype):
return scalar
-def validate_numeric_casting(dtype: np.dtype, value):
+def validate_numeric_casting(dtype: np.dtype, value: Scalar) -> None:
"""
Check that we can losslessly insert the given value into an array
with the given dtype.
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/37024 | 2020-10-10T06:32:00Z | 2020-10-14T12:35:15Z | 2020-10-14T12:35:15Z | 2020-10-14T12:35:20Z |
REGR: fix bug in DatetimeIndex slicing with irregular or unsorted indices | diff --git a/doc/source/whatsnew/v1.1.4.rst b/doc/source/whatsnew/v1.1.4.rst
index eb68ca38ea5b6..eefc1284c1285 100644
--- a/doc/source/whatsnew/v1.1.4.rst
+++ b/doc/source/whatsnew/v1.1.4.rst
@@ -22,6 +22,7 @@ Fixed regressions
- Fixed regression in :class:`RollingGroupby` causing a segmentation fault with Index of dtype object (:issue:`36727`)
- Fixed regression in :meth:`DataFrame.resample(...).apply(...)` raised ``AttributeError`` when input was a :class:`DataFrame` and only a :class:`Series` was evaluated (:issue:`36951`)
- Fixed regression in :class:`PeriodDtype` comparing both equal and unequal to its string representation (:issue:`37265`)
+- Fixed regression where slicing :class:`DatetimeIndex` raised :exc:`AssertionError` on irregular time series with ``pd.NaT`` or on unsorted indices (:issue:`36953` and :issue:`35509`)
- Fixed regression in certain offsets (:meth:`pd.offsets.Day() <pandas.tseries.offsets.Day>` and below) no longer being hashable (:issue:`37267`)
- Fixed regression in :class:`StataReader` which required ``chunksize`` to be manually set when using an iterator to read a dataset (:issue:`37280`)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 8ff16049628a3..f097f8faac8f8 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2920,6 +2920,8 @@ def __getitem__(self, key):
# Do we have a slicer (on rows)?
indexer = convert_to_index_sliceable(self, key)
if indexer is not None:
+ if isinstance(indexer, np.ndarray):
+ indexer = lib.maybe_indices_to_slice(indexer, len(self))
# either we have a slice or we have a string that can be converted
# to a slice for partial-string date indexing
return self._slice(indexer, axis=0)
diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py
index b1928de69ea0f..80b7947eb5239 100644
--- a/pandas/tests/indexing/test_partial.py
+++ b/pandas/tests/indexing/test_partial.py
@@ -681,3 +681,24 @@ def test_index_name_empty(self):
{"series": [1.23] * 4}, index=pd.RangeIndex(4, name="series_index")
)
tm.assert_frame_equal(df, expected)
+
+ def test_slice_irregular_datetime_index_with_nan(self):
+ # GH36953
+ index = pd.to_datetime(["2012-01-01", "2012-01-02", "2012-01-03", None])
+ df = DataFrame(range(len(index)), index=index)
+ expected = DataFrame(range(len(index[:3])), index=index[:3])
+ result = df["2012-01-01":"2012-01-04"]
+ tm.assert_frame_equal(result, expected)
+
+ def test_slice_datetime_index(self):
+ # GH35509
+ df = DataFrame(
+ {"col1": ["a", "b", "c"], "col2": [1, 2, 3]},
+ index=pd.to_datetime(["2020-08-01", "2020-07-02", "2020-08-05"]),
+ )
+ expected = DataFrame(
+ {"col1": ["a", "c"], "col2": [1, 3]},
+ index=pd.to_datetime(["2020-08-01", "2020-08-05"]),
+ )
+ result = df.loc["2020-08"]
+ tm.assert_frame_equal(result, expected)
| closes #36953
closes #35509
- [x] 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/37023 | 2020-10-10T06:30:19Z | 2020-10-26T14:51:58Z | 2020-10-26T14:51:58Z | 2020-10-26T15:15:06Z |
Fix to_gbq method when verbose=False | diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py
index e706434f29dc5..edd8f8c7b5033 100644
--- a/pandas/io/gbq.py
+++ b/pandas/io/gbq.py
@@ -426,9 +426,8 @@ def load_data(self, dataframe, dataset_id, table_id, chunksize):
rows = []
remaining_rows = len(dataframe)
- if self.verbose:
- total_rows = remaining_rows
- self._print("\n\n")
+ total_rows = remaining_rows
+ self._print("\n\n")
for index, row in dataframe.reset_index(drop=True).iterrows():
row_dict = dict()
| Currently the `to_gbq` method fails when `verbose=False`, as the printing of progress is done regardless of the value of the `verbose` flag, and therefore `total_rows` gets called without being set. This change suppresses printing of progress when `verbose=False`.
| https://api.github.com/repos/pandas-dev/pandas/pulls/13244 | 2016-05-20T22:13:53Z | 2016-08-15T20:19:33Z | 2016-08-15T20:19:33Z | 2016-08-15T20:19:42Z |
CLN: Check Warnings in test_graphics_others | diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py
index b09185c19bffb..bd19a83ce2b64 100644
--- a/pandas/tests/test_graphics.py
+++ b/pandas/tests/test_graphics.py
@@ -450,8 +450,9 @@ def _check_box_return_type(self, returned, return_type, expected_keys=None,
self.assertIsInstance(value.lines, dict)
elif return_type == 'dict':
line = value['medians'][0]
+ axes = line.axes if self.mpl_ge_1_5_0 else line.get_axes()
if check_ax_title:
- self.assertEqual(line.get_axes().get_title(), key)
+ self.assertEqual(axes.get_title(), key)
else:
raise AssertionError
@@ -820,10 +821,13 @@ def test_hist_legacy(self):
_check_plot_works(self.ts.hist)
_check_plot_works(self.ts.hist, grid=False)
_check_plot_works(self.ts.hist, figsize=(8, 10))
- _check_plot_works(self.ts.hist, filterwarnings='ignore',
- by=self.ts.index.month)
- _check_plot_works(self.ts.hist, filterwarnings='ignore',
- by=self.ts.index.month, bins=5)
+ # _check_plot_works adds an ax so catch warning. see GH #13188
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(self.ts.hist,
+ by=self.ts.index.month)
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(self.ts.hist,
+ by=self.ts.index.month, bins=5)
fig, ax = self.plt.subplots(1, 1)
_check_plot_works(self.ts.hist, ax=ax)
@@ -857,32 +861,40 @@ def test_hist_layout(self):
def test_hist_layout_with_by(self):
df = self.hist_df
- axes = _check_plot_works(df.height.hist, filterwarnings='ignore',
- by=df.gender, layout=(2, 1))
+ # _check_plot_works adds an ax so catch warning. see GH #13188
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.height.hist,
+ by=df.gender, layout=(2, 1))
self._check_axes_shape(axes, axes_num=2, layout=(2, 1))
- axes = _check_plot_works(df.height.hist, filterwarnings='ignore',
- by=df.gender, layout=(3, -1))
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.height.hist,
+ by=df.gender, layout=(3, -1))
self._check_axes_shape(axes, axes_num=2, layout=(3, 1))
- axes = _check_plot_works(df.height.hist, filterwarnings='ignore',
- by=df.category, layout=(4, 1))
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.height.hist,
+ by=df.category, layout=(4, 1))
self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
- axes = _check_plot_works(df.height.hist, filterwarnings='ignore',
- by=df.category, layout=(2, -1))
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.height.hist,
+ by=df.category, layout=(2, -1))
self._check_axes_shape(axes, axes_num=4, layout=(2, 2))
- axes = _check_plot_works(df.height.hist, filterwarnings='ignore',
- by=df.category, layout=(3, -1))
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.height.hist,
+ by=df.category, layout=(3, -1))
self._check_axes_shape(axes, axes_num=4, layout=(3, 2))
- axes = _check_plot_works(df.height.hist, filterwarnings='ignore',
- by=df.category, layout=(-1, 4))
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.height.hist,
+ by=df.category, layout=(-1, 4))
self._check_axes_shape(axes, axes_num=4, layout=(1, 4))
- axes = _check_plot_works(df.height.hist, filterwarnings='ignore',
- by=df.classroom, layout=(2, 2))
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.height.hist,
+ by=df.classroom, layout=(2, 2))
self._check_axes_shape(axes, axes_num=3, layout=(2, 2))
axes = df.height.hist(by=df.category, layout=(4, 2), figsize=(12, 7))
@@ -899,7 +911,7 @@ def test_hist_no_overlap(self):
subplot(122)
y.hist()
fig = gcf()
- axes = fig.get_axes()
+ axes = fig.axes if self.mpl_ge_1_5_0 else fig.get_axes()
self.assertEqual(len(axes), 2)
@slow
@@ -1300,17 +1312,21 @@ def setUp(self):
@slow
def test_plot(self):
df = self.tdf
- _check_plot_works(df.plot, filterwarnings='ignore', grid=False)
- axes = _check_plot_works(df.plot, filterwarnings='ignore',
- subplots=True)
+ _check_plot_works(df.plot, grid=False)
+ # _check_plot_works adds an ax so catch warning. see GH #13188
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.plot,
+ subplots=True)
self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
- axes = _check_plot_works(df.plot, filterwarnings='ignore',
- subplots=True, layout=(-1, 2))
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.plot,
+ subplots=True, layout=(-1, 2))
self._check_axes_shape(axes, axes_num=4, layout=(2, 2))
- axes = _check_plot_works(df.plot, filterwarnings='ignore',
- subplots=True, use_index=False)
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.plot,
+ subplots=True, use_index=False)
self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
df = DataFrame({'x': [1, 2], 'y': [3, 4]})
@@ -1326,8 +1342,8 @@ def test_plot(self):
_check_plot_works(df.plot, xticks=[1, 5, 10])
_check_plot_works(df.plot, ylim=(-100, 100), xlim=(-100, 100))
- _check_plot_works(df.plot, filterwarnings='ignore',
- subplots=True, title='blah')
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(df.plot, subplots=True, title='blah')
# We have to redo it here because _check_plot_works does two plots,
# once without an ax kwarg and once with an ax kwarg and the new sharex
@@ -2217,7 +2233,9 @@ def test_plot_bar(self):
_check_plot_works(df.plot.bar)
_check_plot_works(df.plot.bar, legend=False)
- _check_plot_works(df.plot.bar, filterwarnings='ignore', subplots=True)
+ # _check_plot_works adds an ax so catch warning. see GH #13188
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(df.plot.bar, subplots=True)
_check_plot_works(df.plot.bar, stacked=True)
df = DataFrame(randn(10, 15),
@@ -2433,8 +2451,10 @@ def test_boxplot_vertical(self):
self._check_text_labels(ax.get_yticklabels(), labels)
self.assertEqual(len(ax.lines), self.bp_n_objects * len(numeric_cols))
- axes = _check_plot_works(df.plot.box, filterwarnings='ignore',
- subplots=True, vert=False, logx=True)
+ # _check_plot_works adds an ax so catch warning. see GH #13188
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.plot.box,
+ subplots=True, vert=False, logx=True)
self._check_axes_shape(axes, axes_num=3, layout=(1, 3))
self._check_ax_scales(axes, xaxis='log')
for ax, label in zip(axes, labels):
@@ -2494,8 +2514,9 @@ def test_kde_df(self):
ax = df.plot(kind='kde', rot=20, fontsize=5)
self._check_ticks_props(ax, xrot=20, xlabelsize=5, ylabelsize=5)
- axes = _check_plot_works(df.plot, filterwarnings='ignore', kind='kde',
- subplots=True)
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.plot, kind='kde',
+ subplots=True)
self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
axes = df.plot(kind='kde', logy=True, subplots=True)
@@ -2522,8 +2543,9 @@ def test_hist_df(self):
expected = [pprint_thing(c) for c in df.columns]
self._check_legend_labels(ax, labels=expected)
- axes = _check_plot_works(df.plot.hist, filterwarnings='ignore',
- subplots=True, logy=True)
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.plot.hist,
+ subplots=True, logy=True)
self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
self._check_ax_scales(axes, yaxis='log')
@@ -2902,8 +2924,9 @@ def test_line_colors_and_styles_subplots(self):
# Color contains shorthand hex value results in ValueError
custom_colors = ['#F00', '#00F', '#FF0', '#000', '#FFF']
# Forced show plot
- _check_plot_works(df.plot, color=custom_colors, subplots=True,
- filterwarnings='ignore')
+ # _check_plot_works adds an ax so catch warning. see GH #13188
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(df.plot, color=custom_colors, subplots=True)
rgba_colors = lmap(cm.jet, np.linspace(0, 1, len(df)))
for cmap in ['jet', cm.jet]:
@@ -3294,8 +3317,10 @@ def test_pie_df(self):
ax = _check_plot_works(df.plot.pie, y=2)
self._check_text_labels(ax.texts, df.index)
- axes = _check_plot_works(df.plot.pie, filterwarnings='ignore',
- subplots=True)
+ # _check_plot_works adds an ax so catch warning. see GH #13188
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.plot.pie,
+ subplots=True)
self.assertEqual(len(axes), len(df.columns))
for ax in axes:
self._check_text_labels(ax.texts, df.index)
@@ -3304,9 +3329,10 @@ def test_pie_df(self):
labels = ['A', 'B', 'C', 'D', 'E']
color_args = ['r', 'g', 'b', 'c', 'm']
- axes = _check_plot_works(df.plot.pie, filterwarnings='ignore',
- subplots=True, labels=labels,
- colors=color_args)
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.plot.pie,
+ subplots=True, labels=labels,
+ colors=color_args)
self.assertEqual(len(axes), len(df.columns))
for ax in axes:
@@ -3362,9 +3388,12 @@ def test_errorbar_plot(self):
self._check_has_errorbars(ax, xerr=2, yerr=2)
ax = _check_plot_works(df.plot, xerr=0.2, yerr=0.2, kind=kind)
self._check_has_errorbars(ax, xerr=2, yerr=2)
- axes = _check_plot_works(df.plot, filterwarnings='ignore',
- yerr=df_err, xerr=df_err, subplots=True,
- kind=kind)
+ # _check_plot_works adds an ax so catch warning. see GH #13188
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.plot,
+ yerr=df_err, xerr=df_err,
+ subplots=True,
+ kind=kind)
self._check_has_errorbars(axes, xerr=1, yerr=1)
ax = _check_plot_works((df + 1).plot, yerr=df_err,
@@ -3455,8 +3484,11 @@ def test_errorbar_timeseries(self):
self._check_has_errorbars(ax, xerr=0, yerr=1)
ax = _check_plot_works(tdf.plot, yerr=tdf_err, kind=kind)
self._check_has_errorbars(ax, xerr=0, yerr=2)
- axes = _check_plot_works(tdf.plot, filterwarnings='ignore',
- kind=kind, yerr=tdf_err, subplots=True)
+ # _check_plot_works adds an ax so catch warning. see GH #13188
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(tdf.plot,
+ kind=kind, yerr=tdf_err,
+ subplots=True)
self._check_has_errorbars(axes, xerr=0, yerr=1)
def test_errorbar_asymmetrical(self):
diff --git a/pandas/tests/test_graphics_others.py b/pandas/tests/test_graphics_others.py
index 7285d84865542..f9a210a492594 100644
--- a/pandas/tests/test_graphics_others.py
+++ b/pandas/tests/test_graphics_others.py
@@ -5,7 +5,6 @@
import itertools
import os
import string
-import warnings
from distutils.version import LooseVersion
from pandas import Series, DataFrame, MultiIndex
@@ -61,8 +60,11 @@ def test_hist_legacy(self):
_check_plot_works(self.ts.hist)
_check_plot_works(self.ts.hist, grid=False)
_check_plot_works(self.ts.hist, figsize=(8, 10))
- _check_plot_works(self.ts.hist, by=self.ts.index.month)
- _check_plot_works(self.ts.hist, by=self.ts.index.month, bins=5)
+ # _check_plot_works adds an ax so catch warning. see GH #13188
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(self.ts.hist, by=self.ts.index.month)
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(self.ts.hist, by=self.ts.index.month, bins=5)
fig, ax = self.plt.subplots(1, 1)
_check_plot_works(self.ts.hist, ax=ax)
@@ -96,29 +98,42 @@ def test_hist_layout(self):
def test_hist_layout_with_by(self):
df = self.hist_df
- axes = _check_plot_works(df.height.hist, by=df.gender, layout=(2, 1))
+ # _check_plot_works adds an `ax` kwarg to the method call
+ # so we get a warning about an axis being cleared, even
+ # though we don't explicing pass one, see GH #13188
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.height.hist, by=df.gender,
+ layout=(2, 1))
self._check_axes_shape(axes, axes_num=2, layout=(2, 1))
- axes = _check_plot_works(df.height.hist, by=df.gender, layout=(3, -1))
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.height.hist, by=df.gender,
+ layout=(3, -1))
self._check_axes_shape(axes, axes_num=2, layout=(3, 1))
- axes = _check_plot_works(df.height.hist, by=df.category, layout=(4, 1))
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.height.hist, by=df.category,
+ layout=(4, 1))
self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
- axes = _check_plot_works(
- df.height.hist, by=df.category, layout=(2, -1))
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(
+ df.height.hist, by=df.category, layout=(2, -1))
self._check_axes_shape(axes, axes_num=4, layout=(2, 2))
- axes = _check_plot_works(
- df.height.hist, by=df.category, layout=(3, -1))
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(
+ df.height.hist, by=df.category, layout=(3, -1))
self._check_axes_shape(axes, axes_num=4, layout=(3, 2))
- axes = _check_plot_works(
- df.height.hist, by=df.category, layout=(-1, 4))
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(
+ df.height.hist, by=df.category, layout=(-1, 4))
self._check_axes_shape(axes, axes_num=4, layout=(1, 4))
- axes = _check_plot_works(
- df.height.hist, by=df.classroom, layout=(2, 2))
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(
+ df.height.hist, by=df.classroom, layout=(2, 2))
self._check_axes_shape(axes, axes_num=3, layout=(2, 2))
axes = df.height.hist(by=df.category, layout=(4, 2), figsize=(12, 7))
@@ -135,7 +150,7 @@ def test_hist_no_overlap(self):
subplot(122)
y.hist()
fig = gcf()
- axes = fig.get_axes()
+ axes = fig.axes if self.mpl_ge_1_5_0 else fig.get_axes()
self.assertEqual(len(axes), 2)
@slow
@@ -203,33 +218,43 @@ def test_boxplot_legacy(self):
_check_plot_works(df.boxplot, return_type='dict')
_check_plot_works(df.boxplot, column=[
'one', 'two'], return_type='dict')
- _check_plot_works(df.boxplot, column=['one', 'two'], by='indic')
+ # _check_plot_works adds an ax so catch warning. see GH #13188
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(df.boxplot, column=['one', 'two'],
+ by='indic')
_check_plot_works(df.boxplot, column='one', by=['indic', 'indic2'])
- _check_plot_works(df.boxplot, by='indic')
- _check_plot_works(df.boxplot, by=['indic', 'indic2'])
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(df.boxplot, by='indic')
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(df.boxplot, by=['indic', 'indic2'])
_check_plot_works(plotting.boxplot, data=df['one'], return_type='dict')
_check_plot_works(df.boxplot, notch=1, return_type='dict')
- _check_plot_works(df.boxplot, by='indic', notch=1)
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(df.boxplot, by='indic', notch=1)
df = DataFrame(np.random.rand(10, 2), columns=['Col1', 'Col2'])
df['X'] = Series(['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'])
df['Y'] = Series(['A'] * 10)
- _check_plot_works(df.boxplot, by='X')
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(df.boxplot, by='X')
# When ax is supplied and required number of axes is 1,
# passed ax should be used:
fig, ax = self.plt.subplots()
axes = df.boxplot('Col1', by='X', ax=ax)
- self.assertIs(ax.get_axes(), axes)
+ ax_axes = ax.axes if self.mpl_ge_1_5_0 else ax.get_axes()
+ self.assertIs(ax_axes, axes)
fig, ax = self.plt.subplots()
axes = df.groupby('Y').boxplot(ax=ax, return_type='axes')
- self.assertIs(ax.get_axes(), axes['A'])
+ ax_axes = ax.axes if self.mpl_ge_1_5_0 else ax.get_axes()
+ self.assertIs(ax_axes, axes['A'])
# Multiple columns with an ax argument should use same figure
fig, ax = self.plt.subplots()
- axes = df.boxplot(column=['Col1', 'Col2'],
- by='X', ax=ax, return_type='axes')
+ with tm.assert_produces_warning(UserWarning):
+ axes = df.boxplot(column=['Col1', 'Col2'],
+ by='X', ax=ax, return_type='axes')
self.assertIs(axes['Col1'].get_figure(), fig)
# When by is None, check that all relevant lines are present in the
@@ -304,11 +329,13 @@ def test_boxplot_empty_column(self):
@slow
def test_hist_df_legacy(self):
from matplotlib.patches import Rectangle
- _check_plot_works(self.hist_df.hist)
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(self.hist_df.hist)
# make sure layout is handled
df = DataFrame(randn(100, 3))
- axes = _check_plot_works(df.hist, grid=False)
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.hist, grid=False)
self._check_axes_shape(axes, axes_num=3, layout=(2, 2))
self.assertFalse(axes[1, 1].get_visible())
@@ -317,17 +344,21 @@ def test_hist_df_legacy(self):
# make sure layout is handled
df = DataFrame(randn(100, 6))
- axes = _check_plot_works(df.hist, layout=(4, 2))
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.hist, layout=(4, 2))
self._check_axes_shape(axes, axes_num=6, layout=(4, 2))
# make sure sharex, sharey is handled
- _check_plot_works(df.hist, sharex=True, sharey=True)
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(df.hist, sharex=True, sharey=True)
# handle figsize arg
- _check_plot_works(df.hist, figsize=(8, 10))
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(df.hist, figsize=(8, 10))
# check bins argument
- _check_plot_works(df.hist, bins=5)
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(df.hist, bins=5)
# make sure xlabelsize and xrot are handled
ser = df[0]
@@ -401,22 +432,30 @@ def test_scatter_plot_legacy(self):
def scat(**kwds):
return plotting.scatter_matrix(df, **kwds)
- _check_plot_works(scat)
- _check_plot_works(scat, marker='+')
- _check_plot_works(scat, vmin=0)
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(scat)
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(scat, marker='+')
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(scat, vmin=0)
if _ok_for_gaussian_kde('kde'):
- _check_plot_works(scat, diagonal='kde')
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(scat, diagonal='kde')
if _ok_for_gaussian_kde('density'):
- _check_plot_works(scat, diagonal='density')
- _check_plot_works(scat, diagonal='hist')
- _check_plot_works(scat, range_padding=.1)
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(scat, diagonal='density')
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(scat, diagonal='hist')
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(scat, range_padding=.1)
def scat2(x, y, by=None, ax=None, figsize=None):
return plotting.scatter_plot(df, x, y, by, ax, figsize=None)
_check_plot_works(scat2, x=0, y=1)
grouper = Series(np.repeat([1, 2, 3, 4, 5], 20), df.index)
- _check_plot_works(scat2, x=0, y=1, by=grouper)
+ with tm.assert_produces_warning(UserWarning):
+ _check_plot_works(scat2, x=0, y=1, by=grouper)
def test_scatter_matrix_axis(self):
tm._skip_if_no_scipy()
@@ -607,8 +646,7 @@ class TestDataFrameGroupByPlots(TestPlotBase):
@slow
def test_boxplot_legacy(self):
grouped = self.hist_df.groupby(by='gender')
- with warnings.catch_warnings():
- warnings.simplefilter('ignore')
+ with tm.assert_produces_warning(UserWarning):
axes = _check_plot_works(grouped.boxplot, return_type='axes')
self._check_axes_shape(list(axes.values()), axes_num=2, layout=(1, 2))
@@ -620,7 +658,8 @@ def test_boxplot_legacy(self):
index=MultiIndex.from_tuples(tuples))
grouped = df.groupby(level=1)
- axes = _check_plot_works(grouped.boxplot, return_type='axes')
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(grouped.boxplot, return_type='axes')
self._check_axes_shape(list(axes.values()), axes_num=10, layout=(4, 3))
axes = _check_plot_works(grouped.boxplot, subplots=False,
@@ -628,7 +667,8 @@ def test_boxplot_legacy(self):
self._check_axes_shape(axes, axes_num=1, layout=(1, 1))
grouped = df.unstack(level=1).groupby(level=0, axis=1)
- axes = _check_plot_works(grouped.boxplot, return_type='axes')
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(grouped.boxplot, return_type='axes')
self._check_axes_shape(list(axes.values()), axes_num=3, layout=(2, 2))
axes = _check_plot_works(grouped.boxplot, subplots=False,
@@ -774,18 +814,22 @@ def test_grouped_box_layout(self):
self.assertRaises(ValueError, df.boxplot, column=['weight', 'height'],
by=df.gender, layout=(-1, -1))
- box = _check_plot_works(df.groupby('gender').boxplot, column='height',
- return_type='dict')
+ # _check_plot_works adds an ax so catch warning. see GH #13188
+ with tm.assert_produces_warning(UserWarning):
+ box = _check_plot_works(df.groupby('gender').boxplot,
+ column='height', return_type='dict')
self._check_axes_shape(self.plt.gcf().axes, axes_num=2, layout=(1, 2))
- box = _check_plot_works(df.groupby('category').boxplot,
- column='height',
- return_type='dict')
+ with tm.assert_produces_warning(UserWarning):
+ box = _check_plot_works(df.groupby('category').boxplot,
+ column='height',
+ return_type='dict')
self._check_axes_shape(self.plt.gcf().axes, axes_num=4, layout=(2, 2))
# GH 6769
- box = _check_plot_works(df.groupby('classroom').boxplot,
- column='height', return_type='dict')
+ with tm.assert_produces_warning(UserWarning):
+ box = _check_plot_works(df.groupby('classroom').boxplot,
+ column='height', return_type='dict')
self._check_axes_shape(self.plt.gcf().axes, axes_num=3, layout=(2, 2))
# GH 5897
@@ -803,13 +847,15 @@ def test_grouped_box_layout(self):
column=['height', 'weight', 'category'], return_type='dict')
self._check_axes_shape(self.plt.gcf().axes, axes_num=3, layout=(2, 2))
- box = _check_plot_works(df.groupby('category').boxplot,
- column='height',
- layout=(3, 2), return_type='dict')
+ with tm.assert_produces_warning(UserWarning):
+ box = _check_plot_works(df.groupby('category').boxplot,
+ column='height',
+ layout=(3, 2), return_type='dict')
self._check_axes_shape(self.plt.gcf().axes, axes_num=4, layout=(3, 2))
- box = _check_plot_works(df.groupby('category').boxplot,
- column='height',
- layout=(3, -1), return_type='dict')
+ with tm.assert_produces_warning(UserWarning):
+ box = _check_plot_works(df.groupby('category').boxplot,
+ column='height',
+ layout=(3, -1), return_type='dict')
self._check_axes_shape(self.plt.gcf().axes, axes_num=4, layout=(3, 2))
box = df.boxplot(column=['height', 'weight', 'category'], by='gender',
@@ -848,8 +894,7 @@ def test_grouped_box_multiple_axes(self):
axes_num=4, layout=(2, 2))
fig, axes = self.plt.subplots(2, 3)
- with warnings.catch_warnings():
- warnings.simplefilter('ignore')
+ with tm.assert_produces_warning(UserWarning):
returned = df.boxplot(column=['height', 'weight', 'category'],
by='gender', return_type='axes', ax=axes[0])
returned = np.array(list(returned.values()))
@@ -858,8 +903,7 @@ def test_grouped_box_multiple_axes(self):
self.assertIs(returned[0].figure, fig)
# draw on second row
- with warnings.catch_warnings():
- warnings.simplefilter('ignore')
+ with tm.assert_produces_warning(UserWarning):
returned = df.groupby('classroom').boxplot(
column=['height', 'weight', 'category'],
return_type='axes', ax=axes[1])
@@ -871,7 +915,8 @@ def test_grouped_box_multiple_axes(self):
with tm.assertRaises(ValueError):
fig, axes = self.plt.subplots(2, 3)
# pass different number of axes from required
- axes = df.groupby('classroom').boxplot(ax=axes)
+ with tm.assert_produces_warning(UserWarning):
+ axes = df.groupby('classroom').boxplot(ax=axes)
@slow
def test_grouped_hist_layout(self):
@@ -883,12 +928,14 @@ def test_grouped_hist_layout(self):
self.assertRaises(ValueError, df.hist, column='height', by=df.category,
layout=(-1, -1))
- axes = _check_plot_works(df.hist, column='height', by=df.gender,
- layout=(2, 1))
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.hist, column='height', by=df.gender,
+ layout=(2, 1))
self._check_axes_shape(axes, axes_num=2, layout=(2, 1))
- axes = _check_plot_works(df.hist, column='height', by=df.gender,
- layout=(2, -1))
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.hist, column='height', by=df.gender,
+ layout=(2, -1))
self._check_axes_shape(axes, axes_num=2, layout=(2, 1))
axes = df.hist(column='height', by=df.category, layout=(4, 1))
@@ -904,12 +951,14 @@ def test_grouped_hist_layout(self):
tm.close()
# GH 6769
- axes = _check_plot_works(
- df.hist, column='height', by='classroom', layout=(2, 2))
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(
+ df.hist, column='height', by='classroom', layout=(2, 2))
self._check_axes_shape(axes, axes_num=3, layout=(2, 2))
# without column
- axes = _check_plot_works(df.hist, by='classroom')
+ with tm.assert_produces_warning(UserWarning):
+ axes = _check_plot_works(df.hist, by='classroom')
self._check_axes_shape(axes, axes_num=3, layout=(2, 2))
axes = df.hist(by='gender', layout=(3, 5))
diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index baca8045f0cc1..b6c1926c1e7fc 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -3353,7 +3353,8 @@ def _subplots(naxes=None, sharex=False, sharey=False, squeeze=True,
if sharex or sharey:
warnings.warn("When passing multiple axes, sharex and sharey "
"are ignored. These settings must be specified "
- "when creating axes", UserWarning)
+ "when creating axes", UserWarning,
+ stacklevel=4)
if len(ax) == naxes:
fig = ax[0].get_figure()
return fig, ax
@@ -3370,7 +3371,8 @@ def _subplots(naxes=None, sharex=False, sharey=False, squeeze=True,
return fig, _flatten(ax)
else:
warnings.warn("To output multiple subplots, the figure containing "
- "the passed axes is being cleared", UserWarning)
+ "the passed axes is being cleared", UserWarning,
+ stacklevel=4)
fig.clear()
nrows, ncols = _get_layout(naxes, layout=layout, layout_type=layout_type)
| - [x] closes #13185 maybe
- [x] passes `git diff upstream/master | flake8 --diff`
Also a MatplotlibDeprecationWarning for use of `.get_axes()` vs. `.axes` in some tests.
| https://api.github.com/repos/pandas-dev/pandas/pulls/13188 | 2016-05-15T17:11:08Z | 2016-07-05T23:14:36Z | 2016-07-05T23:14:36Z | 2017-04-05T02:06:59Z |
BUG/COMPAT: to_datetime | diff --git a/doc/source/whatsnew/v0.18.1.txt b/doc/source/whatsnew/v0.18.1.txt
index 3345cb3d29926..1a79601bee384 100644
--- a/doc/source/whatsnew/v0.18.1.txt
+++ b/doc/source/whatsnew/v0.18.1.txt
@@ -478,7 +478,7 @@ In addition to this error change, several others have been made as well:
``to_datetime`` error changes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-Bugs in ``pd.to_datetime()`` when passing a ``unit`` with convertible entries and ``errors='coerce'`` or non-convertible with ``errors='ignore'`` (:issue:`11758`)
+Bugs in ``pd.to_datetime()`` when passing a ``unit`` with convertible entries and ``errors='coerce'`` or non-convertible with ``errors='ignore'`` (:issue:`11758`, :issue:`13052`)
Previous behaviour:
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index 034c31b33bce8..15e9136d78243 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -752,6 +752,16 @@ def test_to_datetime_unit(self):
seconds=t) for t in range(20)] + [NaT])
assert_series_equal(result, expected)
+ result = to_datetime([1, 2, 'NaT', pd.NaT, np.nan], unit='D')
+ expected = DatetimeIndex([Timestamp('1970-01-02'),
+ Timestamp('1970-01-03')] + ['NaT'] * 3)
+ tm.assert_index_equal(result, expected)
+
+ with self.assertRaises(ValueError):
+ to_datetime([1, 2, 'foo'], unit='D')
+ with self.assertRaises(ValueError):
+ to_datetime([1, 2, 111111111], unit='D')
+
def test_series_ctor_datetime64(self):
rng = date_range('1/1/2000 00:00:00', '1/1/2000 1:59:50', freq='10s')
dates = np.asarray(rng)
diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index 56c0dc875f7bf..9b7942400d3a9 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -1992,6 +1992,7 @@ cpdef array_with_unit_to_datetime(ndarray values, unit, errors='coerce'):
ndarray[float64_t] fvalues
ndarray mask
bint is_ignore=errors=='ignore', is_coerce=errors=='coerce', is_raise=errors=='raise'
+ bint need_to_iterate=True
ndarray[int64_t] iresult
ndarray[object] oresult
@@ -2006,33 +2007,28 @@ cpdef array_with_unit_to_datetime(ndarray values, unit, errors='coerce'):
if is_raise:
- # we can simply raise if there is a conversion
- # issue; but we need to mask the nulls
- # we need to guard against out-of-range conversions
- # to i8
+ # try a quick conversion to i8
+ # if we have nulls that are not type-compat
+ # then need to iterate
try:
iresult = values.astype('i8')
mask = iresult == iNaT
iresult[mask] = 0
+ fvalues = iresult.astype('f8') * m
+ need_to_iterate=False
except:
+ pass
- # we have nulls embedded
- from pandas import isnull
-
- values = values.astype('object')
- mask = isnull(values)
- values[mask] = 0
- iresult = values.astype('i8')
+ # check the bounds
+ if not need_to_iterate:
- fvalues = iresult.astype('f8') * m
- if (fvalues < _NS_LOWER_BOUND).any() or (fvalues > _NS_UPPER_BOUND).any():
- raise ValueError("cannot convert input with unit: {0}".format(unit))
- result = (values*m).astype('M8[ns]')
- iresult = result.view('i8')
- iresult[mask] = iNaT
- return result
+ if (fvalues < _NS_LOWER_BOUND).any() or (fvalues > _NS_UPPER_BOUND).any():
+ raise ValueError("cannot convert input with unit: {0}".format(unit))
+ result = (iresult*m).astype('M8[ns]')
+ iresult = result.view('i8')
+ iresult[mask] = iNaT
+ return result
- # coerce or ignore
result = np.empty(n, dtype='M8[ns]')
iresult = result.view('i8')
@@ -2051,7 +2047,7 @@ cpdef array_with_unit_to_datetime(ndarray values, unit, errors='coerce'):
try:
iresult[i] = cast_from_unit(val, unit)
except:
- if is_ignore:
+ if is_ignore or is_raise:
raise
iresult[i] = NPY_NAT
@@ -2063,24 +2059,27 @@ cpdef array_with_unit_to_datetime(ndarray values, unit, errors='coerce'):
try:
iresult[i] = cast_from_unit(float(val), unit)
except:
- if is_ignore:
+ if is_ignore or is_raise:
raise
iresult[i] = NPY_NAT
else:
- if is_ignore:
- raise Exception
+ if is_ignore or is_raise:
+ raise ValueError
iresult[i] = NPY_NAT
return result
- except:
- pass
+ except (OverflowError, ValueError) as e:
+
+ # we cannot process and are done
+ if is_raise:
+ raise ValueError("cannot convert input with the unit: {0}".format(unit))
- # we have hit an exception
- # and are in ignore mode
- # redo as object
+ # we have hit an exception
+ # and are in ignore mode
+ # redo as object
oresult = np.empty(n, dtype=object)
for i in range(n):
| xref #11758, fix for bug in #13033
| https://api.github.com/repos/pandas-dev/pandas/pulls/13052 | 2016-05-01T21:44:32Z | 2016-05-01T22:59:20Z | 2016-05-01T22:59:20Z | 2016-05-03T00:38:26Z |
COMPAT: some compatibility fixes with new numpies | diff --git a/pandas/compat/numpy_compat.py b/pandas/compat/numpy_compat.py
index d71420e979c82..8ecc5dc979792 100644
--- a/pandas/compat/numpy_compat.py
+++ b/pandas/compat/numpy_compat.py
@@ -1,5 +1,6 @@
""" support numpy compatiblitiy across versions """
+import re
import numpy as np
from distutils.version import LooseVersion
from pandas.compat import string_types, string_and_binary_types
@@ -24,11 +25,14 @@
'this pandas version'.format(_np_version))
+_tz_regex = re.compile('[+-]0000$')
+
+
def tz_replacer(s):
if isinstance(s, string_types):
if s.endswith('Z'):
s = s[:-1]
- elif s.endswith('-0000'):
+ elif _tz_regex.search(s):
s = s[:-5]
return s
diff --git a/pandas/computation/tests/test_eval.py b/pandas/computation/tests/test_eval.py
index 97db171312557..62e643b095c4d 100644
--- a/pandas/computation/tests/test_eval.py
+++ b/pandas/computation/tests/test_eval.py
@@ -50,13 +50,7 @@ def _eval_single_bin(lhs, cmp1, rhs, engine):
try:
return c(lhs, rhs)
except ValueError as e:
- try:
- msg = e.message
- except AttributeError:
- msg = e
- msg = u(msg)
- if msg == u('negative number cannot be raised to a fractional'
- ' power'):
+ if str(e).startswith('negative number cannot be raised to a fractional power'):
return np.nan
raise
return c(lhs, rhs)
@@ -306,17 +300,9 @@ def get_expected_pow_result(self, lhs, rhs):
try:
expected = _eval_single_bin(lhs, '**', rhs, self.engine)
except ValueError as e:
- msg = 'negative number cannot be raised to a fractional power'
- try:
- emsg = e.message
- except AttributeError:
- emsg = e
-
- emsg = u(emsg)
-
- if emsg == msg:
+ if str(e).startswith('negative number cannot be raised to a fractional power'):
if self.engine == 'python':
- raise nose.SkipTest(emsg)
+ raise nose.SkipTest(str(e))
else:
expected = np.nan
else:
diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py
index 9932d7f9db4cd..5dd764b471d3f 100644
--- a/pandas/io/tests/test_excel.py
+++ b/pandas/io/tests/test_excel.py
@@ -2174,19 +2174,17 @@ def check_called(func):
del called_save[:]
del called_write_cells[:]
- register_writer(DummyClass)
- writer = ExcelWriter('something.test')
- tm.assertIsInstance(writer, DummyClass)
- df = tm.makeCustomDataframe(1, 1)
- panel = tm.makePanel()
- func = lambda: df.to_excel('something.test')
- check_called(func)
- check_called(lambda: panel.to_excel('something.test'))
- val = get_option('io.excel.xlsx.writer')
- set_option('io.excel.xlsx.writer', 'dummy')
- check_called(lambda: df.to_excel('something.xlsx'))
- check_called(lambda: df.to_excel('something.xls', engine='dummy'))
- set_option('io.excel.xlsx.writer', val)
+ with pd.option_context('io.excel.xlsx.writer', 'dummy'):
+ register_writer(DummyClass)
+ writer = ExcelWriter('something.test')
+ tm.assertIsInstance(writer, DummyClass)
+ df = tm.makeCustomDataframe(1, 1)
+ panel = tm.makePanel()
+ func = lambda: df.to_excel('something.test')
+ check_called(func)
+ check_called(lambda: panel.to_excel('something.test'))
+ check_called(lambda: df.to_excel('something.xlsx'))
+ check_called(lambda: df.to_excel('something.xls', engine='dummy'))
if __name__ == '__main__':
diff --git a/pandas/io/tests/test_gbq.py b/pandas/io/tests/test_gbq.py
index 865b7e8d689c0..15e7d51106bdb 100644
--- a/pandas/io/tests/test_gbq.py
+++ b/pandas/io/tests/test_gbq.py
@@ -15,6 +15,7 @@
from pandas.core.frame import DataFrame
import pandas.io.gbq as gbq
import pandas.util.testing as tm
+from pandas.compat.numpy_compat import np_datetime64_compat
PROJECT_ID = None
PRIVATE_KEY_JSON_PATH = None
@@ -289,7 +290,7 @@ def test_should_return_bigquery_floats_as_python_floats(self):
def test_should_return_bigquery_timestamps_as_numpy_datetime(self):
result = gbq._parse_entry('0e9', 'TIMESTAMP')
- tm.assert_equal(result, np.datetime64('1970-01-01T00:00:00Z'))
+ tm.assert_equal(result, np_datetime64_compat('1970-01-01T00:00:00Z'))
def test_should_return_bigquery_booleans_as_python_booleans(self):
result = gbq._parse_entry('false', 'BOOLEAN')
diff --git a/pandas/io/tests/test_packers.py b/pandas/io/tests/test_packers.py
index 4c0e71698ad79..7c61a6942e8e7 100644
--- a/pandas/io/tests/test_packers.py
+++ b/pandas/io/tests/test_packers.py
@@ -1,5 +1,6 @@
import nose
+import warnings
import os
import datetime
import numpy as np
@@ -519,7 +520,8 @@ def test_sparse_frame(self):
def test_sparse_panel(self):
- with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ with warnings.catch_warnings(record=True):
+
items = ['x', 'y', 'z']
p = Panel(dict((i, tm.makeDataFrame().ix[:2, :2]) for i in items))
sp = p.to_sparse()
diff --git a/pandas/io/tests/test_pytables.py b/pandas/io/tests/test_pytables.py
index 92a59337b7e43..d21189fe91a2a 100644
--- a/pandas/io/tests/test_pytables.py
+++ b/pandas/io/tests/test_pytables.py
@@ -848,11 +848,11 @@ def test_append(self):
# uints - test storage of uints
uint_data = DataFrame({
- 'u08': Series(np.random.random_integers(0, high=255, size=5),
+ 'u08': Series(np.random.randint(0, high=255, size=5),
dtype=np.uint8),
- 'u16': Series(np.random.random_integers(0, high=65535, size=5),
+ 'u16': Series(np.random.randint(0, high=65535, size=5),
dtype=np.uint16),
- 'u32': Series(np.random.random_integers(0, high=2**30, size=5),
+ 'u32': Series(np.random.randint(0, high=2**30, size=5),
dtype=np.uint32),
'u64': Series([2**58, 2**59, 2**60, 2**61, 2**62],
dtype=np.uint64)}, index=np.arange(5))
diff --git a/pandas/tests/formats/test_format.py b/pandas/tests/formats/test_format.py
index ab547f943375f..47e1147840fc3 100644
--- a/pandas/tests/formats/test_format.py
+++ b/pandas/tests/formats/test_format.py
@@ -28,7 +28,7 @@
import IPython
if IPython.__version__ < LooseVersion('3.0.0'):
div_style = ' style="max-width:1500px;overflow:auto;"'
-except ImportError:
+except (ImportError, AttributeError):
pass
from pandas import DataFrame, Series, Index, Timestamp, MultiIndex, date_range, NaT
diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index b13b9d2ed2272..b522340be3171 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -21,6 +21,7 @@
CategoricalIndex, DatetimeIndex, TimedeltaIndex,
PeriodIndex)
from pandas.util.testing import assert_almost_equal
+from pandas.compat.numpy_compat import np_datetime64_compat
import pandas.core.config as cf
@@ -250,18 +251,18 @@ def test_constructor_dtypes(self):
for idx in [Index(np.array([1, 2, 3], dtype=int), dtype='category'),
Index([1, 2, 3], dtype='category'),
- Index(np.array([np.datetime64('2011-01-01'),
- np.datetime64('2011-01-02')]), dtype='category'),
+ Index(np.array([np_datetime64_compat('2011-01-01'),
+ np_datetime64_compat('2011-01-02')]), dtype='category'),
Index([datetime(2011, 1, 1), datetime(2011, 1, 2)], dtype='category')]:
self.assertIsInstance(idx, CategoricalIndex)
- for idx in [Index(np.array([np.datetime64('2011-01-01'),
- np.datetime64('2011-01-02')])),
+ for idx in [Index(np.array([np_datetime64_compat('2011-01-01'),
+ np_datetime64_compat('2011-01-02')])),
Index([datetime(2011, 1, 1), datetime(2011, 1, 2)])]:
self.assertIsInstance(idx, DatetimeIndex)
- for idx in [Index(np.array([np.datetime64('2011-01-01'),
- np.datetime64('2011-01-02')]), dtype=object),
+ for idx in [Index(np.array([np_datetime64_compat('2011-01-01'),
+ np_datetime64_compat('2011-01-02')]), dtype=object),
Index([datetime(2011, 1, 1),
datetime(2011, 1, 2)], dtype=object)]:
self.assertNotIsInstance(idx, DatetimeIndex)
@@ -442,8 +443,8 @@ def test_nanosecond_index_access(self):
self.assertEqual(
first_value,
- x[Timestamp(np.datetime64('2013-01-01 00:00:00.000000050+0000',
- 'ns'))])
+ x[Timestamp(np_datetime64_compat('2013-01-01 00:00:00.000000050+0000',
+ 'ns'))])
def test_comparators(self):
index = self.dateIndex
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index 5c83cdb1493dc..68864306525dc 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -11,6 +11,7 @@
import pandas.core.algorithms as algos
import pandas.util.testing as tm
import pandas.hashtable as hashtable
+from pandas.compat.numpy_compat import np_array_datetime64_compat
class TestMatch(tm.TestCase):
@@ -275,9 +276,10 @@ def test_on_index_object(self):
def test_datetime64_dtype_array_returned(self):
# GH 9431
- expected = np.array(['2015-01-03T00:00:00.000000000+0000',
- '2015-01-01T00:00:00.000000000+0000'],
- dtype='M8[ns]')
+ expected = np_array_datetime64_compat(
+ ['2015-01-03T00:00:00.000000000+0000',
+ '2015-01-01T00:00:00.000000000+0000'],
+ dtype='M8[ns]')
dt_index = pd.to_datetime(['2015-01-03T00:00:00.000000000+0000',
'2015-01-01T00:00:00.000000000+0000',
diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py
index 0a64bb058fbb4..1c5774a7e7e2e 100644
--- a/pandas/tests/test_base.py
+++ b/pandas/tests/test_base.py
@@ -14,6 +14,7 @@
from pandas import (Series, Index, DatetimeIndex, TimedeltaIndex, PeriodIndex,
Timedelta)
from pandas.compat import u, StringIO
+from pandas.compat.numpy_compat import np_array_datetime64_compat
from pandas.core.base import (FrozenList, FrozenNDArray, PandasDelegate,
NoNewAttributesMixin)
from pandas.tseries.base import DatetimeIndexOpsMixin
@@ -663,10 +664,10 @@ def test_value_counts_inferred(self):
expected_s = Series([3, 2, 1], index=idx)
tm.assert_series_equal(s.value_counts(), expected_s)
- expected = np.array(['2010-01-01 00:00:00Z',
- '2009-01-01 00:00:00Z',
- '2008-09-09 00:00:00Z'],
- dtype='datetime64[ns]')
+ expected = np_array_datetime64_compat(['2010-01-01 00:00:00Z',
+ '2009-01-01 00:00:00Z',
+ '2008-09-09 00:00:00Z'],
+ dtype='datetime64[ns]')
if isinstance(s, DatetimeIndex):
expected = DatetimeIndex(expected)
self.assertTrue(s.unique().equals(expected))
diff --git a/pandas/tseries/tests/test_converter.py b/pandas/tseries/tests/test_converter.py
index 1fe35838ef9ad..c50e3fa7b5174 100644
--- a/pandas/tseries/tests/test_converter.py
+++ b/pandas/tseries/tests/test_converter.py
@@ -8,6 +8,7 @@
from pandas.compat import u
import pandas.util.testing as tm
from pandas.tseries.offsets import Second, Milli, Micro
+from pandas.compat.numpy_compat import np_datetime64_compat
try:
import pandas.tseries.converter as converter
@@ -50,16 +51,16 @@ def test_conversion(self):
self.assertEqual(rs, xp)
# also testing datetime64 dtype (GH8614)
- rs = self.dtc.convert(np.datetime64('2012-01-01'), None, None)
+ rs = self.dtc.convert(np_datetime64_compat('2012-01-01'), None, None)
self.assertEqual(rs, xp)
- rs = self.dtc.convert(np.datetime64(
- '2012-01-01 00:00:00+00:00'), None, None)
+ rs = self.dtc.convert(np_datetime64_compat(
+ '2012-01-01 00:00:00+0000'), None, None)
self.assertEqual(rs, xp)
rs = self.dtc.convert(np.array([
- np.datetime64('2012-01-01 00:00:00+00:00'),
- np.datetime64('2012-01-02 00:00:00+00:00')]), None, None)
+ np_datetime64_compat('2012-01-01 00:00:00+0000'),
+ np_datetime64_compat('2012-01-02 00:00:00+0000')]), None, None)
self.assertEqual(rs[0], xp)
def test_conversion_float(self):
@@ -142,16 +143,19 @@ def test_conversion(self):
self.assertEqual(rs, xp)
# FIXME
- # rs = self.pc.convert(np.datetime64('2012-01-01'), None, self.axis)
+ # rs = self.pc.convert(
+ # np_datetime64_compat('2012-01-01'), None, self.axis)
# self.assertEqual(rs, xp)
#
- # rs = self.pc.convert(np.datetime64('2012-01-01 00:00:00+00:00'),
+ # rs = self.pc.convert(
+ # np_datetime64_compat('2012-01-01 00:00:00+0000'),
# None, self.axis)
# self.assertEqual(rs, xp)
#
# rs = self.pc.convert(np.array([
- # np.datetime64('2012-01-01 00:00:00+00:00'),
- # np.datetime64('2012-01-02 00:00:00+00:00')]), None, self.axis)
+ # np_datetime64_compat('2012-01-01 00:00:00+0000'),
+ # np_datetime64_compat('2012-01-02 00:00:00+0000')]),
+ # None, self.axis)
# self.assertEqual(rs[0], xp)
def test_integer_passthrough(self):
| https://api.github.com/repos/pandas-dev/pandas/pulls/13010 | 2016-04-27T14:57:16Z | 2016-04-27T18:32:25Z | 2016-04-27T18:32:25Z | 2016-04-27T18:32:25Z | |
support constructing Panel or Panel4D with scalar data, fixes #8285 | diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt
index d60fa718ae07c..5b2a788829ce3 100644
--- a/doc/source/whatsnew/v0.16.0.txt
+++ b/doc/source/whatsnew/v0.16.0.txt
@@ -622,3 +622,4 @@ Bug Fixes
- Bug in ``Series.values_counts`` with excluding ``NaN`` for categorical type ``Series`` with ``dropna=True`` (:issue:`9443`)
- Fixed mising numeric_only option for ``DataFrame.std/var/sem`` (:issue:`9201`)
+- Support constructing ``Panel`` or ``Panel4D`` with scalar data (:issue:`8285`)
diff --git a/pandas/core/panel.py b/pandas/core/panel.py
index b3fc9aec00271..7df23a54c737d 100644
--- a/pandas/core/panel.py
+++ b/pandas/core/panel.py
@@ -165,6 +165,13 @@ def _init_data(self, data, copy, dtype, **kwargs):
mgr = self._init_matrix(data, passed_axes, dtype=dtype, copy=copy)
copy = False
dtype = None
+ elif lib.isscalar(data) and all(x is not None for x in passed_axes):
+ if dtype is None:
+ dtype, data = _infer_dtype_from_scalar(data)
+ values = np.empty([len(x) for x in passed_axes], dtype=dtype)
+ values.fill(data)
+ mgr = self._init_matrix(values, passed_axes, dtype=dtype, copy=False)
+ copy = False
else: # pragma: no cover
raise PandasError('Panel constructor not properly called!')
diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py
index 744dd31755c81..841df36fa0a84 100644
--- a/pandas/tests/test_panel.py
+++ b/pandas/tests/test_panel.py
@@ -888,6 +888,21 @@ def test_constructor(self):
wp = Panel(vals, copy=True)
self.assertIsNot(wp.values, vals)
+ # GH #8285, test when scalar data is used to construct a Panel
+ # if dtype is not passed, it should be inferred
+ value_and_dtype = [(1, int), (3.14, float), ('foo', np.object_)]
+ for (val, dtype) in value_and_dtype:
+ wp = Panel(val, items=range(2), major_axis=range(3), minor_axis=range(4))
+ vals = np.empty((2, 3, 4), dtype=dtype)
+ vals.fill(val)
+ assert_panel_equal(wp, Panel(vals, dtype=dtype))
+
+ # test the case when dtype is passed
+ wp = Panel(1, items=range(2), major_axis=range(3), minor_axis=range(4), dtype=float)
+ vals = np.empty((2, 3, 4), dtype=float)
+ vals.fill(1)
+ assert_panel_equal(wp, Panel(vals, dtype=float))
+
def test_constructor_cast(self):
zero_filled = self.panel.fillna(0)
diff --git a/pandas/tests/test_panel4d.py b/pandas/tests/test_panel4d.py
index 94c6bb9e2a4aa..7d6332879cfb4 100644
--- a/pandas/tests/test_panel4d.py
+++ b/pandas/tests/test_panel4d.py
@@ -629,6 +629,21 @@ def test_constructor(self):
panel4d = Panel4D(vals, copy=True)
self.assertIsNot(panel4d.values, vals)
+ # GH #8285, test when scalar data is used to construct a Panel4D
+ # if dtype is not passed, it should be inferred
+ value_and_dtype = [(1, int), (3.14, float), ('foo', np.object_)]
+ for (val, dtype) in value_and_dtype:
+ panel4d = Panel4D(val, labels=range(2), items=range(3), major_axis=range(4), minor_axis=range(5))
+ vals = np.empty((2, 3, 4, 5), dtype=dtype)
+ vals.fill(val)
+ assert_panel4d_equal(panel4d, Panel4D(vals, dtype=dtype))
+
+ # test the case when dtype is passed
+ panel4d = Panel4D(1, labels=range(2), items=range(3), major_axis=range(4), minor_axis=range(5), dtype=float)
+ vals = np.empty((2, 3, 4, 5), dtype=float)
+ vals.fill(1)
+ assert_panel4d_equal(panel4d, Panel4D(vals, dtype=float))
+
def test_constructor_cast(self):
zero_filled = self.panel4d.fillna(0)
| this should fix https://github.com/pydata/pandas/issues/8285
| https://api.github.com/repos/pandas-dev/pandas/pulls/9640 | 2015-03-13T02:22:36Z | 2015-03-14T01:31:43Z | 2015-03-14T01:31:43Z | 2015-04-29T15:32:32Z |
Rearrange into logical sections and add relevant links | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index e6ae1d0a36bd1..876daa97313e8 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,4 +1,4 @@
-###Guidelines
+### Guidelines
All contributions, bug reports, bug fixes, documentation improvements,
enhancements and ideas are welcome.
@@ -14,8 +14,9 @@ looking for a quick way to help out.
```python
- print("I ♥ pandas!")
-
+ >>> from pandas import DataFrame
+ >>> df = DataFrame(...)
+ ...
```
- Include the full version string of pandas and it's dependencies. In recent (>0.12) versions
@@ -30,22 +31,21 @@ looking for a quick way to help out.
```python
>>> pd.show_versions()
```
-
- Explain what the expected behavior was, and what you saw instead.
#### Pull Requests
- - **Make sure the test suite passes** on your box, Use the provided `test_*.sh` scripts or tox.
- - Use [proper commit messages](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html):
- - a subject line with `< 80` chars.
- - One blank line.
- - Optionally, a commit message body.
- - Please reference relevant Github issues in your commit message using `GH1234`
- or `#1234`. Either style is fine but the '#' style generates noise when your rebase your PR.
- - `doc/source/vx.y.z.txt` contains an ongoing
- changelog for each release. Add an entry to this file
- as needed in your PR: document the fix, enhancement,
- or (unavoidable) breaking change.
+##### Testing:
+ - Every addition to the codebase whether it be a bug or new feature should have associated tests. The can be placed in the `tests` directory where your code change occurs.
+ - When writing tests, use 2.6 compatible `self.assertFoo` methods. Some polyfills such as `assertRaises`
+ can be found in `pandas.util.testing`.
+ - Do not attach doctrings to tests. Make the test itself readable and use comments if needed.
+ - **Make sure the test suite passes** on your box, use the provided `test_*.sh` scripts or tox. Pandas tests a variety of platforms and Python versions so be cognizant of cross-platorm considerations.
+ - Performance matters. Make sure your PR hasn't introduced performance regressions by using `test_perf.sh`. See [vbench performance tests](https://github.com/pydata/pandas/wiki/Performance-Testing) wiki for more information on running these tests.
+ - For more information on testing see [Testing advice and best practices in `pandas`](https://github.com/pydata/pandas/wiki/Testing)
+
+##### Documentation / Commit Messages:
+ - Docstrings follow the [numpydoc](https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt) format.
- Keep style fixes to a separate commit to make your PR more readable.
- An informal commit message format is in effect for the project. Please try
and adhere to it. Check `git log` for examples. Here are some common prefixes
@@ -57,18 +57,24 @@ looking for a quick way to help out.
- **BLD**: Updates to the build process/scripts
- **PERF**: Performance improvement
- **CLN**: Code cleanup
+ - Use [proper commit messages](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html):
+ - a subject line with `< 80` chars.
+ - One blank line.
+ - Optionally, a commit message body.
+ - Please reference relevant Github issues in your commit message using `GH1234`
+ or `#1234`. Either style is fine but the '#' style generates noise when your rebase your PR.
+ - `doc/source/vx.y.z.txt` contains an ongoing
+ changelog for each release. Add an entry to this file
+ as needed in your PR: document the fix, enhancement,
+ or (unavoidable) breaking change.
- Maintain backward-compatibility. Pandas has lots of users with lots of existing code. Don't break it.
- If you think breakage is required clearly state why as part of the PR.
- Be careful when changing method signatures.
- Add deprecation warnings where needed.
- - Performance matters. Make sure your PR hasn't introduced perf regressions by using `test_perf.sh`.
- - Docstrings follow the [numpydoc](https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt) format.
- - Write tests.
- - When writing tests, use 2.6 compatible `self.assertFoo` methods. Some polyfills such as `assertRaises`
- can be found in `pandas.util.testing`.
- - Do not attach doctrings to tests. Make the test itself readable and use comments if needed.
- Generally, pandas source files should not contain attributions. You can include a "thanks to..."
in the release changelog. The rest is `git blame`/`git log`.
+
+##### Workflow/Git
- When you start working on a PR, start by creating a new branch pointing at the latest
commit on github master.
- **Do not** merge upstream into a branch you're going to submit as a PR.
@@ -78,21 +84,22 @@ looking for a quick way to help out.
- Use `raise AssertionError` over `assert` unless you want the assertion stripped by `python -o`.
- The pandas copyright policy is detailed in the pandas [LICENSE](https://github.com/pydata/pandas/blob/master/LICENSE).
- On the subject of [PEP8](http://www.python.org/dev/peps/pep-0008/): yes.
+ - [Git tips and tricks](https://github.com/pydata/pandas/wiki/Using-Git)
+
+##### Code standards:
- We've written a tool to check that your commits are PEP8 great,
[`pip install pep8radius`](https://github.com/hayd/pep8radius). Look at PEP8 fixes in your branch
vs master with `pep8radius master --diff` and make these changes with
`pep8radius master --diff --in-place`.
- On the subject of a massive PEP8-storm touching everything: not too often (once per release works).
+ - Additional standards are outlined on the [code style wiki page](https://github.com/pydata/pandas/wiki/Code-Style-and-Conventions)
### Notes on plotting function conventions
https://groups.google.com/forum/#!topic/pystatsmodels/biNlCvJPNNY/discussion
-####More developer docs
-
+#### More developer docs
* See the [developers](http://pandas.pydata.org/developers.html) page on the
project website for more details.
-* [`pandas` wiki](https://github.com/pydata/pandas/wiki)
+* [`pandas` wiki](https://github.com/pydata/pandas/wiki) constains useful pages for development and general pandas usage
* [Tips and tricks](https://github.com/pydata/pandas/wiki/Tips-&-Tricks)
-* [Git tips and tricks](https://github.com/pydata/pandas/wiki/Using-Git)
-* [Testing advice and best practices in `pandas`](https://github.com/pydata/pandas/wiki/Testing)
| This rearranges the Contributing page into more logical sections and provides some more useful links to wiki pages. I think this should be the place where all relevant documentation on pandas development can be found. For example, both this page and the pandas homepage mention `vbench` but the information on running tests was lacking and it turns out that the wiki has this information but it was difficult to find. Hopefully this is a step in the right direction.
| https://api.github.com/repos/pandas-dev/pandas/pulls/9639 | 2015-03-13T01:03:45Z | 2015-03-13T07:48:21Z | 2015-03-13T07:48:21Z | 2015-03-13T16:54:25Z |
BLD: add conda recipe (GH8934) | diff --git a/.binstar.yml b/.binstar.yml
new file mode 100644
index 0000000000000..6f7c2c5ba4c7a
--- /dev/null
+++ b/.binstar.yml
@@ -0,0 +1,38 @@
+package: pandas
+user: jreback
+
+platform:
+ #- osx-64
+ #- linux-32
+ - linux-64
+ - win-64
+ #- win-32
+
+engine:
+ #- python=2.6
+ - python=2.7
+ #- python=3.3
+ #- python=3.4
+
+before_script:
+ - python -V
+
+script:
+ - conda build conda.recipe --quiet
+
+iotimeout: 600
+
+build_targets: conda
+
+notifications:
+ email:
+ recipients: ['jeff@reback.net']
+
+---
+platform: win-32
+engine: python=2.6
+exclude: true
+---
+platform: win-64
+engine: python=2.6
+exclude: true
diff --git a/conda.recipe/bld.bat b/conda.recipe/bld.bat
new file mode 100644
index 0000000000000..cc977c65dcbe1
--- /dev/null
+++ b/conda.recipe/bld.bat
@@ -0,0 +1,2 @@
+@echo off
+%PYTHON% setup.py install --quiet
diff --git a/conda.recipe/build.sh b/conda.recipe/build.sh
new file mode 100644
index 0000000000000..bce23bf0c6549
--- /dev/null
+++ b/conda.recipe/build.sh
@@ -0,0 +1,2 @@
+#!/bin/bash
+$PYTHON setup.py install --quiet
diff --git a/conda.recipe/meta.yaml b/conda.recipe/meta.yaml
new file mode 100644
index 0000000000000..6817fbc9b43e0
--- /dev/null
+++ b/conda.recipe/meta.yaml
@@ -0,0 +1,38 @@
+package:
+ name: pandas
+ version: {{ environ.get('GIT_DESCRIBE_TAG', '') }}
+
+build:
+ number: {{ environ.get('GIT_DESCRIBE_NUMBER', 0) }}
+
+source:
+ git_url: ../
+
+requirements:
+ build:
+ - python
+ - cython
+ - libpython # [win]
+ - numpy
+ - setuptools
+ - pytz
+ - dateutil
+
+ run:
+ - python
+ - numpy
+ - libpython # [win]
+ - dateutil
+ - pytz
+
+test:
+ requires:
+ - nose
+ - coverage
+
+ commands:
+ - python -c "import pandas"
+
+about:
+ home: http://pandas.pydata.org
+ license: BSD
| closes #8934
| https://api.github.com/repos/pandas-dev/pandas/pulls/9634 | 2015-03-11T20:46:10Z | 2015-03-11T20:46:30Z | 2015-03-11T20:46:30Z | 2015-03-20T14:48:59Z |
Return the right class, when subclassing a DataFrame with multi-level index | diff --git a/doc/source/whatsnew/v0.16.1.txt b/doc/source/whatsnew/v0.16.1.txt
index 56d940031119d..d422e7815a5a3 100755
--- a/doc/source/whatsnew/v0.16.1.txt
+++ b/doc/source/whatsnew/v0.16.1.txt
@@ -300,3 +300,4 @@ Bug Fixes
- Bug in ``transform`` when groups are equal in number and dtype to the input index (:issue:`9700`)
- Google BigQuery connector now imports dependencies on a per-method basis.(:issue:`9713`)
- Updated BigQuery connector to no longer use deprecated ``oauth2client.tools.run()`` (:issue:`8327`)
+- Bug in subclassed ``DataFrame``. It may not return the correct class, when slicing or subsetting it. (:issue:`9632`)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 01b0d65e055df..cf676b81388a2 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1839,7 +1839,7 @@ def _getitem_multilevel(self, key):
result.columns = result_columns
else:
new_values = self.values[:, loc]
- result = DataFrame(new_values, index=self.index,
+ result = self._constructor(new_values, index=self.index,
columns=result_columns).__finalize__(self)
if len(result.columns) == 1:
top = result.columns[0]
@@ -1847,7 +1847,7 @@ def _getitem_multilevel(self, key):
(type(top) == tuple and top[0] == '')):
result = result['']
if isinstance(result, Series):
- result = Series(result, index=self.index, name=key)
+ result = self._constructor_sliced(result, index=self.index, name=key)
result._set_is_copy(self)
return result
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 3f60f10e81013..4964d13f7ac28 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -2791,6 +2791,59 @@ def test_insert_error_msmgs(self):
with assertRaisesRegexp(TypeError, msg):
df['gr'] = df.groupby(['b', 'c']).count()
+ def test_frame_subclassing_and_slicing(self):
+ # Subclass frame and ensure it returns the right class on slicing it
+ # In reference to PR 9632
+
+ class CustomSeries(Series):
+ @property
+ def _constructor(self):
+ return CustomSeries
+
+ def custom_series_function(self):
+ return 'OK'
+
+ class CustomDataFrame(DataFrame):
+ "Subclasses pandas DF, fills DF with simulation results, adds some custom plotting functions."
+
+ def __init__(self, *args, **kw):
+ super(CustomDataFrame, self).__init__(*args, **kw)
+
+ @property
+ def _constructor(self):
+ return CustomDataFrame
+
+ _constructor_sliced = CustomSeries
+
+ def custom_frame_function(self):
+ return 'OK'
+
+ data = {'col1': range(10),
+ 'col2': range(10)}
+ cdf = CustomDataFrame(data)
+
+ # Did we get back our own DF class?
+ self.assertTrue(isinstance(cdf, CustomDataFrame))
+
+ # Do we get back our own Series class after selecting a column?
+ cdf_series = cdf.col1
+ self.assertTrue(isinstance(cdf_series, CustomSeries))
+ self.assertEqual(cdf_series.custom_series_function(), 'OK')
+
+ # Do we get back our own DF class after slicing row-wise?
+ cdf_rows = cdf[1:5]
+ self.assertTrue(isinstance(cdf_rows, CustomDataFrame))
+ self.assertEqual(cdf_rows.custom_frame_function(), 'OK')
+
+ # Make sure sliced part of multi-index frame is custom class
+ mcol = pd.MultiIndex.from_tuples([('A', 'A'), ('A', 'B')])
+ cdf_multi = CustomDataFrame([[0, 1], [2, 3]], columns=mcol)
+ self.assertTrue(isinstance(cdf_multi['A'], CustomDataFrame))
+
+ mcol = pd.MultiIndex.from_tuples([('A', ''), ('B', '')])
+ cdf_multi2 = CustomDataFrame([[0, 1], [2, 3]], columns=mcol)
+ self.assertTrue(isinstance(cdf_multi2['A'], CustomSeries))
+
def test_constructor_subclass_dict(self):
# Test for passing dict subclass to constructor
data = {'col1': tm.TestSubDict((x, 10.0 * x) for x in range(10)),
| Subclassing pandas.DataFrame had some issues, when a multi-level index was used. This PR should fix that.
| https://api.github.com/repos/pandas-dev/pandas/pulls/9632 | 2015-03-11T10:48:17Z | 2015-05-04T18:58:49Z | 2015-05-04T18:58:49Z | 2015-05-04T18:58:56Z |
DEPR: DatetimeIndex/PeriodsIndex +/- ops (GH9094) | diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt
index 2e910e32d4dfd..3f37b44f509ff 100644
--- a/doc/source/whatsnew/v0.16.0.txt
+++ b/doc/source/whatsnew/v0.16.0.txt
@@ -385,6 +385,8 @@ Deprecations
- The ``pandas.rpy`` interface is deprecated and will be removed in a future version.
Similar functionaility can be accessed thru the `rpy2 <http://rpy.sourceforge.net/>`_ project (:issue:`9602`)
+- Adding ``DatetimeIndex/PeriodIndex`` to another ``DatetimeIndex/PeriodIndex`` is being deprecated as a set-operation. This will be changed to a ``TypeError`` in a future version. ``.union()`` should be used for the union set operation. (:issue:`9094`)
+- Subtracting ``DatetimeIndex/PeriodIndex`` from another ``DatetimeIndex/PeriodIndex`` is being deprecated as a set-operation. This will be changed to an actual numeric subtraction yielding a ``TimeDeltaIndex`` in a future version. ``.difference()`` should be used for the differencing set operation. (:issue:`9094`)
.. _whatsnew_0160.prior_deprecations:
diff --git a/pandas/tseries/base.py b/pandas/tseries/base.py
index 048a9ff4b93a6..ed11b12871ce5 100644
--- a/pandas/tseries/base.py
+++ b/pandas/tseries/base.py
@@ -2,7 +2,7 @@
Base and utility classes for tseries type pandas objects.
"""
-
+import warnings
from datetime import datetime, time, timedelta
from pandas import compat
@@ -334,6 +334,8 @@ def __add__(self, other):
return other._add_delta(self)
raise TypeError("cannot add TimedeltaIndex and {typ}".format(typ=type(other)))
elif isinstance(other, Index):
+ warnings.warn("using '+' to provide set union with datetimelike Indexes is deprecated, "
+ "use .union()",FutureWarning)
return self.union(other)
elif isinstance(other, (DateOffset, timedelta, np.timedelta64, tslib.Timedelta)):
return self._add_delta(other)
@@ -357,6 +359,8 @@ def __sub__(self, other):
raise TypeError("cannot subtract TimedeltaIndex and {typ}".format(typ=type(other)))
return self._add_delta(-other)
elif isinstance(other, Index):
+ warnings.warn("using '-' to provide set differences with datetimelike Indexes is deprecated, "
+ "use .difference()",FutureWarning)
return self.difference(other)
elif isinstance(other, (DateOffset, timedelta, np.timedelta64, tslib.Timedelta)):
return self._add_delta(-other)
diff --git a/pandas/tseries/tests/test_base.py b/pandas/tseries/tests/test_base.py
index 3c9a94286509a..c42802bdb31ad 100644
--- a/pandas/tseries/tests/test_base.py
+++ b/pandas/tseries/tests/test_base.py
@@ -196,12 +196,16 @@ def test_add_iadd(self):
for rng, other, expected in [(rng1, other1, expected1), (rng2, other2, expected2),
(rng3, other3, expected3)]:
- result_add = rng + other
+ # GH9094
+ with tm.assert_produces_warning(FutureWarning):
+ result_add = rng + other
result_union = rng.union(other)
tm.assert_index_equal(result_add, expected)
tm.assert_index_equal(result_union, expected)
- rng += other
+ # GH9094
+ with tm.assert_produces_warning(FutureWarning):
+ rng += other
tm.assert_index_equal(rng, expected)
# offset
@@ -593,6 +597,50 @@ def _check(result, expected):
expected = DatetimeIndex(['20121231','20130101','20130102'],tz='US/Eastern')
tm.assert_index_equal(result,expected)
+ def test_dti_dti_deprecated_ops(self):
+
+ # deprecated in 0.16.0 (GH9094)
+ # change to return subtraction -> TimeDeltaIndex in 0.17.0
+ # shoudl move to the appropriate sections above
+
+ dti = date_range('20130101',periods=3)
+ dti_tz = date_range('20130101',periods=3).tz_localize('US/Eastern')
+
+ with tm.assert_produces_warning(FutureWarning):
+ result = dti-dti
+ expected = Index([])
+ tm.assert_index_equal(result,expected)
+
+ with tm.assert_produces_warning(FutureWarning):
+ result = dti+dti
+ expected = dti
+ tm.assert_index_equal(result,expected)
+
+ with tm.assert_produces_warning(FutureWarning):
+ result = dti_tz-dti_tz
+ expected = Index([])
+ tm.assert_index_equal(result,expected)
+
+ with tm.assert_produces_warning(FutureWarning):
+ result = dti_tz+dti_tz
+ expected = dti_tz
+ tm.assert_index_equal(result,expected)
+
+ with tm.assert_produces_warning(FutureWarning):
+ result = dti_tz-dti
+ expected = dti_tz
+ tm.assert_index_equal(result,expected)
+
+ with tm.assert_produces_warning(FutureWarning):
+ result = dti-dti_tz
+ expected = dti
+ tm.assert_index_equal(result,expected)
+
+ with tm.assert_produces_warning(FutureWarning):
+ self.assertRaises(TypeError, lambda : dti_tz+dti)
+ with tm.assert_produces_warning(FutureWarning):
+ self.assertRaises(TypeError, lambda : dti+dti_tz)
+
def test_dti_tdi_numeric_ops(self):
# These are normally union/diff set-like ops
@@ -909,13 +957,19 @@ def test_add_iadd(self):
(rng5, other5, expected5), (rng6, other6, expected6),
(rng7, other7, expected7)]:
- result_add = rng + other
+ # GH9094
+ with tm.assert_produces_warning(FutureWarning):
+ result_add = rng + other
+
result_union = rng.union(other)
tm.assert_index_equal(result_add, expected)
tm.assert_index_equal(result_union, expected)
+
# GH 6527
- rng += other
+ # GH9094
+ with tm.assert_produces_warning(FutureWarning):
+ rng += other
tm.assert_index_equal(rng, expected)
# offset
| closes #9094
closes #9095
deprecate `DatetimeIndex/PeriodIndex` `+/-` ops which are set ops. In a future version `-` will produce a `TimeDeltaIndex` and `+` a `TypeError`
| https://api.github.com/repos/pandas-dev/pandas/pulls/9630 | 2015-03-11T01:53:16Z | 2015-03-11T10:21:42Z | 2015-03-11T10:21:41Z | 2015-03-11T10:21:42Z |
TST/DOC: Fix tests and docs for .cat raising AttributeError if invalid | diff --git a/doc/source/categorical.rst b/doc/source/categorical.rst
index 91cfa77bc618c..8eb235d46e6ed 100644
--- a/doc/source/categorical.rst
+++ b/doc/source/categorical.rst
@@ -766,6 +766,14 @@ Dtype comparisons work:
dtype == np.str_
np.str_ == dtype
+To check if a Series contains Categorical data, with pandas 0.16 or later, use
+``hasattr(s, 'cat')``:
+
+.. ipython:: python
+
+ hasattr(Series(['a'], dtype='category'), 'cat')
+ hasattr(Series(['a']), 'cat')
+
Using `numpy` functions on a `Series` of type ``category`` should not work as `Categoricals`
are not numeric data (even in the case that ``.categories`` is numeric).
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index c29e97b423fe1..3db531c946d01 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -78,10 +78,11 @@ class NDFrame(PandasObject):
copy : boolean, default False
"""
_internal_names = ['_data', '_cacher', '_item_cache', '_cache',
- 'is_copy', 'dt', 'cat', 'str', '_subtyp', '_index',
+ 'is_copy', '_subtyp', '_index',
'_default_kind', '_default_fill_value',
'__array_struct__','__array_interface__']
_internal_names_set = set(_internal_names)
+ _accessors = frozenset([])
_metadata = []
is_copy = None
@@ -1957,9 +1958,9 @@ def __getattr__(self, name):
# Note: obj.x will always call obj.__getattribute__('x') prior to
# calling obj.__getattr__('x').
- if name in self._internal_names_set:
- return object.__getattribute__(self, name)
- elif name in self._metadata:
+ if (name in self._internal_names_set
+ or name in self._metadata
+ or name in self._accessors):
return object.__getattribute__(self, name)
else:
if name in self._info_axis:
diff --git a/pandas/core/series.py b/pandas/core/series.py
index a83a6291e6c81..d34657f0dc256 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -113,6 +113,7 @@ class Series(base.IndexOpsMixin, generic.NDFrame):
Copy input data
"""
_metadata = ['name']
+ _accessors = frozenset(['dt', 'cat', 'str'])
_allow_index_ops = True
def __init__(self, data=None, index=None, dtype=None, name=None,
diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py
index a77f3984105cc..d27fb39ec65e9 100644
--- a/pandas/tests/test_categorical.py
+++ b/pandas/tests/test_categorical.py
@@ -1354,13 +1354,13 @@ def test_sequence_like(self):
def test_series_delegations(self):
# invalid accessor
- self.assertRaises(TypeError, lambda : Series([1,2,3]).cat)
- tm.assertRaisesRegexp(TypeError,
+ self.assertRaises(AttributeError, lambda : Series([1,2,3]).cat)
+ tm.assertRaisesRegexp(AttributeError,
r"Can only use .cat accessor with a 'category' dtype",
lambda : Series([1,2,3]).cat)
- self.assertRaises(TypeError, lambda : Series(['a','b','c']).cat)
- self.assertRaises(TypeError, lambda : Series(np.arange(5.)).cat)
- self.assertRaises(TypeError, lambda : Series([Timestamp('20130101')]).cat)
+ self.assertRaises(AttributeError, lambda : Series(['a','b','c']).cat)
+ self.assertRaises(AttributeError, lambda : Series(np.arange(5.)).cat)
+ self.assertRaises(AttributeError, lambda : Series([Timestamp('20130101')]).cat)
# Series should delegate calls to '.categories', '.codes', '.ordered' and the
# methods '.set_categories()' 'drop_unused_categories()' to the categorical
| Follow-up on #9617
Fixes #8814 -- is it fair to say that `hasattr(s, 'cat')` is probably
the best solution we're going to come up with for checking for categorical
data?
CC @jreback @jorisvandenbossche @JanSchulz
| https://api.github.com/repos/pandas-dev/pandas/pulls/9629 | 2015-03-11T00:21:03Z | 2015-03-11T01:35:33Z | 2015-03-11T01:35:32Z | 2015-03-11T01:35:35Z |
Fix table name on comparison with SQL | diff --git a/doc/source/comparison_with_sql.rst b/doc/source/comparison_with_sql.rst
index 371875d9996f9..5dc083db7d147 100644
--- a/doc/source/comparison_with_sql.rst
+++ b/doc/source/comparison_with_sql.rst
@@ -204,7 +204,7 @@ Grouping by more than one column is done by passing a list of columns to the
.. code-block:: sql
SELECT smoker, day, COUNT(*), AVG(tip)
- FROM tip
+ FROM tips
GROUP BY smoker, day;
/*
smoker day
| All the other examples use the table name "tips"
| https://api.github.com/repos/pandas-dev/pandas/pulls/9628 | 2015-03-10T23:15:28Z | 2015-03-11T00:18:33Z | 2015-03-11T00:18:32Z | 2015-03-11T00:18:33Z |
improve error message when importing pandas from source directory | diff --git a/pandas/__init__.py b/pandas/__init__.py
index 939495d3687ad..2a142a6ff2072 100644
--- a/pandas/__init__.py
+++ b/pandas/__init__.py
@@ -4,17 +4,13 @@
__docformat__ = 'restructuredtext'
try:
- from . import hashtable, tslib, lib
-except Exception: # pragma: no cover
- import sys
- e = sys.exc_info()[1] # Py25 and Py3 current exception syntax conflict
- print(e)
- if 'No module named lib' in str(e):
- raise ImportError('C extensions not built: if you installed already '
- 'verify that you are not importing from the source '
- 'directory')
- else:
- raise
+ from pandas import hashtable, tslib, lib
+except ImportError as e: # pragma: no cover
+ module = str(e).lstrip('cannot import name ') # hack but overkill to use re
+ raise ImportError("C extension: {0} not built. If you want to import "
+ "pandas from the source directory, you may need to run "
+ "'python setup.py build_ext --inplace' to build the C "
+ "extensions first.".format(module))
from datetime import datetime
import numpy as np
| Currently if one imports from the source directory without building the C extension the error message is not very helpful:
`ImportError: cannot import name 'hashtable'`
I see a few previous PRs (https://github.com/pydata/pandas/pull/3827, https://github.com/pydata/pandas/pull/3821) that tried to address this but somehow this is still the behavior on `master`.
With this PR the error message would be a lot more informative:
```
ImportError: C extension: 'hashtable' not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace' to build the C extensions first.
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/9626 | 2015-03-10T18:46:43Z | 2015-05-04T22:41:49Z | 2015-05-04T22:41:49Z | 2015-05-05T00:09:03Z |
API: deprecate setting of .ordered directly (GH9347, GH9190) | diff --git a/doc/source/api.rst b/doc/source/api.rst
index 7fbb432f0be6b..58ea517d055a0 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -585,6 +585,8 @@ following usable methods and properties (all available as ``Series.cat.<method_o
Categorical.remove_categories
Categorical.remove_unused_categories
Categorical.set_categories
+ Categorical.as_ordered
+ Categorical.as_unordered
Categorical.codes
To create a Series of dtype ``category``, use ``cat = s.astype("category")``.
diff --git a/doc/source/categorical.rst b/doc/source/categorical.rst
index 8eb235d46e6ed..6ce93326f0e16 100644
--- a/doc/source/categorical.rst
+++ b/doc/source/categorical.rst
@@ -90,8 +90,6 @@ By using some special functions:
See :ref:`documentation <reshaping.tile.cut>` for :func:`~pandas.cut`.
By passing a :class:`pandas.Categorical` object to a `Series` or assigning it to a `DataFrame`.
-This is the only possibility to specify differently ordered categories (or no order at all) at
-creation time and the only reason to use :class:`pandas.Categorical` directly:
.. ipython:: python
@@ -103,6 +101,14 @@ creation time and the only reason to use :class:`pandas.Categorical` directly:
df["B"] = raw_cat
df
+You can also specify differently ordered categories or make the resulting data ordered, by passing these arguments to ``astype()``:
+
+.. ipython:: python
+
+ s = Series(["a","b","c","a"])
+ s_cat = s.astype("category", categories=["b","c","d"], ordered=False)
+ s_cat
+
Categorical data has a specific ``category`` :ref:`dtype <basics.dtypes>`:
.. ipython:: python
@@ -176,10 +182,9 @@ It's also possible to pass in the categories in a specific order:
s.cat.ordered
.. note::
- New categorical data is automatically ordered if the passed in values are sortable or a
- `categories` argument is supplied. This is a difference to R's `factors`, which are unordered
- unless explicitly told to be ordered (``ordered=TRUE``). You can of course overwrite that by
- passing in an explicit ``ordered=False``.
+
+ New categorical data are NOT automatically ordered. You must explicity pass ``ordered=True`` to
+ indicate an ordered ``Categorical``.
Renaming categories
@@ -270,29 +275,37 @@ Sorting and Order
.. _categorical.sort:
+.. warning::
+
+ The default for construction has change in v0.16.0 to ``ordered=False``, from the prior implicit ``ordered=True``
+
If categorical data is ordered (``s.cat.ordered == True``), then the order of the categories has a
-meaning and certain operations are possible. If the categorical is unordered, a `TypeError` is
-raised.
+meaning and certain operations are possible. If the categorical is unordered, ``.min()/.max()`` will raise a `TypeError`.
.. ipython:: python
s = Series(Categorical(["a","b","c","a"], ordered=False))
- try:
- s.sort()
- except TypeError as e:
- print("TypeError: " + str(e))
- s = Series(["a","b","c","a"], dtype="category") # ordered per default!
+ s.sort()
+ s = Series(["a","b","c","a"]).astype('category', ordered=True)
s.sort()
s
s.min(), s.max()
+You can set categorical data to be ordered by using ``as_ordered()`` or unordered by using ``as_unordered()``. These will by
+default return a *new* object.
+
+.. ipython:: python
+
+ s.cat.as_ordered()
+ s.cat.as_unordered()
+
Sorting will use the order defined by categories, not any lexical order present on the data type.
This is even true for strings and numeric data:
.. ipython:: python
s = Series([1,2,3,1], dtype="category")
- s.cat.categories = [2,3,1]
+ s = s.cat.set_categories([2,3,1], ordered=True)
s
s.sort()
s
@@ -310,7 +323,7 @@ necessarily make the sort order the same as the categories order.
.. ipython:: python
s = Series([1,2,3,1], dtype="category")
- s = s.cat.reorder_categories([2,3,1])
+ s = s.cat.reorder_categories([2,3,1], ordered=True)
s
s.sort()
s
@@ -339,7 +352,7 @@ The ordering of the categorical is determined by the ``categories`` of that colu
.. ipython:: python
- dfs = DataFrame({'A' : Categorical(list('bbeebbaa'),categories=['e','a','b']),
+ dfs = DataFrame({'A' : Categorical(list('bbeebbaa'),categories=['e','a','b'],ordered=True),
'B' : [1,2,1,2,2,1,2,1] })
dfs.sort(['A','B'])
@@ -664,9 +677,6 @@ The following differences to R's factor functions can be observed:
* R's `levels` are named `categories`
* R's `levels` are always of type string, while `categories` in pandas can be of any dtype.
-* New categorical data is automatically ordered if the passed in values are sortable or a
- `categories` argument is supplied. This is a difference to R's `factors`, which are unordered
- unless explicitly told to be ordered (``ordered=TRUE``).
* It's not possible to specify labels at creation time. Use ``s.cat.rename_categories(new_labels)``
afterwards.
* In contrast to R's `factor` function, using categorical data as the sole input to create a
diff --git a/doc/source/release.rst b/doc/source/release.rst
index d3d9f031f4598..b60a47bb72daa 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -59,6 +59,7 @@ Highlights include:
- ``Series.to_coo/from_coo`` methods to interact with ``scipy.sparse``, see :ref:`here <whatsnew_0160.enhancements.sparse>`
- Backwards incompatible change to ``Timedelta`` to conform the ``.seconds`` attribute with ``datetime.timedelta``, see :ref:`here <whatsnew_0160.api_breaking.timedelta>`
- Changes to the ``.loc`` slicing API to conform with the behavior of ``.ix`` see :ref:`here <whatsnew_0160.api_breaking.indexing>`
+- Changes to the default for ordering in the ``Categorical`` constructor, see :ref:`here <whatsnew_0160.api_breaking.categorical>`
See the :ref:`v0.16.0 Whatsnew <whatsnew_0160>` overview or the issue tracker on GitHub for an extensive list
of all API changes, enhancements and bugs that have been fixed in 0.16.0.
diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt
index 3f37b44f509ff..882dcce8c8164 100644
--- a/doc/source/whatsnew/v0.16.0.txt
+++ b/doc/source/whatsnew/v0.16.0.txt
@@ -13,6 +13,7 @@ users upgrade to this version.
* ``Series.to_coo/from_coo`` methods to interact with ``scipy.sparse``, see :ref:`here <whatsnew_0160.enhancements.sparse>`
* Backwards incompatible change to ``Timedelta`` to conform the ``.seconds`` attribute with ``datetime.timedelta``, see :ref:`here <whatsnew_0160.api_breaking.timedelta>`
* Changes to the ``.loc`` slicing API to conform with the behavior of ``.ix`` see :ref:`here <whatsnew_0160.api_breaking.indexing>`
+ * Changes to the default for ordering in the ``Categorical`` constructor, see :ref:`here <whatsnew_0160.api_breaking.categorical>`
- Check the :ref:`API Changes <whatsnew_0160.api>` and :ref:`deprecations <whatsnew_0160.deprecations>` before updating
@@ -366,6 +367,134 @@ API Changes
- ``Series.describe`` for categorical data will now give counts and frequencies of 0, not ``NaN``, for unused categories (:issue:`9443`)
+Categorical Changes
+~~~~~~~~~~~~~~~~~~~
+
+.. _whatsnew_0160.api_breaking.categorical:
+
+In prior versions, ``Categoricals`` that had an unspecified ordering (meaning no ``ordered`` keyword was passed) were defaulted as ``ordered`` Categoricals. Going forward, the ``ordered`` keyword in the ``Categorical`` constructor will default to ``False``. Ordering must now be explicit.
+
+Furthermore, previously you *could* change the ``ordered`` attribute of a Categorical by just setting the attribute, e.g. ``cat.ordered=True``; This is now deprecated and you should use ``cat.as_ordered()`` or ``cat.as_unordered()``. These will by default return a **new** object and not modify the existing object. (:issue:`9347`, :issue:`9190`)
+
+Previous Behavior
+
+.. code-block:: python
+
+ In [3]: s = Series([0,1,2], dtype='category')
+
+ In [4]: s
+ Out[4]:
+ 0 0
+ 1 1
+ 2 2
+ dtype: category
+ Categories (3, int64): [0 < 1 < 2]
+
+ In [5]: s.cat.ordered
+ Out[5]: True
+
+ In [6]: s.cat.ordered = False
+
+ In [7]: s
+ Out[7]:
+ 0 0
+ 1 1
+ 2 2
+ dtype: category
+ Categories (3, int64): [0, 1, 2]
+
+New Behavior
+
+.. ipython:: python
+
+ s = Series([0,1,2], dtype='category')
+ s
+ s.cat.ordered
+ s = s.cat.as_ordered()
+ s
+ s.cat.ordered
+
+ # you can set in the constructor of the Categorical
+ s = Series(Categorical([0,1,2],ordered=True))
+ s
+ s.cat.ordered
+
+For ease of creation of series of categorical data, we have added the ability to pass keywords when calling ``.astype()``. These are passed directly to the constructor.
+
+.. ipython:: python
+
+ s = Series(["a","b","c","a"]).astype('category',ordered=True)
+ s
+ s = Series(["a","b","c","a"]).astype('category',categories=list('abcdef'),ordered=False)
+ s
+
+Indexing Changes
+~~~~~~~~~~~~~~~~
+
+.. _whatsnew_0160.api_breaking.indexing:
+
+The behavior of a small sub-set of edge cases for using ``.loc`` have changed (:issue:`8613`). Furthermore we have improved the content of the error messages that are raised:
+
+- slicing with ``.loc`` where the start and/or stop bound is not found in the index is now allowed; this previously would raise a ``KeyError``. This makes the behavior the same as ``.ix`` in this case. This change is only for slicing, not when indexing with a single label.
+
+.. ipython:: python
+
+ df = DataFrame(np.random.randn(5,4),
+ columns=list('ABCD'),
+ index=date_range('20130101',periods=5))
+ df
+ s = Series(range(5),[-2,-1,1,2,3])
+ s
+
+ Previous Behavior
+
+ .. code-block:: python
+
+ In [4]: df.loc['2013-01-02':'2013-01-10']
+ KeyError: 'stop bound [2013-01-10] is not in the [index]'
+
+ In [6]: s.loc[-10:3]
+ KeyError: 'start bound [-10] is not the [index]'
+
+ New Behavior
+
+ .. ipython:: python
+
+ df.loc['2013-01-02':'2013-01-10']
+ s.loc[-10:3]
+
+- allow slicing with float-like values on an integer index for ``.ix``. Previously this was only enabled for ``.loc``:
+
+ Previous Behavior
+
+ .. code-block:: python
+
+ In [8]: s.ix[-1.0:2]
+ TypeError: the slice start value [-1.0] is not a proper indexer for this index type (Int64Index)
+
+ New Behavior
+
+ .. ipython:: python
+
+ s.ix[-1.0:2]
+
+- provide a useful exception for indexing with an invalid type for that index when using ``.loc``. For example trying to use ``.loc`` on an index of type ``DatetimeIndex`` or ``PeriodIndex`` or ``TimedeltaIndex``, with an integer (or a float).
+
+ Previous Behavior
+
+ .. code-block:: python
+
+ In [4]: df.loc[2:3]
+ KeyError: 'start bound [2] is not the [index]'
+
+ New Behavior
+
+ .. code-block:: python
+
+ In [4]: df.loc[2:3]
+ TypeError: Cannot do slice indexing on <class 'pandas.tseries.index.DatetimeIndex'> with <type 'int'> keys
+
+
.. _whatsnew_0160.deprecations:
Deprecations
diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py
index f4246ed057c89..991678a8e7d79 100644
--- a/pandas/core/categorical.py
+++ b/pandas/core/categorical.py
@@ -17,7 +17,7 @@
from pandas.core.common import (CategoricalDtype, ABCSeries, isnull, notnull,
is_categorical_dtype, is_integer_dtype, is_object_dtype,
_possibly_infer_to_datetimelike, get_dtype_kinds,
- is_list_like, is_sequence, is_null_slice,
+ is_list_like, is_sequence, is_null_slice, is_bool,
_ensure_platform_int, _ensure_object, _ensure_int64,
_coerce_indexer_dtype, _values_from_object, take_1d)
from pandas.util.terminal import get_terminal_size
@@ -139,9 +139,9 @@ class Categorical(PandasObject):
categories : Index-like (unique), optional
The unique categories for this categorical. If not given, the categories are assumed
to be the unique values of values.
- ordered : boolean, optional
+ ordered : boolean, (default False)
Whether or not this categorical is treated as a ordered categorical. If not given,
- the resulting categorical will be ordered if values can be sorted.
+ the resulting categorical will not be ordered.
name : str, optional
Name for the Categorical variable. If name is None, will attempt
to infer from values.
@@ -184,7 +184,6 @@ class Categorical(PandasObject):
dtype = CategoricalDtype()
"""The dtype (always "category")"""
- ordered = None
"""Whether or not this Categorical is ordered.
Only ordered `Categoricals` can be sorted (according to the order
@@ -201,10 +200,9 @@ class Categorical(PandasObject):
# For comparisons, so that numpy uses our implementation if the compare ops, which raise
__array_priority__ = 1000
_typ = 'categorical'
- ordered = False
name = None
- def __init__(self, values, categories=None, ordered=None, name=None, fastpath=False,
+ def __init__(self, values, categories=None, ordered=False, name=None, fastpath=False,
levels=None):
if fastpath:
@@ -212,7 +210,7 @@ def __init__(self, values, categories=None, ordered=None, name=None, fastpath=Fa
self._codes = _coerce_indexer_dtype(values, categories)
self.name = name
self.categories = categories
- self.ordered = ordered
+ self._ordered = ordered
return
if name is None:
@@ -237,8 +235,6 @@ def __init__(self, values, categories=None, ordered=None, name=None, fastpath=Fa
cat = values.values
if categories is None:
categories = cat.categories
- if ordered is None:
- ordered = cat.ordered
values = values.__array__()
elif isinstance(values, Index):
@@ -264,10 +260,6 @@ def __init__(self, values, categories=None, ordered=None, name=None, fastpath=Fa
if categories is None:
try:
codes, categories = factorize(values, sort=True)
- # If the underlying data structure was sortable, and the user doesn't want to
- # "forget" this order, the categorical also is sorted/ordered
- if ordered is None:
- ordered = True
except TypeError:
codes, categories = factorize(values, sort=False)
if ordered:
@@ -300,12 +292,7 @@ def __init__(self, values, categories=None, ordered=None, name=None, fastpath=Fa
warn("None of the categories were found in values. Did you mean to use\n"
"'Categorical.from_codes(codes, categories)'?", RuntimeWarning)
- # if we got categories, we can assume that the order is intended
- # if ordered is unspecified
- if ordered is None:
- ordered = True
-
- self.ordered = False if ordered is None else ordered
+ self.set_ordered(ordered, inplace=True)
self.categories = categories
self.name = name
self._codes = _coerce_indexer_dtype(codes, categories)
@@ -360,7 +347,7 @@ def from_codes(cls, codes, categories, ordered=False, name=None):
An integer array, where each integer points to a category in categories or -1 for NaN
categories : index-like
The categories for the categorical. Items need to be unique.
- ordered : boolean, optional
+ ordered : boolean, (default False)
Whether or not this categorical is treated as a ordered categorical. If not given,
the resulting categorical will be unordered.
name : str, optional
@@ -460,6 +447,61 @@ def _get_levels(self):
# TODO: Remove after deprecation period in 2017/ after 0.18
levels = property(fget=_get_levels, fset=_set_levels)
+ _ordered = None
+
+ def _set_ordered(self, value):
+ """ Sets the ordered attribute to the boolean value """
+ warn("Setting 'ordered' directly is deprecated, use 'set_ordered'", FutureWarning)
+ self.set_ordered(value, inplace=True)
+
+ def set_ordered(self, value, inplace=False):
+ """
+ Sets the ordered attribute to the boolean value
+
+ Parameters
+ ----------
+ value : boolean to set whether this categorical is ordered (True) or not (False)
+ inplace : boolean (default: False)
+ Whether or not to set the ordered attribute inplace or return a copy of this categorical
+ with ordered set to the value
+ """
+ if not is_bool(value):
+ raise TypeError("ordered must be a boolean value")
+ cat = self if inplace else self.copy()
+ cat._ordered = value
+ if not inplace:
+ return cat
+
+ def as_ordered(self, inplace=False):
+ """
+ Sets the Categorical to be ordered
+
+ Parameters
+ ----------
+ inplace : boolean (default: False)
+ Whether or not to set the ordered attribute inplace or return a copy of this categorical
+ with ordered set to True
+ """
+ return self.set_ordered(True, inplace=inplace)
+
+ def as_unordered(self, inplace=False):
+ """
+ Sets the Categorical to be unordered
+
+ Parameters
+ ----------
+ inplace : boolean (default: False)
+ Whether or not to set the ordered attribute inplace or return a copy of this categorical
+ with ordered set to False
+ """
+ return self.set_ordered(False, inplace=inplace)
+
+ def _get_ordered(self):
+ """ Gets the ordered attribute """
+ return self._ordered
+
+ ordered = property(fget=_get_ordered, fset=_set_ordered)
+
def set_categories(self, new_categories, ordered=None, rename=False, inplace=False):
""" Sets the categories to the specified new_categories.
@@ -486,7 +528,7 @@ def set_categories(self, new_categories, ordered=None, rename=False, inplace=Fal
----------
new_categories : Index-like
The categories in new order.
- ordered : boolean, optional
+ ordered : boolean, (default: False)
Whether or not the categorical is treated as a ordered categorical. If not given,
do not change the ordered information.
rename : boolean (default: False)
@@ -520,8 +562,9 @@ def set_categories(self, new_categories, ordered=None, rename=False, inplace=Fal
cat._codes = _get_codes_for_values(values, new_categories)
cat._categories = new_categories
- if not ordered is None:
- cat.ordered = ordered
+ if ordered is None:
+ ordered = self.ordered
+ cat.set_ordered(ordered, inplace=True)
if not inplace:
return cat
@@ -765,6 +808,15 @@ def __setstate__(self, state):
state['_categories'] = \
self._validate_categories(state.pop('_levels'))
+ # 0.16.0 ordered change
+ if '_ordered' not in state:
+
+ # >=15.0 < 0.16.0
+ if 'ordered' in state:
+ state['_ordered'] = state.pop('ordered')
+ else:
+ state['_ordered'] = False
+
for k, v in compat.iteritems(state):
setattr(self, k, v)
@@ -827,7 +879,8 @@ def searchsorted(self, v, side='left', sorter=None):
array([3, 5]) # eggs after donuts, after switching milk and donuts
"""
if not self.ordered:
- raise ValueError("searchsorted requires an ordered Categorical.")
+ raise ValueError("Categorical not ordered\n"
+ "you can use .as_ordered() to change the Categorical to an ordered one\n")
from pandas.core.series import Series
values_as_codes = self.categories.values.searchsorted(Series(v).values, side)
@@ -943,6 +996,12 @@ def get_values(self):
return np.array(self)
+ def check_for_ordered(self, op):
+ """ assert that we are ordered """
+ if not self.ordered:
+ raise TypeError("Categorical is not ordered for operation {op}\n"
+ "you can use .as_ordered() to change the Categorical to an ordered one\n".format(op=op))
+
def argsort(self, ascending=True, **kwargs):
""" Implements ndarray.argsort.
@@ -954,8 +1013,6 @@ def argsort(self, ascending=True, **kwargs):
-------
argsorted : numpy array
"""
- if not self.ordered:
- raise TypeError("Categorical not ordered")
result = np.argsort(self._codes.copy(), **kwargs)
if not ascending:
result = result[::-1]
@@ -986,8 +1043,6 @@ def order(self, inplace=False, ascending=True, na_position='last'):
--------
Category.sort
"""
- if not self.ordered:
- raise TypeError("Categorical not ordered")
if na_position not in ['last','first']:
raise ValueError('invalid na_position: {!r}'.format(na_position))
@@ -1367,8 +1422,7 @@ def min(self, numeric_only=None, **kwargs):
-------
min : the minimum of this `Categorical`
"""
- if not self.ordered:
- raise TypeError("Categorical not ordered")
+ self.check_for_ordered('min')
if numeric_only:
good = self._codes != -1
pointer = self._codes[good].min(**kwargs)
@@ -1394,8 +1448,7 @@ def max(self, numeric_only=None, **kwargs):
-------
max : the maximum of this `Categorical`
"""
- if not self.ordered:
- raise TypeError("Categorical not ordered")
+ self.check_for_ordered('max')
if numeric_only:
good = self._codes != -1
pointer = self._codes[good].max(**kwargs)
@@ -1498,6 +1551,8 @@ class CategoricalAccessor(PandasDelegate):
>>> s.cat.remove_categories(['d'])
>>> s.cat.remove_unused_categories()
>>> s.cat.set_categories(list('abcde'))
+ >>> s.cat.as_ordered()
+ >>> s.cat.as_unordered()
"""
@@ -1533,7 +1588,9 @@ def _delegate_method(self, name, *args, **kwargs):
"add_categories",
"remove_categories",
"remove_unused_categories",
- "set_categories"],
+ "set_categories",
+ "as_ordered",
+ "as_unordered"],
typ='method')
##### utility routines #####
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 3db531c946d01..d76c526237f76 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2209,7 +2209,7 @@ def blocks(self):
"Internal property, property synonym for as_blocks()"
return self.as_blocks()
- def astype(self, dtype, copy=True, raise_on_error=True):
+ def astype(self, dtype, copy=True, raise_on_error=True, **kwargs):
"""
Cast object to input numpy.dtype
Return a copy when copy = True (be really careful with this!)
@@ -2218,6 +2218,7 @@ def astype(self, dtype, copy=True, raise_on_error=True):
----------
dtype : numpy.dtype or Python type
raise_on_error : raise on invalid input
+ kwargs : keyword arguments to pass on to the constructor
Returns
-------
@@ -2225,7 +2226,7 @@ def astype(self, dtype, copy=True, raise_on_error=True):
"""
mgr = self._data.astype(
- dtype=dtype, copy=copy, raise_on_error=raise_on_error)
+ dtype=dtype, copy=copy, raise_on_error=raise_on_error, **kwargs)
return self._constructor(mgr).__finalize__(self)
def copy(self, deep=True):
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 05947eec8cfaf..73439fb1e535d 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -1923,8 +1923,18 @@ def __init__(self, index, grouper=None, obj=None, name=None, level=None,
# a passed Categorical
elif isinstance(self.grouper, Categorical):
+
+ # must have an ordered categorical
+ if self.sort:
+ if not self.grouper.ordered:
+
+ # technically we cannot group on an unordered Categorical
+ # but this a user convenience to do so; the ordering
+ # is preserved and if its a reduction is doesnt't make any difference
+ pass
+
# fix bug #GH8868 sort=False being ignored in categorical groupby
- if not self.sort:
+ else:
self.grouper = self.grouper.reorder_categories(self.grouper.unique())
self._labels = self.grouper.codes
self._group_index = self.grouper.categories
diff --git a/pandas/core/index.py b/pandas/core/index.py
index 5ba3026a89f7a..195cb21d6564c 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -3628,7 +3628,7 @@ def from_arrays(cls, arrays, sortorder=None, names=None):
name = None if names is None else names[0]
return Index(arrays[0], name=name)
- cats = [Categorical.from_array(arr) for arr in arrays]
+ cats = [Categorical.from_array(arr, ordered=True) for arr in arrays]
levels = [c.categories for c in cats]
labels = [c.codes for c in cats]
if names is None:
@@ -3721,7 +3721,7 @@ def from_product(cls, iterables, sortorder=None, names=None):
from pandas.core.categorical import Categorical
from pandas.tools.util import cartesian_product
- categoricals = [Categorical.from_array(it) for it in iterables]
+ categoricals = [Categorical.from_array(it, ordered=True) for it in iterables]
labels = cartesian_product([c.codes for c in categoricals])
return MultiIndex(levels=[c.categories for c in categoricals],
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 08618d7794b5d..5cb032521d51a 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -367,12 +367,12 @@ def downcast(self, dtypes=None):
return blocks
- def astype(self, dtype, copy=False, raise_on_error=True, values=None):
+ def astype(self, dtype, copy=False, raise_on_error=True, values=None, **kwargs):
return self._astype(dtype, copy=copy, raise_on_error=raise_on_error,
- values=values)
+ values=values, **kwargs)
def _astype(self, dtype, copy=False, raise_on_error=True, values=None,
- klass=None):
+ klass=None, **kwargs):
"""
Coerce to the new type (if copy=True, return a new copy)
raise on an except if raise == True
@@ -381,7 +381,7 @@ def _astype(self, dtype, copy=False, raise_on_error=True, values=None,
# may need to convert to categorical
# this is only called for non-categoricals
if self.is_categorical_astype(dtype):
- return make_block(Categorical(self.values),
+ return make_block(Categorical(self.values, **kwargs),
ndim=self.ndim,
placement=self.mgr_locs)
@@ -1229,8 +1229,8 @@ def to_native_types(self, slicer=None, na_rep='', float_format=None, decimal='.'
values = np.array(values, dtype=object)
mask = isnull(values)
values[mask] = na_rep
-
-
+
+
if float_format and decimal != '.':
formatter = lambda v : (float_format % v).replace('.',decimal,1)
elif decimal != '.':
@@ -1239,12 +1239,12 @@ def to_native_types(self, slicer=None, na_rep='', float_format=None, decimal='.'
formatter = lambda v : float_format % v
else:
formatter = None
-
+
if formatter:
imask = (~mask).ravel()
values.flat[imask] = np.array(
[formatter(val) for val in values.ravel()[imask]])
-
+
return values.tolist()
def should_store(self, value):
diff --git a/pandas/core/panel.py b/pandas/core/panel.py
index f77ed59df8ac1..b3fc9aec00271 100644
--- a/pandas/core/panel.py
+++ b/pandas/core/panel.py
@@ -95,8 +95,8 @@ def panel_index(time, panels, names=['time', 'panel']):
(1962, 'C')], dtype=object)
"""
time, panels = _ensure_like_indices(time, panels)
- time_factor = Categorical.from_array(time)
- panel_factor = Categorical.from_array(panels)
+ time_factor = Categorical.from_array(time, ordered=True)
+ panel_factor = Categorical.from_array(panels, ordered=True)
labels = [time_factor.codes, panel_factor.codes]
levels = [time_factor.categories, panel_factor.categories]
diff --git a/pandas/core/reshape.py b/pandas/core/reshape.py
index 1fe23551e886c..291a73778197a 100644
--- a/pandas/core/reshape.py
+++ b/pandas/core/reshape.py
@@ -157,7 +157,8 @@ def get_result(self):
# may need to coerce categoricals here
if self.is_categorical is not None:
values = [ Categorical.from_array(values[:,i],
- categories=self.is_categorical.categories)
+ categories=self.is_categorical.categories,
+ ordered=True)
for i in range(values.shape[-1]) ]
return DataFrame(values, index=index, columns=columns)
@@ -1049,7 +1050,7 @@ def check_len(item, name):
def _get_dummies_1d(data, prefix, prefix_sep='_', dummy_na=False):
# Series avoids inconsistent NaN handling
- cat = Categorical.from_array(Series(data))
+ cat = Categorical.from_array(Series(data), ordered=True)
levels = cat.categories
# if all NaN
@@ -1117,7 +1118,7 @@ def make_axis_dummies(frame, axis='minor', transform=None):
labels = frame.index.labels[num]
if transform is not None:
mapped_items = items.map(transform)
- cat = Categorical.from_array(mapped_items.take(labels))
+ cat = Categorical.from_array(mapped_items.take(labels), ordered=True)
labels = cat.codes
items = cat.categories
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 05510f655f7be..e784934ea28b2 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -3637,7 +3637,7 @@ def read(self, where=None, columns=None, **kwargs):
if not self.read_axes(where=where, **kwargs):
return None
- factors = [Categorical.from_array(a.values) for a in self.index_axes]
+ factors = [Categorical.from_array(a.values, ordered=True) for a in self.index_axes]
levels = [f.categories for f in factors]
N = [len(f.categories) for f in factors]
labels = [f.codes for f in factors]
diff --git a/pandas/tests/data/categorical_0_15_2.pickle b/pandas/tests/data/categorical_0_15_2.pickle
new file mode 100644
index 0000000000000..25cd862976cab
Binary files /dev/null and b/pandas/tests/data/categorical_0_15_2.pickle differ
diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py
index d27fb39ec65e9..a7f241168ea73 100644
--- a/pandas/tests/test_categorical.py
+++ b/pandas/tests/test_categorical.py
@@ -22,7 +22,7 @@ class TestCategorical(tm.TestCase):
def setUp(self):
self.factor = Categorical.from_array(['a', 'b', 'b', 'a',
- 'a', 'c', 'c', 'c'])
+ 'a', 'c', 'c', 'c'], ordered=True)
def test_getitem(self):
self.assertEqual(self.factor[0], 'a')
@@ -60,7 +60,7 @@ def test_setitem(self):
indexer[-1] = True
c[indexer] = 'c'
expected = Categorical.from_array(['c', 'b', 'b', 'a',
- 'a', 'c', 'c', 'c'])
+ 'a', 'c', 'c', 'c'], ordered=True)
self.assert_categorical_equal(c, expected)
@@ -82,9 +82,12 @@ def test_constructor_unsortable(self):
# it works!
arr = np.array([1, 2, 3, datetime.now()], dtype='O')
- factor = Categorical.from_array(arr)
+ factor = Categorical.from_array(arr, ordered=False)
self.assertFalse(factor.ordered)
+ # this however will raise as cannot be sorted
+ self.assertRaises(TypeError, lambda : Categorical.from_array(arr, ordered=True))
+
def test_constructor(self):
exp_arr = np.array(["a", "b", "c", "a", "b", "c"])
@@ -268,6 +271,7 @@ def f():
pd.Categorical.from_codes(codes, categories=["train", "test"])
def test_comparisons(self):
+
result = self.factor[self.factor == 'a']
expected = self.factor[np.asarray(self.factor) == 'a']
self.assertTrue(result.equals(expected))
@@ -304,10 +308,10 @@ def test_comparisons(self):
self.assert_numpy_array_equal(result, expected)
# comparisons with categoricals
- cat_rev = pd.Categorical(["a","b","c"], categories=["c","b","a"])
- cat_rev_base = pd.Categorical(["b","b","b"], categories=["c","b","a"])
- cat = pd.Categorical(["a","b","c"])
- cat_base = pd.Categorical(["b","b","b"], categories=cat.categories)
+ cat_rev = pd.Categorical(["a","b","c"], categories=["c","b","a"], ordered=True)
+ cat_rev_base = pd.Categorical(["b","b","b"], categories=["c","b","a"], ordered=True)
+ cat = pd.Categorical(["a","b","c"], ordered=True)
+ cat_base = pd.Categorical(["b","b","b"], categories=cat.categories, ordered=True)
# comparisons need to take categories ordering into account
res_rev = cat_rev > cat_rev_base
@@ -333,8 +337,7 @@ def f():
self.assertRaises(TypeError, f)
# Only categories with same ordering information can be compared
- cat_unorderd = cat.copy()
- cat_unorderd.ordered = False
+ cat_unorderd = cat.set_ordered(False)
self.assertFalse((cat > cat).any())
def f():
cat > cat_unorderd
@@ -373,7 +376,7 @@ def test_na_flags_int_categories(self):
def test_categories_none(self):
factor = Categorical(['a', 'b', 'b', 'a',
- 'a', 'c', 'c', 'c'])
+ 'a', 'c', 'c', 'c'], ordered=True)
self.assertTrue(factor.equals(self.factor))
def test_describe(self):
@@ -454,16 +457,19 @@ def test_big_print(self):
def test_empty_print(self):
factor = Categorical([], ["a","b","c"], name="cat")
- expected = ("[], Name: cat, Categories (3, object): [a < b < c]")
+ expected = ("[], Name: cat, Categories (3, object): [a, b, c]")
# hack because array_repr changed in numpy > 1.6.x
actual = repr(factor)
-
self.assertEqual(actual, expected)
factor = Categorical([], ["a","b","c"])
- expected = ("[], Categories (3, object): [a < b < c]")
+ expected = ("[], Categories (3, object): [a, b, c]")
actual = repr(factor)
+ self.assertEqual(expected, actual)
+ factor = Categorical([], ["a","b","c"], ordered=True)
+ expected = ("[], Categories (3, object): [a < b < c]")
+ actual = repr(factor)
self.assertEqual(expected, actual)
factor = Categorical([], [])
@@ -483,7 +489,7 @@ def test_periodindex(self):
idx2 = PeriodIndex(['2014-03', '2014-03', '2014-02', '2014-01',
'2014-03', '2014-01'], freq='M')
- cat2 = Categorical.from_array(idx2)
+ cat2 = Categorical.from_array(idx2, ordered=True)
str(cat2)
exp_arr = np.array([2, 2, 1, 0, 2, 0],dtype='int64')
exp_idx2 = PeriodIndex(['2014-01', '2014-02', '2014-03'], freq='M')
@@ -492,7 +498,7 @@ def test_periodindex(self):
idx3 = PeriodIndex(['2013-12', '2013-11', '2013-10', '2013-09',
'2013-08', '2013-07', '2013-05'], freq='M')
- cat3 = Categorical.from_array(idx3)
+ cat3 = Categorical.from_array(idx3, ordered=True)
exp_arr = np.array([6, 5, 4, 3, 2, 1, 0],dtype='int64')
exp_idx = PeriodIndex(['2013-05', '2013-07', '2013-08', '2013-09',
'2013-10', '2013-11', '2013-12'], freq='M')
@@ -514,6 +520,60 @@ def f():
s.categories = [1,2]
self.assertRaises(ValueError, f)
+ def test_construction_with_ordered(self):
+ # GH 9347, 9190
+ cat = Categorical([0,1,2])
+ self.assertFalse(cat.ordered)
+ cat = Categorical([0,1,2],ordered=False)
+ self.assertFalse(cat.ordered)
+ cat = Categorical([0,1,2],ordered=True)
+ self.assertTrue(cat.ordered)
+
+ def test_ordered_api(self):
+ # GH 9347
+ cat1 = pd.Categorical(["a","c","b"], ordered=False)
+ self.assertTrue(cat1.categories.equals(Index(['a','b','c'])))
+ self.assertFalse(cat1.ordered)
+
+ cat2 = pd.Categorical(["a","c","b"], categories=['b','c','a'], ordered=False)
+ self.assertTrue(cat2.categories.equals(Index(['b','c','a'])))
+ self.assertFalse(cat2.ordered)
+
+ cat3 = pd.Categorical(["a","c","b"], ordered=True)
+ self.assertTrue(cat3.categories.equals(Index(['a','b','c'])))
+ self.assertTrue(cat3.ordered)
+
+ cat4 = pd.Categorical(["a","c","b"], categories=['b','c','a'], ordered=True)
+ self.assertTrue(cat4.categories.equals(Index(['b','c','a'])))
+ self.assertTrue(cat4.ordered)
+
+ def test_set_ordered(self):
+
+ cat = Categorical(["a","b","c","a"], ordered=True)
+ cat2 = cat.as_unordered()
+ self.assertFalse(cat2.ordered)
+ cat2 = cat.as_ordered()
+ self.assertTrue(cat2.ordered)
+ cat2.as_unordered(inplace=True)
+ self.assertFalse(cat2.ordered)
+ cat2.as_ordered(inplace=True)
+ self.assertTrue(cat2.ordered)
+
+ self.assertTrue(cat2.set_ordered(True).ordered)
+ self.assertFalse(cat2.set_ordered(False).ordered)
+ cat2.set_ordered(True, inplace=True)
+ self.assertTrue(cat2.ordered)
+ cat2.set_ordered(False, inplace=True)
+ self.assertFalse(cat2.ordered)
+
+ # deperecated in v0.16.0
+ with tm.assert_produces_warning(FutureWarning):
+ cat.ordered = False
+ self.assertFalse(cat.ordered)
+ with tm.assert_produces_warning(FutureWarning):
+ cat.ordered = True
+ self.assertTrue(cat.ordered)
+
def test_set_categories(self):
cat = Categorical(["a","b","c","a"], ordered=True)
exp_categories = np.array(["c","b","a"])
@@ -549,7 +609,7 @@ def test_set_categories(self):
self.assert_numpy_array_equal(cat.categories, exp_categories)
# internals...
- c = Categorical([1,2,3,4,1], categories=[1,2,3,4])
+ c = Categorical([1,2,3,4,1], categories=[1,2,3,4], ordered=True)
self.assert_numpy_array_equal(c._codes, np.array([0,1,2,3,0]))
self.assert_numpy_array_equal(c.categories , np.array([1,2,3,4] ))
self.assert_numpy_array_equal(c.get_values(), np.array([1,2,3,4,1] ))
@@ -560,6 +620,16 @@ def test_set_categories(self):
self.assertTrue(c.min(), 4)
self.assertTrue(c.max(), 1)
+ # set_categories should set the ordering if specified
+ c2 = c.set_categories([4,3,2,1],ordered=False)
+ self.assertFalse(c2.ordered)
+ self.assert_numpy_array_equal(c.get_values(), c2.get_values())
+
+ # set_categories should pass thru the ordering
+ c2 = c.set_ordered(False).set_categories([4,3,2,1])
+ self.assertFalse(c2.ordered)
+ self.assert_numpy_array_equal(c.get_values(), c2.get_values())
+
def test_rename_categories(self):
cat = pd.Categorical(["a","b","c","a"])
@@ -848,9 +918,11 @@ def test_mode(self):
def test_sort(self):
- # unordered cats are not sortable
+ # unordered cats are sortable
cat = Categorical(["a","b","b","a"], ordered=False)
- self.assertRaises(TypeError, lambda : cat.sort())
+ cat.order()
+ cat.sort()
+
cat = Categorical(["a","c","b","d"], ordered=True)
# order
@@ -928,8 +1000,8 @@ def test_searchsorted(self):
# https://github.com/pydata/pandas/issues/8420
s1 = pd.Series(['apple', 'bread', 'bread', 'cheese', 'milk' ])
s2 = pd.Series(['apple', 'bread', 'bread', 'cheese', 'milk', 'donuts' ])
- c1 = pd.Categorical(s1)
- c2 = pd.Categorical(s2)
+ c1 = pd.Categorical(s1, ordered=True)
+ c2 = pd.Categorical(s2, ordered=True)
# Single item array
res = c1.searchsorted(['bread'])
@@ -990,13 +1062,13 @@ def test_deprecated_levels(self):
self.assertFalse(LooseVersion(pd.__version__) >= '0.18')
def test_datetime_categorical_comparison(self):
- dt_cat = pd.Categorical(pd.date_range('2014-01-01', periods=3))
+ dt_cat = pd.Categorical(pd.date_range('2014-01-01', periods=3), ordered=True)
self.assert_numpy_array_equal(dt_cat > dt_cat[0], [False, True, True])
self.assert_numpy_array_equal(dt_cat[0] < dt_cat, [False, True, True])
def test_reflected_comparison_with_scalars(self):
# GH8658
- cat = pd.Categorical([1, 2, 3])
+ cat = pd.Categorical([1, 2, 3], ordered=True)
self.assert_numpy_array_equal(cat > cat[0], [False, True, True])
self.assert_numpy_array_equal(cat[0] < cat, [False, True, True])
@@ -1153,6 +1225,17 @@ def test_creation_astype(self):
df["cats"] = df["cats"].astype("category")
tm.assert_frame_equal(exp_df, df)
+ # with keywords
+ l = ["a","b","c","a"]
+ s = pd.Series(l)
+ exp = pd.Series(Categorical(l, ordered=True))
+ res = s.astype('category', ordered=True)
+ tm.assert_series_equal(res, exp)
+
+ exp = pd.Series(Categorical(l, categories=list('abcdef'), ordered=True))
+ res = s.astype('category', categories=list('abcdef'), ordered=True)
+ tm.assert_series_equal(res, exp)
+
def test_construction_series(self):
l = [1,2,3,1]
@@ -1318,7 +1401,7 @@ def test_nan_handling(self):
def test_cat_accessor(self):
s = Series(Categorical(["a","b",np.nan,"a"]))
self.assert_numpy_array_equal(s.cat.categories, np.array(["a","b"]))
- self.assertEqual(s.cat.ordered, True)
+ self.assertEqual(s.cat.ordered, False)
exp = Categorical(["a","b",np.nan,"a"], categories=["b","a"])
s.cat.set_categories(["b", "a"], inplace=True)
self.assertTrue(s.values.equals(exp))
@@ -1375,8 +1458,10 @@ def test_series_delegations(self):
tm.assert_series_equal(s.cat.codes, exp_codes)
self.assertEqual(s.cat.ordered, True)
- s.cat.ordered = False
+ s = s.cat.as_unordered()
self.assertEqual(s.cat.ordered, False)
+ s.cat.as_ordered(inplace=True)
+ self.assertEqual(s.cat.ordered, True)
# reorder
s = Series(Categorical(["a","b","c","a"], ordered=True))
@@ -1466,11 +1551,11 @@ def test_describe(self):
def test_repr(self):
a = pd.Series(pd.Categorical([1,2,3,4], name="a"))
exp = u("0 1\n1 2\n2 3\n3 4\n" +
- "Name: a, dtype: category\nCategories (4, int64): [1 < 2 < 3 < 4]")
+ "Name: a, dtype: category\nCategories (4, int64): [1, 2, 3, 4]")
self.assertEqual(exp, a.__unicode__())
- a = pd.Series(pd.Categorical(["a","b"] *25, name="a"))
+ a = pd.Series(pd.Categorical(["a","b"] *25, name="a", ordered=True))
exp = u("".join(["%s a\n%s b\n"%(i,i+1) for i in range(0,10,2)]) + "...\n" +
"".join(["%s a\n%s b\n"%(i,i+1) for i in range(40,50,2)]) +
"Name: a, Length: 50, dtype: category\n" +
@@ -1478,7 +1563,7 @@ def test_repr(self):
self.assertEqual(exp,a._tidy_repr())
levs = list("abcdefghijklmnopqrstuvwxyz")
- a = pd.Series(pd.Categorical(["a","b"], name="a", categories=levs))
+ a = pd.Series(pd.Categorical(["a","b"], name="a", categories=levs, ordered=True))
exp = u("0 a\n1 b\n" +
"Name: a, dtype: category\n"
"Categories (26, object): [a < b < c < d ... w < x < y < z]")
@@ -1604,15 +1689,15 @@ def test_value_counts_with_nan(self):
def test_groupby(self):
- cats = Categorical(["a", "a", "a", "b", "b", "b", "c", "c", "c"], categories=["a","b","c","d"])
+ cats = Categorical(["a", "a", "a", "b", "b", "b", "c", "c", "c"], categories=["a","b","c","d"], ordered=True)
data = DataFrame({"a":[1,1,1,2,2,2,3,4,5], "b":cats})
expected = DataFrame({ 'a' : Series([1,2,4,np.nan],index=Index(['a','b','c','d'],name='b')) })
result = data.groupby("b").mean()
tm.assert_frame_equal(result, expected)
- raw_cat1 = Categorical(["a","a","b","b"], categories=["a","b","z"])
- raw_cat2 = Categorical(["c","d","c","d"], categories=["c","d","y"])
+ raw_cat1 = Categorical(["a","a","b","b"], categories=["a","b","z"], ordered=True)
+ raw_cat2 = Categorical(["c","d","c","d"], categories=["c","d","y"], ordered=True)
df = DataFrame({"A":raw_cat1,"B":raw_cat2, "values":[1,2,3,4]})
# single grouper
@@ -1666,8 +1751,8 @@ def f(x):
def test_pivot_table(self):
- raw_cat1 = Categorical(["a","a","b","b"], categories=["a","b","z"])
- raw_cat2 = Categorical(["c","d","c","d"], categories=["c","d","y"])
+ raw_cat1 = Categorical(["a","a","b","b"], categories=["a","b","z"], ordered=True)
+ raw_cat2 = Categorical(["c","d","c","d"], categories=["c","d","y"], ordered=True)
df = DataFrame({"A":raw_cat1,"B":raw_cat2, "values":[1,2,3,4]})
result = pd.pivot_table(df, values='values', index=['A', 'B'])
@@ -1684,9 +1769,12 @@ def test_count(self):
def test_sort(self):
- # unordered cats are not sortable
cat = Series(Categorical(["a","b","b","a"], ordered=False))
- self.assertRaises(TypeError, lambda : cat.sort())
+
+ # sort in the categories order
+ expected = Series(Categorical(["a","a","b","b"], ordered=False),index=[0,3,1,2])
+ result = cat.order()
+ tm.assert_series_equal(result, expected)
cat = Series(Categorical(["a","c","b","d"], ordered=True))
@@ -1704,7 +1792,7 @@ def test_sort(self):
self.assert_numpy_array_equal(res.__array__(), exp)
raw_cat1 = Categorical(["a","b","c","d"], categories=["a","b","c","d"], ordered=False)
- raw_cat2 = Categorical(["a","b","c","d"], categories=["d","c","b","a"])
+ raw_cat2 = Categorical(["a","b","c","d"], categories=["d","c","b","a"], ordered=True)
s = ["a","b","c","d"]
df = DataFrame({"unsort":raw_cat1,"sort":raw_cat2, "string":s, "values":[1,2,3,4]})
@@ -1720,14 +1808,13 @@ def test_sort(self):
self.assertEqual(res["sort"].dtype, "category")
self.assertEqual(res["unsort"].dtype, "category")
- def f():
- df.sort(columns=["unsort"], ascending=False)
- self.assertRaises(TypeError, f)
+ # unordered cat, but we allow this
+ df.sort(columns=["unsort"], ascending=False)
# multi-columns sort
# GH 7848
df = DataFrame({"id":[6,5,4,3,2,1], "raw_grade":['a', 'b', 'b', 'a', 'a', 'e']})
- df["grade"] = pd.Categorical(df["raw_grade"])
+ df["grade"] = pd.Categorical(df["raw_grade"], ordered=True)
df['grade'] = df['grade'].cat.set_categories(['b', 'e', 'a'])
# sorts 'grade' according to the order of the categories
@@ -2279,10 +2366,10 @@ def test_comparisons(self):
tests_data = [(list("abc"), list("cba"), list("bbb")),
([1,2,3], [3,2,1], [2,2,2])]
for data , reverse, base in tests_data:
- cat_rev = pd.Series(pd.Categorical(data, categories=reverse))
- cat_rev_base = pd.Series(pd.Categorical(base, categories=reverse))
- cat = pd.Series(pd.Categorical(data))
- cat_base = pd.Series(pd.Categorical(base, categories=cat.cat.categories))
+ cat_rev = pd.Series(pd.Categorical(data, categories=reverse, ordered=True))
+ cat_rev_base = pd.Series(pd.Categorical(base, categories=reverse, ordered=True))
+ cat = pd.Series(pd.Categorical(data, ordered=True))
+ cat_base = pd.Series(pd.Categorical(base, categories=cat.cat.categories, ordered=True))
s = Series(base)
a = np.array(base)
@@ -2616,7 +2703,8 @@ def test_cat_tab_completition(self):
# test the tab completion display
ok_for_cat = ['categories','codes','ordered','set_categories',
'add_categories', 'remove_categories', 'rename_categories',
- 'reorder_categories', 'remove_unused_categories']
+ 'reorder_categories', 'remove_unused_categories',
+ 'as_ordered', 'as_unordered']
def get_dir(s):
results = [ r for r in s.cat.__dir__() if not r.startswith('_') ]
return list(sorted(set(results)))
@@ -2651,6 +2739,23 @@ def test_pickle_v0_14_1(self):
#
self.assert_categorical_equal(cat, pd.read_pickle(pickle_path))
+ def test_pickle_v0_15_2(self):
+ # ordered -> _ordered
+ # GH 9347
+
+ cat = pd.Categorical(values=['a', 'b', 'c'],
+ categories=['a', 'b', 'c', 'd'],
+ name='foobar', ordered=False)
+ pickle_path = os.path.join(tm.get_data_path(),
+ 'categorical_0_15_2.pickle')
+ # This code was executed once on v0.15.2 to generate the pickle:
+ #
+ # cat = Categorical(labels=np.arange(3), levels=['a', 'b', 'c', 'd'],
+ # name='foobar')
+ # with open(pickle_path, 'wb') as f: pickle.dump(cat, f)
+ #
+ self.assert_categorical_equal(cat, pd.read_pickle(pickle_path))
+
if __name__ == '__main__':
import nose
diff --git a/pandas/tests/test_groupby.py b/pandas/tests/test_groupby.py
index 9498c7e1207c3..17ae8c66e26dd 100644
--- a/pandas/tests/test_groupby.py
+++ b/pandas/tests/test_groupby.py
@@ -3274,7 +3274,7 @@ def test_groupby_sort_categorical(self):
['(2.5, 5]', 4, 50],
['(0, 2.5]', 1, 60],
['(5, 7.5]', 7, 70]], columns=['range', 'foo', 'bar'])
- df['range'] = Categorical(df['range'])
+ df['range'] = Categorical(df['range'],ordered=True)
index = Index(['(0, 2.5]', '(2.5, 5]', '(5, 7.5]', '(7.5, 10]'], dtype='object')
index.name = 'range'
result_sort = DataFrame([[1, 60], [5, 30], [6, 40], [10, 10]], columns=['foo', 'bar'])
@@ -3288,6 +3288,22 @@ def test_groupby_sort_categorical(self):
assert_frame_equal(result_sort, df.groupby(col, sort=True).first())
assert_frame_equal(result_nosort, df.groupby(col, sort=False).first())
+ df['range'] = Categorical(df['range'],ordered=False)
+ index = Index(['(0, 2.5]', '(2.5, 5]', '(5, 7.5]', '(7.5, 10]'], dtype='object')
+ index.name = 'range'
+ result_sort = DataFrame([[1, 60], [5, 30], [6, 40], [10, 10]], columns=['foo', 'bar'])
+ result_sort.index = index
+ index = Index(['(7.5, 10]', '(2.5, 5]', '(5, 7.5]', '(0, 2.5]'], dtype='object')
+ index.name = 'range'
+ result_nosort = DataFrame([[10, 10], [5, 30], [6, 40], [1, 60]], index=index, columns=['foo', 'bar'])
+ result_nosort.index = index
+
+ col = 'range'
+
+ #### this is an unordered categorical, but we allow this ####
+ assert_frame_equal(result_sort, df.groupby(col, sort=True).first())
+ assert_frame_equal(result_nosort, df.groupby(col, sort=False).first())
+
def test_groupby_sort_multiindex_series(self):
# series multiindex groupby sort argument was not being passed through _compress_group_index
@@ -3310,7 +3326,7 @@ def test_groupby_categorical(self):
levels = ['foo', 'bar', 'baz', 'qux']
codes = np.random.randint(0, 4, size=100)
- cats = Categorical.from_codes(codes, levels, name='myfactor')
+ cats = Categorical.from_codes(codes, levels, name='myfactor', ordered=True)
data = DataFrame(np.random.randn(100, 4))
@@ -3338,7 +3354,7 @@ def test_groupby_datetime_categorical(self):
levels = pd.date_range('2014-01-01', periods=4)
codes = np.random.randint(0, 4, size=100)
- cats = Categorical.from_codes(codes, levels, name='myfactor')
+ cats = Categorical.from_codes(codes, levels, name='myfactor', ordered=True)
data = DataFrame(np.random.randn(100, 4))
@@ -3485,21 +3501,21 @@ def test_groupby_categorical_no_compress(self):
data = Series(np.random.randn(9))
codes = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2])
- cats = Categorical.from_codes(codes, [0, 1, 2])
+ cats = Categorical.from_codes(codes, [0, 1, 2], ordered=True)
result = data.groupby(cats).mean()
exp = data.groupby(codes).mean()
assert_series_equal(result, exp)
codes = np.array([0, 0, 0, 1, 1, 1, 3, 3, 3])
- cats = Categorical.from_codes(codes, [0, 1, 2, 3])
+ cats = Categorical.from_codes(codes, [0, 1, 2, 3], ordered=True)
result = data.groupby(cats).mean()
exp = data.groupby(codes).mean().reindex(cats.categories)
assert_series_equal(result, exp)
cats = Categorical(["a", "a", "a", "b", "b", "b", "c", "c", "c"],
- categories=["a","b","c","d"])
+ categories=["a","b","c","d"], ordered=True)
data = DataFrame({"a":[1,1,1,2,2,2,3,4,5], "b":cats})
result = data.groupby("b").mean()
@@ -4991,7 +5007,7 @@ def test_transform_doesnt_clobber_ints(self):
def test_groupby_categorical_two_columns(self):
# https://github.com/pydata/pandas/issues/8138
- d = {'cat': pd.Categorical(["a","b","a","b"], categories=["a", "b", "c"]),
+ d = {'cat': pd.Categorical(["a","b","a","b"], categories=["a", "b", "c"], ordered=True),
'ints': [1, 1, 2, 2],'val': [10, 20, 30, 40]}
test = pd.DataFrame(d)
diff --git a/pandas/tools/merge.py b/pandas/tools/merge.py
index 454b0f79310e4..c7c578232cd0f 100644
--- a/pandas/tools/merge.py
+++ b/pandas/tools/merge.py
@@ -1037,7 +1037,7 @@ def _make_concat_multiindex(indexes, keys, levels=None, names=None):
names = [None] * len(zipped)
if levels is None:
- levels = [Categorical.from_array(zp).categories for zp in zipped]
+ levels = [Categorical.from_array(zp, ordered=True).categories for zp in zipped]
else:
levels = [_ensure_index(x) for x in levels]
else:
@@ -1075,7 +1075,7 @@ def _make_concat_multiindex(indexes, keys, levels=None, names=None):
levels.extend(concat_index.levels)
label_list.extend(concat_index.labels)
else:
- factor = Categorical.from_array(concat_index)
+ factor = Categorical.from_array(concat_index, ordered=True)
levels.append(factor.categories)
label_list.append(factor.codes)
| alternate to #9611
closes #9347
closes #9190
closes #9148
This implementes the alternate, and IMHO a nice compromise.
Groupby's will succeed whether ordered or not
ordering ops (sort/argsort/min/max) will still raise.
one though is that we could detect a non-reduction where the ordering matters (maybe we do this in another PR), and show a warning, e.g. imagine `df.groupby('A').head(2)` is technically 'wrong', while `df.groupby('A').sum()` would have no warning.
```
In [1]: df = DataFrame({ 'A' : Series(list('aabc')).astype('category'), 'B' : np.arange(4) })
In [2]: df.groupby('A').sum()
Out[2]:
B
A
a 1
b 2
c 3
In [3]: df['A'].order()
TypeError: Categorical is not ordered for operation argsort
you can use .as_ordered() to change the Categorical to an ordered one
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/9622 | 2015-03-09T22:56:46Z | 2015-03-11T12:11:49Z | 2015-03-11T12:11:48Z | 2015-03-11T12:12:05Z |
fix pymysql at 0.6.3 (GH9608) | diff --git a/ci/requirements-3.4.txt b/ci/requirements-3.4.txt
index 33d3b3b4dc459..8a55c0458688e 100644
--- a/ci/requirements-3.4.txt
+++ b/ci/requirements-3.4.txt
@@ -15,5 +15,5 @@ matplotlib
lxml
sqlalchemy
bottleneck
-pymysql
+pymysql==0.6.3
psycopg2
| xref #9608
fix version to bypass failures for now
| https://api.github.com/repos/pandas-dev/pandas/pulls/9621 | 2015-03-09T20:55:16Z | 2015-03-09T21:39:59Z | 2015-03-09T21:39:59Z | 2015-03-09T21:39:59Z |
DOC: Shrink image asset for assign | diff --git a/doc/source/_static/whatsnew_assign.png b/doc/source/_static/whatsnew_assign.png
index 0e39e161dc606..84546cadf0276 100644
Binary files a/doc/source/_static/whatsnew_assign.png and b/doc/source/_static/whatsnew_assign.png differ
| Let's try this again. The sphinx directive didn't seem to work. I just shrunk the static asset.
I'm not at my regular computer and I haven't been able to get the docs to build on this one, so I'm exactly sure how it will look in the page :)
| https://api.github.com/repos/pandas-dev/pandas/pulls/9619 | 2015-03-09T15:20:03Z | 2015-03-09T18:42:16Z | 2015-03-09T18:42:16Z | 2015-08-18T12:45:06Z |
BUG/API: Accessors like .cat raise AttributeError when invalid | diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt
index bc51519898359..9467764ec2a74 100644
--- a/doc/source/whatsnew/v0.16.0.txt
+++ b/doc/source/whatsnew/v0.16.0.txt
@@ -245,6 +245,7 @@ Backwards incompatible API changes
- Bar and horizontal bar plots no longer add a dashed line along the info axis. The prior style can be achieved with matplotlib's ``axhline`` or ``axvline`` methods (:issue:`9088`).
+- ``Series`` accessors ``.dt``, ``.cat`` and ``.str`` now raise ``AttributeError`` instead of ``TypeError`` if the series does not contain the appropriate type of data (:issue:`9617`). This follows Python's built-in exception hierarchy more closely and ensures that tests like ``hasattr(s, 'cat')`` are consistent on both Python 2 and 3.
- ``Series`` now supports bitwise operation for integral types (:issue:`9016`)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 67a9ab67c0a98..c29e97b423fe1 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -78,8 +78,9 @@ class NDFrame(PandasObject):
copy : boolean, default False
"""
_internal_names = ['_data', '_cacher', '_item_cache', '_cache',
- 'is_copy', 'str', '_subtyp', '_index', '_default_kind',
- '_default_fill_value','__array_struct__','__array_interface__']
+ 'is_copy', 'dt', 'cat', 'str', '_subtyp', '_index',
+ '_default_kind', '_default_fill_value',
+ '__array_struct__','__array_interface__']
_internal_names_set = set(_internal_names)
_metadata = []
is_copy = None
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 4640776f3b88e..a83a6291e6c81 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2521,8 +2521,9 @@ def _make_str_accessor(self):
# this really should exclude all series with any non-string values,
# but that isn't practical for performance reasons until we have a
# str dtype (GH 9343)
- raise TypeError("Can only use .str accessor with string values, "
- "which use np.object_ dtype in pandas")
+ raise AttributeError("Can only use .str accessor with string "
+ "values, which use np.object_ dtype in "
+ "pandas")
return StringMethods(self)
str = base.AccessorProperty(StringMethods, _make_str_accessor)
@@ -2533,8 +2534,9 @@ def _make_str_accessor(self):
def _make_dt_accessor(self):
try:
return maybe_to_datetimelike(self)
- except (Exception):
- raise TypeError("Can only use .dt accessor with datetimelike values")
+ except Exception:
+ raise AttributeError("Can only use .dt accessor with datetimelike "
+ "values")
dt = base.AccessorProperty(CombinedDatetimelikeProperties, _make_dt_accessor)
@@ -2543,7 +2545,8 @@ def _make_dt_accessor(self):
def _make_cat_accessor(self):
if not com.is_categorical_dtype(self.dtype):
- raise TypeError("Can only use .cat accessor with a 'category' dtype")
+ raise AttributeError("Can only use .cat accessor with a "
+ "'category' dtype")
return CategoricalAccessor(self.values, self.index)
cat = base.AccessorProperty(CategoricalAccessor, _make_cat_accessor)
diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py
index 63722264c25dc..a77f3984105cc 100644
--- a/pandas/tests/test_categorical.py
+++ b/pandas/tests/test_categorical.py
@@ -2631,8 +2631,11 @@ def test_cat_accessor_api(self):
self.assertIs(Series.cat, CategoricalAccessor)
s = Series(list('aabbcde')).astype('category')
self.assertIsInstance(s.cat, CategoricalAccessor)
- with tm.assertRaisesRegexp(TypeError, "only use .cat accessor"):
- Series([1]).cat
+
+ invalid = Series([1])
+ with tm.assertRaisesRegexp(AttributeError, "only use .cat accessor"):
+ invalid.cat
+ self.assertFalse(hasattr(invalid, 'cat'))
def test_pickle_v0_14_1(self):
cat = pd.Categorical(values=['a', 'b', 'c'],
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index e5d983472256f..7e0dbaa735456 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -104,12 +104,6 @@ def compare(s, name):
else:
tm.assert_series_equal(a,b)
- # invalids
- for s in [Series(np.arange(5)),
- Series(list('abcde')),
- Series(np.random.randn(5))]:
- self.assertRaises(TypeError, lambda : s.dt)
-
# datetimeindex
for s in [Series(date_range('20130101',periods=5)),
Series(date_range('20130101',periods=5,freq='s')),
@@ -240,8 +234,13 @@ def test_dt_accessor_api(self):
s = Series(date_range('2000-01-01', periods=3))
self.assertIsInstance(s.dt, DatetimeProperties)
- with tm.assertRaisesRegexp(TypeError, "only use .dt accessor"):
- Series([1]).dt
+ for s in [Series(np.arange(5)),
+ Series(list('abcde')),
+ Series(np.random.randn(5))]:
+ with tm.assertRaisesRegexp(AttributeError,
+ "only use .dt accessor"):
+ s.dt
+ self.assertFalse(hasattr(s, 'dt'))
def test_binop_maybe_preserve_name(self):
diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py
index 00ef017859e3d..727ef39aa35e7 100644
--- a/pandas/tests/test_strings.py
+++ b/pandas/tests/test_strings.py
@@ -37,8 +37,10 @@ def test_api(self):
self.assertIsInstance(Series(['']).str, strings.StringMethods)
# GH 9184
- with tm.assertRaisesRegexp(TypeError, "only use .str accessor"):
- Series([1]).str
+ invalid = Series([1])
+ with tm.assertRaisesRegexp(AttributeError, "only use .str accessor"):
+ invalid.str
+ self.assertFalse(hasattr(invalid, 'str'))
def test_iter(self):
# GH3638
| `AttributeError` is really the appropriate error to raise for an invalid
attribute. In particular, it is necessary to ensure that tests like
`hasattr(s, 'cat')` work consistently on Python 2 and 3: on Python 2,
`hasattr(s, 'cat')` will return `False` even if a `TypeError` was raised, but
Python 3 more strictly requires `AttributeError`.
This is an unfortunate trap that we should avoid. See this discussion in
Seaborn for a full report:
https://github.com/mwaskom/seaborn/issues/361#issuecomment-77770773
Note that technically, this is an API change, since these accessors (all but
`.str`, I think) raised TypeError in the last release.
This also suggests another possibility for testing for Series with a
Categorical dtype (#8814): just use `hasattr(s, 'cat')` (at least for Python
2 or pandas >=0.16).
CC @mwaskom @jorisvandenbossche @JanSchulz
| https://api.github.com/repos/pandas-dev/pandas/pulls/9617 | 2015-03-09T08:12:31Z | 2015-03-10T22:49:06Z | 2015-03-10T22:49:06Z | 2015-03-11T02:33:15Z |
DEPR: deprecate pandas.sandbox.qtpandas | diff --git a/doc/source/faq.rst b/doc/source/faq.rst
index 6977716e2913f..de88b436198dd 100644
--- a/doc/source/faq.rst
+++ b/doc/source/faq.rst
@@ -290,6 +290,11 @@ details.
Visualizing Data in Qt applications
-----------------------------------
+.. warning::
+
+ The ``qt`` support is **deprecated and will be removed in a future version**.
+ We refer users to the external package `pandas-qt <https://github.com/datalyze-solutions/pandas-qt>`_.
+
There is experimental support for visualizing DataFrames in PyQt4 and PySide
applications. At the moment you can display and edit the values of the cells
in the DataFrame. Qt will take care of displaying just the portion of the
diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt
index 9dfa8e61387b9..c631faf09747f 100644
--- a/doc/source/whatsnew/v0.16.0.txt
+++ b/doc/source/whatsnew/v0.16.0.txt
@@ -384,6 +384,8 @@ Deprecations
The documentation includes some examples how to convert your existing code
using ``rplot`` to seaborn: - :ref:`rplot docs <rplot>`
+- The ``pandas.sandbox.qtpandas`` interface is deprecated and will be removed in a future version.
+ We refer users to the external package `pandas-qt <https://github.com/datalyze-solutions/pandas-qt>`_. (:issue:`9615`)
.. _whatsnew_0160.prior_deprecations:
diff --git a/pandas/sandbox/qtpandas.py b/pandas/sandbox/qtpandas.py
index 3f284990efd40..2655aa5a452c8 100644
--- a/pandas/sandbox/qtpandas.py
+++ b/pandas/sandbox/qtpandas.py
@@ -3,6 +3,14 @@
@author: Jev Kuznetsov
'''
+
+# GH9615
+
+import warnings
+warnings.warn("The pandas.sandbox.qtpandas module is deprecated and will be "
+ "removed in a future version. We refer users to the external package "
+ "here: https://github.com/datalyze-solutions/pandas-qt")
+
try:
from PyQt4.QtCore import QAbstractTableModel, Qt, QVariant, QModelIndex
from PyQt4.QtGui import (
| not supported module/interface.
xref #1986, #8788
| https://api.github.com/repos/pandas-dev/pandas/pulls/9615 | 2015-03-08T16:18:08Z | 2015-03-08T16:27:28Z | 2015-03-08T16:27:28Z | 2015-03-08T16:27:28Z |
DEPR: deprecate pandas.rpy (GH9602) | diff --git a/doc/source/r_interface.rst b/doc/source/r_interface.rst
index 98fc4edfd5816..826d9e980538e 100644
--- a/doc/source/r_interface.rst
+++ b/doc/source/r_interface.rst
@@ -13,11 +13,9 @@
rpy2 / R interface
******************
-.. note::
-
- This is all highly experimental. I would like to get more people involved
- with building a nice RPy2 interface for pandas
+.. warning::
+ In v0.16.0, the ``pandas.rpy`` interface has been **deprecated and will be removed in a future version**. Similar functionaility can be accessed thru the `rpy2 <http://rpy.sourceforge.net/>`_ project.
If your computer has R and rpy2 (> 2.2) installed (which will be left to the
reader), you will be able to leverage the below functionality. On Windows,
diff --git a/doc/source/whatsnew/v0.13.0.txt b/doc/source/whatsnew/v0.13.0.txt
index 78239eef1b98f..2e10ae4ea668d 100644
--- a/doc/source/whatsnew/v0.13.0.txt
+++ b/doc/source/whatsnew/v0.13.0.txt
@@ -617,6 +617,7 @@ Enhancements
.. code-block:: python
+ # note that pandas.rpy was deprecated in v0.16.0
import pandas.rpy.common as com
com.load_data('Titanic')
diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt
index c631faf09747f..2d85584168f48 100644
--- a/doc/source/whatsnew/v0.16.0.txt
+++ b/doc/source/whatsnew/v0.16.0.txt
@@ -387,6 +387,10 @@ Deprecations
- The ``pandas.sandbox.qtpandas`` interface is deprecated and will be removed in a future version.
We refer users to the external package `pandas-qt <https://github.com/datalyze-solutions/pandas-qt>`_. (:issue:`9615`)
+- The ``pandas.rpy`` interface is deprecated and will be removed in a future version.
+ Similar functionaility can be accessed thru the `rpy2 <http://rpy.sourceforge.net/>`_ project (:issue:`9602`)
+
+
.. _whatsnew_0160.prior_deprecations:
Removal of prior version deprecations/changes
diff --git a/pandas/rpy/__init__.py b/pandas/rpy/__init__.py
index d5cf8a420b727..899b684ecbff9 100644
--- a/pandas/rpy/__init__.py
+++ b/pandas/rpy/__init__.py
@@ -1,3 +1,12 @@
+
+# GH9602
+# deprecate rpy to instead directly use rpy2
+
+import warnings
+warnings.warn("The pandas.rpy module is deprecated and will be "
+ "removed in a future version. We refer to external packages "
+ "like rpy2, found here: http://rpy.sourceforge.net", FutureWarning)
+
try:
from .common import importr, r, load_data
except ImportError:
diff --git a/pandas/stats/tests/test_var.py b/pandas/stats/tests/test_var.py
index ab5709d013fa9..c6eca4041a61b 100644
--- a/pandas/stats/tests/test_var.py
+++ b/pandas/stats/tests/test_var.py
@@ -21,16 +21,6 @@
reload(_pvar)
from pandas.stats.var import VAR
-try:
- import rpy2.robjects as robj
- from rpy2.robjects import r
- from rpy2.robjects.packages import importr
- import pandas.rpy.common as rpy
- vars = importr('vars')
- urca = importr('urca')
-except ImportError:
- pass
-
DECIMAL_6 = 6
DECIMAL_5 = 5
DECIMAL_4 = 4
@@ -99,97 +89,5 @@ def __init__(self):
self.res2 = results_var.MacrodataResults()
-class RVAR(object):
- """
- Estimates VAR model using R vars package and rpy
- """
-
- def __init__(self, data, p=1, type='both'):
- self.rdata = data
- self.p = p
- self.type = type
-
- self.pydata = rpy.convert_robj(data)
- self._estimate = None
- self.estimate()
-
- @property
- def aic(self):
- pass
-
- @property
- def bic(self):
- pass
-
- @property
- def beta(self):
- return rpy.convert_robj(r.coef(self._estimate))
-
- def summary(self, equation=None):
- print(r.summary(self._estimate, equation=equation))
-
- def output(self):
- print(self._estimate)
-
- def estimate(self):
- self._estimate = r.VAR(self.rdata, p=self.p, type=self.type)
-
- def plot(self, names=None):
- r.plot(model._estimate, names=names)
-
- def serial_test(self, lags_pt=16, type='PT.asymptotic'):
- f = r['serial.test']
-
- test = f(self._estimate, **{'lags.pt': lags_pt,
- 'type': type})
-
- return test
-
- def data_summary(self):
- print(r.summary(self.rdata))
-
-
-class TestVAR(TestCase):
-
- def setUp(self):
- try:
- import rpy2
- except ImportError:
- raise nose.SkipTest("No rpy2")
-
- self.rdata = rpy.load_data('Canada', package='vars', convert=False)
- self.data = rpy.load_data('Canada', package='vars', convert=True)
-
- self.res = VAR(self.data)
- self.ref = RVAR(self.rdata)
-
- def test_foo(self):
- pass
-
if __name__ == '__main__':
- # canada = rpy.load_data('Canada', package='vars', convert=False)
-
- # model = RVAR(canada, p=1)
-
- # summary(Canada)
-
- # plot(Canada, nc=2, xlab="")ppp
-
- # adf1 <- summary(ur.df(Canada[, "prod"], type = "trend", lags = 2))
- # adf1
-
- # adf2 <- summary(ur.df(diff(Canada[, "prod"]), type = "drift", lags = 1))
- # adf2
-
- # VARselect(Canada, lag.max = 8, type = "both")
-
- # Canada <- Canada[, c("prod", "e", "U", "rw")]
-
- # p1ct <- VAR(Canada, p = 1, type = "both")
- # p1ct
-
- # coefs <- coef(p1ct)
- # class(coefs)
-
- # run_module_suite()
unittest.main()
diff --git a/pandas/util/print_versions.py b/pandas/util/print_versions.py
index d3dbeef1af4d2..c1804c34ce3d2 100644
--- a/pandas/util/print_versions.py
+++ b/pandas/util/print_versions.py
@@ -83,7 +83,6 @@ def show_versions(as_json=False):
("html5lib", lambda mod: mod.__version__),
("httplib2", lambda mod: mod.__version__),
("apiclient", lambda mod: mod.__version__),
- ("rpy2", lambda mod: mod.__version__),
("sqlalchemy", lambda mod: mod.__version__),
("pymysql", lambda mod: mod.__version__),
("psycopg2", lambda mod: mod.__version__),
| closes #9602
| https://api.github.com/repos/pandas-dev/pandas/pulls/9612 | 2015-03-07T23:37:38Z | 2015-03-08T16:29:06Z | 2015-03-08T16:29:06Z | 2015-03-08T16:52:18Z |
ENH: Add days_in_month property to Timestamp/DatetimeIndex/... (GH9572) | diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt
index d45125f2be7f3..9df0234da93be 100644
--- a/doc/source/whatsnew/v0.16.0.txt
+++ b/doc/source/whatsnew/v0.16.0.txt
@@ -61,6 +61,7 @@ New features
- Added ``StringMethods.ljust()`` and ``rjust()`` which behave as the same as standard ``str`` (:issue:`9352`)
- ``StringMethods.pad()`` and ``center()`` now accept ``fillchar`` option to specify filling character (:issue:`9352`)
- Added ``StringMethods.zfill()`` which behave as the same as standard ``str`` (:issue:`9387`)
+- Added ``days_in_month`` (compatibility alias ``daysinmonth``) property to ``Timestamp``, ``DatetimeIndex``, ``Period``, ``PeriodIndex``, and ``Series.dt`` (:issue:`9572`)
DataFrame Assign
~~~~~~~~~~~~~~~~
diff --git a/pandas/src/period.pyx b/pandas/src/period.pyx
index 05e8ed22fc316..cc6ad3defe4f3 100644
--- a/pandas/src/period.pyx
+++ b/pandas/src/period.pyx
@@ -95,6 +95,7 @@ cdef extern from "period_helper.h":
int phour(int64_t ordinal, int freq) except INT32_MIN
int pminute(int64_t ordinal, int freq) except INT32_MIN
int psecond(int64_t ordinal, int freq) except INT32_MIN
+ int pdays_in_month(int64_t ordinal, int freq) except INT32_MIN
char *c_strftime(date_info *dinfo, char *fmt)
int get_yq(int64_t ordinal, int freq, int *quarter, int *year)
@@ -427,6 +428,8 @@ cdef accessor _get_accessor_func(int code):
return &pday_of_year
elif code == 10:
return &pweekday
+ elif code == 11:
+ return &pdays_in_month
return NULL
@@ -925,6 +928,12 @@ cdef class Period(object):
property qyear:
def __get__(self):
return self._field(1)
+ property days_in_month:
+ def __get__(self):
+ return self._field(11)
+ property daysinmonth:
+ def __get__(self):
+ return self.days_in_month
@classmethod
def now(cls, freq=None):
diff --git a/pandas/src/period_helper.c b/pandas/src/period_helper.c
index 6641000544858..032bc44de6355 100644
--- a/pandas/src/period_helper.c
+++ b/pandas/src/period_helper.c
@@ -1439,3 +1439,13 @@ int psecond(npy_int64 ordinal, int freq) {
return INT_ERR_CODE;
return (int)dinfo.second;
}
+
+int pdays_in_month(npy_int64 ordinal, int freq) {
+ int days;
+ struct date_info dinfo;
+ if(get_date_info(ordinal, freq, &dinfo) == INT_ERR_CODE)
+ return INT_ERR_CODE;
+
+ days = days_in_month[dInfoCalc_Leapyear(dinfo.year, dinfo.calendar)][dinfo.month-1];
+ return days;
+}
diff --git a/pandas/src/period_helper.h b/pandas/src/period_helper.h
index 55c3722ebaae7..19b186afb9fc8 100644
--- a/pandas/src/period_helper.h
+++ b/pandas/src/period_helper.h
@@ -160,6 +160,7 @@ int pweek(npy_int64 ordinal, int freq);
int phour(npy_int64 ordinal, int freq);
int pminute(npy_int64 ordinal, int freq);
int psecond(npy_int64 ordinal, int freq);
+int pdays_in_month(npy_int64 ordinal, int freq);
double getAbsTime(int freq, npy_int64 dailyDate, npy_int64 originalDate);
char *c_strftime(struct date_info *dinfo, char *fmt);
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 5f1cad11f72fe..e5d983472256f 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -79,7 +79,7 @@ def test_dt_namespace_accessor(self):
# GH 7207
# test .dt namespace accessor
- ok_for_base = ['year','month','day','hour','minute','second','weekofyear','week','dayofweek','weekday','dayofyear','quarter','freq']
+ ok_for_base = ['year','month','day','hour','minute','second','weekofyear','week','dayofweek','weekday','dayofyear','quarter','freq','days_in_month','daysinmonth']
ok_for_period = ok_for_base + ['qyear']
ok_for_dt = ok_for_base + ['date','time','microsecond','nanosecond', 'is_month_start', 'is_month_end', 'is_quarter_start',
'is_quarter_end', 'is_year_start', 'is_year_end', 'tz']
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index 24d12078fd7f0..ca5119acc8b99 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -187,7 +187,7 @@ def _join_i8_wrapper(joinf, **kwargs):
_comparables = ['name','freqstr','tz']
_attributes = ['name','freq','tz']
_datetimelike_ops = ['year','month','day','hour','minute','second',
- 'weekofyear','week','dayofweek','weekday','dayofyear','quarter',
+ 'weekofyear','week','dayofweek','weekday','dayofyear','quarter', 'days_in_month', 'daysinmonth',
'date','time','microsecond','nanosecond','is_month_start','is_month_end',
'is_quarter_start','is_quarter_end','is_year_start','is_year_end','tz','freq']
_is_numeric_dtype = False
@@ -1401,6 +1401,8 @@ def _set_freq(self, value):
weekday = dayofweek
dayofyear = _field_accessor('dayofyear', 'doy', "The ordinal day of the year")
quarter = _field_accessor('quarter', 'q', "The quarter of the date")
+ days_in_month = _field_accessor('days_in_month', 'dim', "The number of days in the month")
+ daysinmonth = days_in_month
is_month_start = _field_accessor('is_month_start', 'is_month_start', "Logical indicating if first day of month (defined by frequency)")
is_month_end = _field_accessor('is_month_end', 'is_month_end', "Logical indicating if last day of month (defined by frequency)")
is_quarter_start = _field_accessor('is_quarter_start', 'is_quarter_start', "Logical indicating if first day of quarter (defined by frequency)")
diff --git a/pandas/tseries/period.py b/pandas/tseries/period.py
index 1a2381441ab8d..b1f0ba1f127fa 100644
--- a/pandas/tseries/period.py
+++ b/pandas/tseries/period.py
@@ -150,7 +150,7 @@ class PeriodIndex(DatetimeIndexOpsMixin, Int64Index):
_typ = 'periodindex'
_attributes = ['name','freq']
_datetimelike_ops = ['year','month','day','hour','minute','second',
- 'weekofyear','week','dayofweek','weekday','dayofyear','quarter', 'qyear', 'freq']
+ 'weekofyear','week','dayofweek','weekday','dayofyear','quarter', 'qyear', 'freq', 'days_in_month', 'daysinmonth']
_is_numeric_dtype = False
freq = None
@@ -385,7 +385,9 @@ def to_datetime(self, dayfirst=False):
dayofyear = day_of_year = _field_accessor('dayofyear', 9, "The ordinal day of the year")
quarter = _field_accessor('quarter', 2, "The quarter of the date")
qyear = _field_accessor('qyear', 1)
-
+ days_in_month = _field_accessor('days_in_month', 11, "The number of days in the month")
+ daysinmonth = days_in_month
+
def _get_object_array(self):
freq = self.freq
return np.array([ Period._from_ordinal(ordinal=x, freq=freq) for x in self.values], copy=False)
diff --git a/pandas/tseries/tests/test_period.py b/pandas/tseries/tests/test_period.py
index 5f48861097b6d..17edcd7504102 100644
--- a/pandas/tseries/tests/test_period.py
+++ b/pandas/tseries/tests/test_period.py
@@ -432,7 +432,9 @@ def test_properties_weekly(self):
assert_equal(w_date.month, 1)
assert_equal(w_date.week, 1)
assert_equal((w_date - 1).week, 52)
-
+ assert_equal(w_date.days_in_month, 31)
+ assert_equal(Period(freq='WK', year=2012, month=2, day=1).days_in_month, 29)
+
def test_properties_daily(self):
# Test properties on Periods with daily frequency.
b_date = Period(freq='B', year=2007, month=1, day=1)
@@ -443,6 +445,8 @@ def test_properties_daily(self):
assert_equal(b_date.day, 1)
assert_equal(b_date.weekday, 0)
assert_equal(b_date.dayofyear, 1)
+ assert_equal(b_date.days_in_month, 31)
+ assert_equal(Period(freq='B', year=2012, month=2, day=1).days_in_month, 29)
#
d_date = Period(freq='D', year=2007, month=1, day=1)
#
@@ -452,6 +456,9 @@ def test_properties_daily(self):
assert_equal(d_date.day, 1)
assert_equal(d_date.weekday, 0)
assert_equal(d_date.dayofyear, 1)
+ assert_equal(d_date.days_in_month, 31)
+ assert_equal(Period(freq='D', year=2012, month=2,
+ day=1).days_in_month, 29)
def test_properties_hourly(self):
# Test properties on Periods with hourly frequency.
@@ -464,6 +471,9 @@ def test_properties_hourly(self):
assert_equal(h_date.weekday, 0)
assert_equal(h_date.dayofyear, 1)
assert_equal(h_date.hour, 0)
+ assert_equal(h_date.days_in_month, 31)
+ assert_equal(Period(freq='H', year=2012, month=2, day=1,
+ hour=0).days_in_month, 29)
#
def test_properties_minutely(self):
@@ -478,6 +488,9 @@ def test_properties_minutely(self):
assert_equal(t_date.dayofyear, 1)
assert_equal(t_date.hour, 0)
assert_equal(t_date.minute, 0)
+ assert_equal(t_date.days_in_month, 31)
+ assert_equal(Period(freq='D', year=2012, month=2, day=1, hour=0,
+ minute=0).days_in_month, 29)
def test_properties_secondly(self):
# Test properties on Periods with secondly frequency.
@@ -493,13 +506,16 @@ def test_properties_secondly(self):
assert_equal(s_date.hour, 0)
assert_equal(s_date.minute, 0)
assert_equal(s_date.second, 0)
+ assert_equal(s_date.days_in_month, 31)
+ assert_equal(Period(freq='Min', year=2012, month=2, day=1, hour=0,
+ minute=0, second=0).days_in_month, 29)
def test_properties_nat(self):
p_nat = Period('NaT', freq='M')
t_nat = pd.Timestamp('NaT')
# confirm Period('NaT') work identical with Timestamp('NaT')
for f in ['year', 'month', 'day', 'hour', 'minute', 'second',
- 'week', 'dayofyear', 'quarter']:
+ 'week', 'dayofyear', 'quarter', 'days_in_month']:
self.assertTrue(np.isnan(getattr(p_nat, f)))
self.assertTrue(np.isnan(getattr(t_nat, f)))
@@ -2327,7 +2343,7 @@ def test_fields(self):
def _check_all_fields(self, periodindex):
fields = ['year', 'month', 'day', 'hour', 'minute',
'second', 'weekofyear', 'week', 'dayofweek',
- 'weekday', 'dayofyear', 'quarter', 'qyear']
+ 'weekday', 'dayofyear', 'quarter', 'qyear', 'days_in_month']
periods = list(periodindex)
diff --git a/pandas/tseries/tests/test_timeseries.py b/pandas/tseries/tests/test_timeseries.py
index b65ecd14d3fff..436a976c72e7e 100644
--- a/pandas/tseries/tests/test_timeseries.py
+++ b/pandas/tseries/tests/test_timeseries.py
@@ -937,7 +937,7 @@ def test_nat_vector_field_access(self):
fields = ['year', 'quarter', 'month', 'day', 'hour',
'minute', 'second', 'microsecond', 'nanosecond',
- 'week', 'dayofyear']
+ 'week', 'dayofyear', 'days_in_month']
for field in fields:
result = getattr(idx, field)
expected = [getattr(x, field) if x is not NaT else np.nan
@@ -947,7 +947,7 @@ def test_nat_vector_field_access(self):
def test_nat_scalar_field_access(self):
fields = ['year', 'quarter', 'month', 'day', 'hour',
'minute', 'second', 'microsecond', 'nanosecond',
- 'week', 'dayofyear']
+ 'week', 'dayofyear', 'days_in_month']
for field in fields:
result = getattr(NaT, field)
self.assertTrue(np.isnan(result))
@@ -1625,7 +1625,7 @@ def test_timestamp_fields(self):
# extra fields from DatetimeIndex like quarter and week
idx = tm.makeDateIndex(100)
- fields = ['dayofweek', 'dayofyear', 'week', 'weekofyear', 'quarter', 'is_month_start', 'is_month_end', 'is_quarter_start', 'is_quarter_end', 'is_year_start', 'is_year_end']
+ fields = ['dayofweek', 'dayofyear', 'week', 'weekofyear', 'quarter', 'days_in_month', 'is_month_start', 'is_month_end', 'is_quarter_start', 'is_quarter_end', 'is_year_start', 'is_year_end']
for f in fields:
expected = getattr(idx, f)[-1]
result = getattr(Timestamp(idx[-1]), f)
@@ -2865,6 +2865,9 @@ def test_datetimeindex_accessors(self):
self.assertEqual(dti.quarter[0], 1)
self.assertEqual(dti.quarter[120], 2)
+ self.assertEqual(dti.days_in_month[0], 31)
+ self.assertEqual(dti.days_in_month[90], 30)
+
self.assertEqual(dti.is_month_start[0], True)
self.assertEqual(dti.is_month_start[1], False)
self.assertEqual(dti.is_month_start[31], True)
@@ -2948,7 +2951,9 @@ def test_datetimeindex_accessors(self):
(Timestamp('2013-06-28', offset='BQS-APR').is_quarter_end, 1),
(Timestamp('2013-03-29', offset='BQS-APR').is_year_end, 1),
(Timestamp('2013-11-01', offset='AS-NOV').is_year_start, 1),
- (Timestamp('2013-10-31', offset='AS-NOV').is_year_end, 1)]
+ (Timestamp('2013-10-31', offset='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:
self.assertEqual(ts, value)
diff --git a/pandas/tslib.pyx b/pandas/tslib.pyx
index f4cf711951f5e..eee72f268036a 100644
--- a/pandas/tslib.pyx
+++ b/pandas/tslib.pyx
@@ -390,6 +390,12 @@ class Timestamp(_Timestamp):
def quarter(self):
return self._get_field('q')
+ @property
+ def days_in_month(self):
+ return self._get_field('dim')
+
+ daysinmonth = days_in_month
+
@property
def freqstr(self):
return getattr(self.offset, 'freqstr', self.offset)
@@ -603,7 +609,7 @@ class NaTType(_NaT):
fields = ['year', 'quarter', 'month', 'day', 'hour',
'minute', 'second', 'millisecond', 'microsecond', 'nanosecond',
- 'week', 'dayofyear']
+ 'week', 'dayofyear', 'days_in_month']
for field in fields:
prop = property(fget=lambda self: np.nan)
setattr(NaTType, field, prop)
@@ -3188,6 +3194,14 @@ def get_date_field(ndarray[int64_t] dtindex, object field):
out[i] = ((out[i] - 1) / 3) + 1
return out
+ elif field == 'dim':
+ for i in range(count):
+ if dtindex[i] == NPY_NAT: out[i] = -1; continue
+
+ pandas_datetime_to_datetimestruct(dtindex[i], PANDAS_FR_ns, &dts)
+ out[i] = monthrange(dts.year, dts.month)[1]
+ return out
+
raise ValueError("Field %s not supported" % field)
| closes #9572
Added days_in_month property (compatibility alias daysinmonth) to Timestamp, DatetimeIndex, Period, PeriodIndex,
Series.dt.
Although not mentioned in the GH issue, I added the property to Period and PeriodIndex to be consistent with the others: dayofweek, dayofyear, etc.
| https://api.github.com/repos/pandas-dev/pandas/pulls/9605 | 2015-03-06T20:01:46Z | 2015-03-06T23:09:16Z | 2015-03-06T23:09:16Z | 2015-03-07T15:09:41Z |
Fix several stata doc issues | diff --git a/doc/source/io.rst b/doc/source/io.rst
index 1b88a5ba3ba98..d49e88c953b27 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -3779,15 +3779,15 @@ into a .dta file. The format version of this file is always 115 (Stata 12).
df = DataFrame(randn(10, 2), columns=list('AB'))
df.to_stata('stata.dta')
-*Stata* data files have limited data type support; only strings with 244 or
-fewer characters, ``int8``, ``int16``, ``int32``, ``float32` and ``float64``
-can be stored
-in ``.dta`` files. Additionally, *Stata* reserves certain values to represent
-missing data. Exporting a non-missing value that is outside of the
-permitted range in Stata for a particular data type will retype the variable
-to the next larger size. For example, ``int8`` values are restricted to lie
-between -127 and 100 in Stata, and so variables with values above 100 will
-trigger a conversion to ``int16``. ``nan`` values in floating points data
+*Stata* data files have limited data type support; only strings with
+244 or fewer characters, ``int8``, ``int16``, ``int32``, ``float32``
+and ``float64`` can be stored in ``.dta`` files. Additionally,
+*Stata* reserves certain values to represent missing data. Exporting a
+non-missing value that is outside of the permitted range in Stata for
+a particular data type will retype the variable to the next larger
+size. For example, ``int8`` values are restricted to lie between -127
+and 100 in Stata, and so variables with values above 100 will trigger
+a conversion to ``int16``. ``nan`` values in floating points data
types are stored as the basic missing data type (``.`` in *Stata*).
.. note::
@@ -3810,7 +3810,7 @@ outside of this range, the variable is cast to ``int16``.
.. warning::
- :class:`~pandas.io.stata.StataWriter`` and
+ :class:`~pandas.io.stata.StataWriter` and
:func:`~pandas.core.frame.DataFrame.to_stata` only support fixed width
strings containing up to 244 characters, a limitation imposed by the version
115 dta file format. Attempting to write *Stata* dta files with strings
@@ -3836,9 +3836,11 @@ Specifying a ``chunksize`` yields a
read ``chunksize`` lines from the file at a time. The ``StataReader``
object can be used as an iterator.
- reader = pd.read_stata('stata.dta', chunksize=1000)
- for df in reader:
- do_something(df)
+.. ipython:: python
+
+ reader = pd.read_stata('stata.dta', chunksize=3)
+ for df in reader:
+ print(df.shape)
For more fine-grained control, use ``iterator=True`` and specify
``chunksize`` with each call to
@@ -3847,8 +3849,8 @@ For more fine-grained control, use ``iterator=True`` and specify
.. ipython:: python
reader = pd.read_stata('stata.dta', iterator=True)
- chunk1 = reader.read(10)
- chunk2 = reader.read(20)
+ chunk1 = reader.read(5)
+ chunk2 = reader.read(5)
Currently the ``index`` is retrieved as a column.
@@ -3861,7 +3863,7 @@ The parameter ``convert_missing`` indicates whether missing value
representations in Stata should be preserved. If ``False`` (the default),
missing values are represented as ``np.nan``. If ``True``, missing values are
represented using ``StataMissingValue`` objects, and columns containing missing
-values will have ```object`` data type.
+values will have ``object`` data type.
:func:`~pandas.read_stata` and :class:`~pandas.io.stata.StataReader` supports .dta
formats 104, 105, 108, 113-115 (Stata 10-12) and 117 (Stata 13+).
@@ -3869,7 +3871,7 @@ formats 104, 105, 108, 113-115 (Stata 10-12) and 117 (Stata 13+).
.. note::
Setting ``preserve_dtypes=False`` will upcast to the standard pandas data types:
- ``int64`` for all integer types and ``float64`` for floating poitn data. By default,
+ ``int64`` for all integer types and ``float64`` for floating point data. By default,
the Stata data types are preserved when importing.
.. ipython:: python
| Related to #9493
| https://api.github.com/repos/pandas-dev/pandas/pulls/9601 | 2015-03-06T12:35:44Z | 2015-03-06T23:01:56Z | 2015-03-06T23:01:56Z | 2015-11-12T23:44:11Z |
BUG: Regression in merging Categorical and object dtypes (GH9426) | diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt
index 653c71a4e2d3c..b98429b82b9af 100644
--- a/doc/source/whatsnew/v0.16.0.txt
+++ b/doc/source/whatsnew/v0.16.0.txt
@@ -521,7 +521,7 @@ Bug Fixes
- ``SparseSeries`` and ``SparsePanel`` now accept zero argument constructors (same as their non-sparse counterparts) (:issue:`9272`).
-
+- Regression in merging Categoricals and object dtypes (:issue:`9426`)
- Bug in ``read_csv`` with buffer overflows with certain malformed input files (:issue:`9205`)
- Bug in groupby MultiIndex with missing pair (:issue:`9049`, :issue:`9344`)
- Fixed bug in ``Series.groupby`` where grouping on ``MultiIndex`` levels would ignore the sort argument (:issue:`9444`)
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 2298fbe4afc65..78406682473ff 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -1146,7 +1146,9 @@ def _maybe_promote(dtype, fill_value=np.nan):
dtype = np.object_
# in case we have a string that looked like a number
- if issubclass(np.dtype(dtype).type, compat.string_types):
+ if is_categorical_dtype(dtype):
+ dtype = dtype
+ elif issubclass(np.dtype(dtype).type, compat.string_types):
dtype = np.object_
return dtype, fill_value
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index d5c39a8e2a5cf..af5ec597085ca 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -4327,8 +4327,9 @@ def dtype(self):
if not self.needs_filling:
return self.block.dtype
else:
- return np.dtype(com._maybe_promote(self.block.dtype,
- self.block.fill_value)[0])
+ return com._get_dtype(com._maybe_promote(self.block.dtype,
+ self.block.fill_value)[0])
+
return self._dtype
@cache_readonly
diff --git a/pandas/io/tests/test_data.py b/pandas/io/tests/test_data.py
index b3753f4cb941b..937af834d348b 100644
--- a/pandas/io/tests/test_data.py
+++ b/pandas/io/tests/test_data.py
@@ -112,7 +112,7 @@ def test_get_multi2(self):
# sanity checking
- assert np.issubdtype(result.dtype, np.floating)
+ self.assertTrue(np.issubdtype(result.dtype, np.floating))
result = pan.Open.ix['Jan-15-12':'Jan-20-12']
self.assertEqual((4, 3), result.shape)
assert_n_failed_equals_n_null_columns(w, result)
@@ -121,11 +121,11 @@ def test_get_multi2(self):
def test_dtypes(self):
#GH3995, #GH8980
data = web.get_data_google('F', start='JAN-01-10', end='JAN-27-13')
- assert np.issubdtype(data.Open.dtype, np.number)
- assert np.issubdtype(data.Close.dtype, np.number)
- assert np.issubdtype(data.Low.dtype, np.number)
- assert np.issubdtype(data.High.dtype, np.number)
- assert np.issubdtype(data.Volume.dtype, np.number)
+ self.assertTrue(np.issubdtype(data.Open.dtype, np.number))
+ self.assertTrue(np.issubdtype(data.Close.dtype, np.number))
+ self.assertTrue(np.issubdtype(data.Low.dtype, np.number))
+ self.assertTrue(np.issubdtype(data.High.dtype, np.number))
+ self.assertTrue(np.issubdtype(data.Volume.dtype, np.number))
@network
def test_unicode_date(self):
@@ -183,7 +183,7 @@ def test_get_components_dow_jones(self):
raise nose.SkipTest('unreliable test, receive partial components back for dow_jones')
df = web.get_components_yahoo('^DJI') #Dow Jones
- assert isinstance(df, pd.DataFrame)
+ self.assertIsInstance(df, pd.DataFrame)
self.assertEqual(len(df), 30)
@network
@@ -191,7 +191,7 @@ def test_get_components_dax(self):
raise nose.SkipTest('unreliable test, receive partial components back for dax')
df = web.get_components_yahoo('^GDAXI') #DAX
- assert isinstance(df, pd.DataFrame)
+ self.assertIsInstance(df, pd.DataFrame)
self.assertEqual(len(df), 30)
self.assertEqual(df[df.name.str.contains('adidas', case=False)].index,
'ADS.DE')
@@ -202,13 +202,13 @@ def test_get_components_nasdaq_100(self):
raise nose.SkipTest('unreliable test, receive partial components back for nasdaq_100')
df = web.get_components_yahoo('^NDX') #NASDAQ-100
- assert isinstance(df, pd.DataFrame)
+ self.assertIsInstance(df, pd.DataFrame)
if len(df) > 1:
# Usual culprits, should be around for a while
- assert 'AAPL' in df.index
- assert 'GOOG' in df.index
- assert 'AMZN' in df.index
+ self.assertTrue('AAPL' in df.index)
+ self.assertTrue('GOOG' in df.index)
+ self.assertTrue('AMZN' in df.index)
else:
expected = DataFrame({'exchange': 'N/A', 'name': '@^NDX'},
index=['@^NDX'])
@@ -256,7 +256,7 @@ def test_get_data_multiple_symbols_two_dates(self):
self.assertEqual(len(result), 3)
# sanity checking
- assert np.issubdtype(result.dtype, np.floating)
+ self.assertTrue(np.issubdtype(result.dtype, np.floating))
expected = np.array([[18.99, 28.4, 25.18],
[18.58, 28.31, 25.13],
@@ -276,7 +276,7 @@ def test_get_date_ret_index(self):
self.assertEqual(result, 1.0)
# sanity checking
- assert np.issubdtype(pan.values.dtype, np.floating)
+ self.assertTrue(np.issubdtype(pan.values.dtype, np.floating))
class TestYahooOptions(tm.TestCase):
@@ -383,26 +383,26 @@ def test_get_underlying_price(self):
quote_price = options_object._underlying_price_from_root(root)
except RemoteDataError as e:
raise nose.SkipTest(e)
- self.assert_(isinstance(quote_price, float))
+ self.assertIsInstance(quote_price, float)
def test_sample_page_price_quote_time1(self):
#Tests the weekend quote time format
price, quote_time = self.aapl._underlying_price_and_time_from_url(self.html1)
- self.assert_(isinstance(price, (int, float, complex)))
- self.assert_(isinstance(quote_time, (datetime, Timestamp)))
+ self.assertIsInstance(price, (int, float, complex))
+ self.assertIsInstance(quote_time, (datetime, Timestamp))
def test_chop(self):
#regression test for #7625
self.aapl.chop_data(self.data1, above_below=2, underlying_price=np.nan)
chopped = self.aapl.chop_data(self.data1, above_below=2, underlying_price=100)
- self.assert_(isinstance(chopped, DataFrame))
+ self.assertIsInstance(chopped, DataFrame)
self.assertTrue(len(chopped) > 1)
def test_chop_out_of_strike_range(self):
#regression test for #7625
self.aapl.chop_data(self.data1, above_below=2, underlying_price=np.nan)
chopped = self.aapl.chop_data(self.data1, above_below=2, underlying_price=100000)
- self.assert_(isinstance(chopped, DataFrame))
+ self.assertIsInstance(chopped, DataFrame)
self.assertTrue(len(chopped) > 1)
@@ -411,8 +411,8 @@ def test_sample_page_price_quote_time2(self):
#Tests the EDT page format
#regression test for #8741
price, quote_time = self.aapl._underlying_price_and_time_from_url(self.html2)
- self.assert_(isinstance(price, (int, float, complex)))
- self.assert_(isinstance(quote_time, (datetime, Timestamp)))
+ self.assertIsInstance(price, (int, float, complex))
+ self.assertIsInstance(quote_time, (datetime, Timestamp))
@network
def test_sample_page_chg_float(self):
@@ -452,17 +452,17 @@ def test_is_s3_url(self):
@network
def test_read_yahoo(self):
gs = DataReader("GS", "yahoo")
- assert isinstance(gs, DataFrame)
+ self.assertIsInstance(gs, DataFrame)
@network
def test_read_google(self):
gs = DataReader("GS", "google")
- assert isinstance(gs, DataFrame)
+ self.assertIsInstance(gs, DataFrame)
@network
def test_read_fred(self):
vix = DataReader("VIXCLS", "fred")
- assert isinstance(vix, DataFrame)
+ self.assertIsInstance(vix, DataFrame)
@network
def test_read_famafrench(self):
@@ -470,8 +470,8 @@ def test_read_famafrench(self):
"F-F_Research_Data_Factors_weekly", "6_Portfolios_2x3",
"F-F_ST_Reversal_Factor", "F-F_Momentum_Factor"):
ff = DataReader(name, "famafrench")
- assert ff
- assert isinstance(ff, dict)
+ self.assertTrue(ff is not None)
+ self.assertIsInstance(ff, dict)
class TestFred(tm.TestCase):
@@ -498,7 +498,7 @@ def test_fred_nan(self):
start = datetime(2010, 1, 1)
end = datetime(2013, 1, 27)
df = web.DataReader("DFII5", "fred", start, end)
- assert pd.isnull(df.ix['2010-01-01'][0])
+ self.assertTrue(pd.isnull(df.ix['2010-01-01'][0]))
@network
def test_fred_parts(self):
@@ -510,7 +510,7 @@ def test_fred_parts(self):
self.assertEqual(df.ix['2010-05-01'][0], 217.23)
t = df.CPIAUCSL.values
- assert np.issubdtype(t.dtype, np.floating)
+ self.assertTrue(np.issubdtype(t.dtype, np.floating))
self.assertEqual(t.shape, (37,))
@network
diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py
index 4ba2d5e9acd53..b1dc6813153aa 100644
--- a/pandas/tests/test_categorical.py
+++ b/pandas/tests/test_categorical.py
@@ -2423,6 +2423,39 @@ def f():
df.append(df_wrong_categories)
self.assertRaises(ValueError, f)
+
+ def test_merge(self):
+ # GH 9426
+
+ right = DataFrame({'c': {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'},
+ 'd': {0: 'null', 1: 'null', 2: 'null', 3: 'null', 4: 'null'}})
+ left = DataFrame({'a': {0: 'f', 1: 'f', 2: 'f', 3: 'f', 4: 'f'},
+ 'b': {0: 'g', 1: 'g', 2: 'g', 3: 'g', 4: 'g'}})
+ df = pd.merge(left, right, how='left', left_on='b', right_on='c')
+
+ # object-object
+ expected = df.copy()
+
+ # object-cat
+ cright = right.copy()
+ cright['d'] = cright['d'].astype('category')
+ result = pd.merge(left, cright, how='left', left_on='b', right_on='c')
+ tm.assert_frame_equal(result, expected)
+
+ # cat-object
+ cleft = left.copy()
+ cleft['b'] = cleft['b'].astype('category')
+ result = pd.merge(cleft, cright, how='left', left_on='b', right_on='c')
+ tm.assert_frame_equal(result, expected)
+
+ # cat-cat
+ cright = right.copy()
+ cright['d'] = cright['d'].astype('category')
+ cleft = left.copy()
+ cleft['b'] = cleft['b'].astype('category')
+ result = pd.merge(cleft, cright, how='left', left_on='b', right_on='c')
+ tm.assert_frame_equal(result, expected)
+
def test_na_actions(self):
cat = pd.Categorical([1,2,3,np.nan], categories=[1,2,3])
diff --git a/pandas/tseries/tests/test_tslib.py b/pandas/tseries/tests/test_tslib.py
index f5626618ea9f5..79adabafb7044 100644
--- a/pandas/tseries/tests/test_tslib.py
+++ b/pandas/tseries/tests/test_tslib.py
@@ -167,7 +167,7 @@ def test_repr(self):
# dateutil zone change (only matters for repr)
import dateutil
- if dateutil.__version__ >= LooseVersion('2.3'):
+ if dateutil.__version__ >= LooseVersion('2.3') and dateutil.__version__ <= LooseVersion('2.4'):
timezones = ['UTC', 'Asia/Tokyo', 'US/Eastern', 'dateutil/US/Pacific']
else:
timezones = ['UTC', 'Asia/Tokyo', 'US/Eastern', 'dateutil/America/Los_Angeles']
| closes #9426
| https://api.github.com/repos/pandas-dev/pandas/pulls/9597 | 2015-03-06T00:32:55Z | 2015-03-06T03:18:10Z | 2015-03-06T03:18:10Z | 2015-03-06T03:18:11Z |
DOC: update tutorial docs on changed sniffing feature of read_csv | diff --git a/doc/source/io.rst b/doc/source/io.rst
index e71b4134f5b9c..d1c134e1c6e9d 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -82,10 +82,10 @@ They can take a number of arguments:
(including http, ftp, and S3 locations), or any object with a ``read``
method (such as an open file or ``StringIO``).
- ``sep`` or ``delimiter``: A delimiter / separator to split fields
- on. `read_csv` is capable of inferring the delimiter automatically in some
- cases by "sniffing." The separator may be specified as a regular
- expression; for instance you may use '\|\\s*' to indicate a pipe plus
- arbitrary whitespace.
+ on. With ``sep=None``, ``read_csv`` will try to infer the delimiter
+ automatically in some cases by "sniffing".
+ The separator may be specified as a regular expression; for instance
+ you may use '\|\\s*' to indicate a pipe plus arbitrary whitespace.
- ``delim_whitespace``: Parse whitespace-delimited (spaces or tabs) file
(much faster than using a regular expression)
- ``compression``: decompress ``'gzip'`` and ``'bz2'`` formats on the fly.
@@ -1085,8 +1085,8 @@ Automatically "sniffing" the delimiter
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``read_csv`` is capable of inferring delimited (not necessarily
-comma-separated) files. YMMV, as pandas uses the :class:`python:csv.Sniffer`
-class of the csv module.
+comma-separated) files, as pandas uses the :class:`python:csv.Sniffer`
+class of the csv module. For this, you have to specify ``sep=None``.
.. ipython:: python
:suppress:
@@ -1098,7 +1098,7 @@ class of the csv module.
.. ipython:: python
print(open('tmp2.sv').read())
- pd.read_csv('tmp2.sv')
+ pd.read_csv('tmp2.sv', sep=None)
.. _io.chunking:
| This was apparantly already changed in 0.7, but the docs were still wrong about it. The current example did not make much sense: http://pandas.pydata.org/pandas-docs/stable/io.html#automatically-sniffing-the-delimiter
| https://api.github.com/repos/pandas-dev/pandas/pulls/9588 | 2015-03-04T15:46:25Z | 2015-03-05T09:20:43Z | 2015-03-05T09:20:43Z | 2015-03-05T09:20:43Z |
Test added and patch to fix python-version-dependent issues when len ro... | diff --git a/pandas/sparse/scipy_sparse.py b/pandas/sparse/scipy_sparse.py
index 91ec26396b3ec..da079a97873b8 100644
--- a/pandas/sparse/scipy_sparse.py
+++ b/pandas/sparse/scipy_sparse.py
@@ -8,7 +8,7 @@
from pandas.core.series import Series
import itertools
import numpy as np
-from pandas.compat import OrderedDict
+from pandas.compat import OrderedDict, lmap
from pandas.tools.util import cartesian_product
@@ -54,7 +54,7 @@ def get_indexers(levels):
def _get_label_to_i_dict(labels, sort_labels=False):
""" Return OrderedDict of unique labels to number.
Optionally sort by label. """
- labels = Index(map(tuple, labels)).unique().tolist() # squish
+ labels = Index(lmap(tuple, labels)).unique().tolist() # squish
if sort_labels:
labels = sorted(list(labels))
d = OrderedDict((k, i) for i, k in enumerate(labels))
@@ -73,7 +73,8 @@ def robust_get_level_values(i):
labels_to_i = _get_label_to_i_dict(
ilabels, sort_labels=sort_labels)
labels_to_i = Series(labels_to_i)
- labels_to_i.index = MultiIndex.from_tuples(labels_to_i.index)
+ if len(subset) > 1:
+ labels_to_i.index = MultiIndex.from_tuples(labels_to_i.index)
labels_to_i.index.names = [index.names[i] for i in subset]
labels_to_i.name = 'value'
return(labels_to_i)
diff --git a/pandas/sparse/tests/test_sparse.py b/pandas/sparse/tests/test_sparse.py
index b0cd81ce4d111..f187e7f883e11 100644
--- a/pandas/sparse/tests/test_sparse.py
+++ b/pandas/sparse/tests/test_sparse.py
@@ -783,8 +783,10 @@ def setUp(self):
([3.0, 1.0, 2.0], ([0, 1, 1], [0, 2, 3])), shape=(3, 4)))
self.coo_matrices.append(scipy.sparse.coo_matrix(
([3.0, 1.0, 2.0], ([1, 0, 0], [0, 2, 3])), shape=(3, 4)))
- self.ils = [[(1, 2), (1, 1), (2, 1)], [(1, 1), (1, 2), (2, 1)]]
- self.jls = [[('a', 0), ('a', 1), ('b', 0), ('b', 1)]]
+ self.coo_matrices.append(scipy.sparse.coo_matrix(
+ ([3.0, 1.0, 2.0], ([0, 1, 1], [0, 0, 1])), shape=(3, 2)))
+ self.ils = [[(1, 2), (1, 1), (2, 1)], [(1, 1), (1, 2), (2, 1)], [(1, 2, 'a'), (1, 1, 'b'), (2, 1, 'b')]]
+ self.jls = [[('a', 0), ('a', 1), ('b', 0), ('b', 1)], [0, 1]]
def test_to_coo_text_names_integer_row_levels_nosort(self):
ss = self.sparse_series[0]
@@ -799,6 +801,13 @@ def test_to_coo_text_names_integer_row_levels_sort(self):
result = (self.coo_matrices[1], self.ils[1], self.jls[0])
self._run_test(ss, kwargs, result)
+ def test_to_coo_text_names_text_row_levels_nosort_col_level_single(self):
+ ss = self.sparse_series[0]
+ kwargs = {'row_levels': ['A', 'B', 'C'],
+ 'column_levels': ['D'], 'sort_labels': False}
+ result = (self.coo_matrices[2], self.ils[2], self.jls[1])
+ self._run_test(ss, kwargs, result)
+
def test_to_coo_integer_names_integer_row_levels_nosort(self):
ss = self.sparse_series[1]
kwargs = {'row_levels': [3, 0], 'column_levels': [1, 2]}
| ...w/col_levels is 1.
The docs for sparse to_coo methods failed to build. There was some case (row_levels len 1) that failed in python 2.7 only that I failed to test (and I have been building docs in python 3). Have added test and patched. Also needed to expand the interator (list(map(... ) in the "# squish" line as there was some tupleizing differences between python 3 and 2.
Perhaps there is a better way to avoid these issues? Waiting for Travis.
| https://api.github.com/repos/pandas-dev/pandas/pulls/9583 | 2015-03-03T23:44:05Z | 2015-03-05T23:21:12Z | 2015-03-05T23:21:12Z | 2015-03-07T12:43:55Z |
Deprecation for 0.16 (#6581) | diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt
index 1550527706a9e..7c9366947059b 100644
--- a/doc/source/whatsnew/v0.16.0.txt
+++ b/doc/source/whatsnew/v0.16.0.txt
@@ -217,6 +217,12 @@ Deprecations
.. _whatsnew_0160.deprecations:
+- ``DataFrame.pivot_table`` and ``crosstab``'s ``rows`` and ``cols`` keyword arguments were removed in favor
+ of ``index`` and ``columns`` (:issue:`6581`)
+- ``DataFrame.to_excel`` and ``DataFrame.to_csv`` ``cols`` keyword argument was removed in favor of ``columns`` (:issue:`6581`)
+- Removed ``covert_dummies`` in favor of ``get_dummies`` (:issue:`6581`)
+- Removed ``value_range`` in favor of ``describe`` (:issue:`6581`)
+
Enhancements
~~~~~~~~~~~~
diff --git a/pandas/__init__.py b/pandas/__init__.py
index 69e8a4bad377e..939495d3687ad 100644
--- a/pandas/__init__.py
+++ b/pandas/__init__.py
@@ -57,7 +57,6 @@
from pandas.tools.pivot import pivot_table, crosstab
from pandas.tools.plotting import scatter_matrix, plot_params
from pandas.tools.tile import cut, qcut
-from pandas.tools.util import value_range
from pandas.core.reshape import melt
from pandas.util.print_versions import show_versions
import pandas.util.testing
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 77b13f53166cd..5bfdaa725b16e 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1107,7 +1107,6 @@ def to_panel(self):
to_wide = deprecate('to_wide', to_panel)
- @deprecate_kwarg(old_arg_name='cols', new_arg_name='columns')
def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None,
columns=None, header=True, index=True, index_label=None,
mode='w', encoding=None, quoting=None,
@@ -1165,7 +1164,6 @@ def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None,
or new (expanded format) if False)
date_format : string, default None
Format string for datetime objects
- cols : kwarg only alias of columns [deprecated]
"""
formatter = fmt.CSVFormatter(self, path_or_buf,
@@ -1186,7 +1184,6 @@ def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None,
if path_or_buf is None:
return formatter.path_or_buf.getvalue()
- @deprecate_kwarg(old_arg_name='cols', new_arg_name='columns')
def to_excel(self, excel_writer, sheet_name='Sheet1', na_rep='',
float_format=None, columns=None, header=True, index=True,
index_label=None, startrow=0, startcol=0, engine=None,
@@ -1228,7 +1225,6 @@ def to_excel(self, excel_writer, sheet_name='Sheet1', na_rep='',
encoding: string, default None
encoding of the resulting excel file. Only necessary for xlwt,
other writers support unicode natively.
- cols : kwarg only alias of columns [deprecated]
inf_rep : string, default 'inf'
Representation for infinity (there is no native representation for
infinity in Excel)
diff --git a/pandas/core/reshape.py b/pandas/core/reshape.py
index 6eb46de11210a..473086914acb0 100644
--- a/pandas/core/reshape.py
+++ b/pandas/core/reshape.py
@@ -929,39 +929,6 @@ def melt_stub(df, stub, i, j):
newdf = newdf.merge(new, how="outer", on=id_vars + [j], copy=False)
return newdf.set_index([i, j])
-
-def convert_dummies(data, cat_variables, prefix_sep='_'):
- """
- Compute DataFrame with specified columns converted to dummy variables (0 /
- 1). Result columns will be prefixed with the column name, then the level
- name, e.g. 'A_foo' for column A and level foo
-
- Parameters
- ----------
- data : DataFrame
- cat_variables : list-like
- Must be column names in the DataFrame
- prefix_sep : string, default '_'
- String to use to separate column name from dummy level
-
- Returns
- -------
- dummies : DataFrame
- """
- import warnings
-
- warnings.warn("'convert_dummies' is deprecated and will be removed "
- "in a future release. Use 'get_dummies' instead.",
- FutureWarning)
-
- result = data.drop(cat_variables, axis=1)
- for variable in cat_variables:
- dummies = _get_dummies_1d(data[variable], prefix=variable,
- prefix_sep=prefix_sep)
- result = result.join(dummies)
- return result
-
-
def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False,
columns=None):
"""
diff --git a/pandas/io/tests/test_excel.py b/pandas/io/tests/test_excel.py
index 95f072835f2b6..699d1212556cc 100644
--- a/pandas/io/tests/test_excel.py
+++ b/pandas/io/tests/test_excel.py
@@ -556,14 +556,6 @@ def test_excel_sheet_by_name_raise(self):
self.assertRaises(xlrd.XLRDError, xl.parse, '0')
- def test_excel_deprecated_options(self):
- with ensure_clean(self.ext) as path:
- with tm.assert_produces_warning(FutureWarning):
- self.frame.to_excel(path, 'test1', cols=['A', 'B'])
-
- with tm.assert_produces_warning(False):
- self.frame.to_excel(path, 'test1', columns=['A', 'B'])
-
def test_excelwriter_contextmanager(self):
_skip_if_no_xlrd()
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index f7c91501b683b..37dbf32c5b2f0 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -5944,23 +5944,6 @@ def test_boolean_comparison(self):
self.assertRaises(ValueError, lambda : df == (2,2))
self.assertRaises(ValueError, lambda : df == [2,2])
- def test_to_csv_deprecated_options(self):
-
- pname = '__tmp_to_csv_deprecated_options__'
- with ensure_clean(pname) as path:
-
- self.tsframe[1:3] = np.nan
- self.tsframe.to_csv(path, nanRep='foo')
- recons = read_csv(path,index_col=0,parse_dates=[0],na_values=['foo'])
- assert_frame_equal(self.tsframe, recons)
-
- with tm.assert_produces_warning(FutureWarning):
- self.frame.to_csv(path, cols=['A', 'B'])
-
- with tm.assert_produces_warning(False):
- self.frame.to_csv(path, columns=['A', 'B'])
-
-
def test_to_csv_from_csv(self):
pname = '__tmp_to_csv_from_csv__'
diff --git a/pandas/tests/test_reshape.py b/pandas/tests/test_reshape.py
index 933cfe54bac27..66f5110830c72 100644
--- a/pandas/tests/test_reshape.py
+++ b/pandas/tests/test_reshape.py
@@ -16,7 +16,7 @@
from pandas.util.testing import assert_frame_equal
from numpy.testing import assert_array_equal
-from pandas.core.reshape import (melt, convert_dummies, lreshape, get_dummies,
+from pandas.core.reshape import (melt, lreshape, get_dummies,
wide_to_long)
import pandas.util.testing as tm
from pandas.compat import StringIO, cPickle, range, u
@@ -322,34 +322,6 @@ def test_dataframe_dummies_with_categorical(self):
'cat_x', 'cat_y']]
assert_frame_equal(result, expected)
-
-class TestConvertDummies(tm.TestCase):
- def test_convert_dummies(self):
- df = DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
- 'foo', 'bar', 'foo', 'foo'],
- 'B': ['one', 'one', 'two', 'three',
- 'two', 'two', 'one', 'three'],
- 'C': np.random.randn(8),
- 'D': np.random.randn(8)})
-
- with tm.assert_produces_warning(FutureWarning):
- result = convert_dummies(df, ['A', 'B'])
- result2 = convert_dummies(df, ['A', 'B'], prefix_sep='.')
-
- expected = DataFrame({'A_foo': [1, 0, 1, 0, 1, 0, 1, 1],
- 'A_bar': [0, 1, 0, 1, 0, 1, 0, 0],
- 'B_one': [1, 1, 0, 0, 0, 0, 1, 0],
- 'B_two': [0, 0, 1, 0, 1, 1, 0, 0],
- 'B_three': [0, 0, 0, 1, 0, 0, 0, 1],
- 'C': df['C'].values,
- 'D': df['D'].values},
- columns=result.columns, dtype=float)
- expected2 = expected.rename(columns=lambda x: x.replace('_', '.'))
-
- tm.assert_frame_equal(result, expected)
- tm.assert_frame_equal(result2, expected2)
-
-
class TestLreshape(tm.TestCase):
def test_pairs(self):
diff --git a/pandas/tools/pivot.py b/pandas/tools/pivot.py
index ef477582b82f2..89fe9463282b6 100644
--- a/pandas/tools/pivot.py
+++ b/pandas/tools/pivot.py
@@ -13,8 +13,6 @@
import pandas.core.common as com
import numpy as np
-@deprecate_kwarg(old_arg_name='cols', new_arg_name='columns')
-@deprecate_kwarg(old_arg_name='rows', new_arg_name='index')
def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean',
fill_value=None, margins=False, dropna=True):
"""
@@ -42,8 +40,6 @@ def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean',
Add all row / columns (e.g. for subtotal / grand totals)
dropna : boolean, default True
Do not include columns whose entries are all NaN
- rows : kwarg only alias of index [deprecated]
- cols : kwarg only alias of columns [deprecated]
Examples
--------
@@ -319,8 +315,6 @@ def _convert_by(by):
by = list(by)
return by
-@deprecate_kwarg(old_arg_name='cols', new_arg_name='columns')
-@deprecate_kwarg(old_arg_name='rows', new_arg_name='index')
def crosstab(index, columns, values=None, rownames=None, colnames=None,
aggfunc=None, margins=False, dropna=True):
"""
@@ -346,8 +340,6 @@ def crosstab(index, columns, values=None, rownames=None, colnames=None,
Add row/column margins (subtotals)
dropna : boolean, default True
Do not include columns whose entries are all NaN
- rows : kwarg only alias of index [deprecated]
- cols : kwarg only alias of columns [deprecated]
Notes
-----
diff --git a/pandas/tools/tests/test_pivot.py b/pandas/tools/tests/test_pivot.py
index 8b6a4d5bacf09..4618501bed841 100644
--- a/pandas/tools/tests/test_pivot.py
+++ b/pandas/tools/tests/test_pivot.py
@@ -53,19 +53,6 @@ def test_pivot_table(self):
expected = self.data.groupby(index + [columns])['D'].agg(np.mean).unstack()
tm.assert_frame_equal(table, expected)
- def test_pivot_table_warnings(self):
- index = ['A', 'B']
- columns = 'C'
- with tm.assert_produces_warning(FutureWarning):
- table = pivot_table(self.data, values='D', rows=index,
- cols=columns)
-
- with tm.assert_produces_warning(False):
- table2 = pivot_table(self.data, values='D', index=index,
- columns=columns)
-
- tm.assert_frame_equal(table, table2)
-
def test_pivot_table_nocols(self):
df = DataFrame({'rows': ['a', 'b', 'c'],
'cols': ['x', 'y', 'z'],
diff --git a/pandas/tools/util.py b/pandas/tools/util.py
index 72fdeaff36ef1..0bb6b4b7f7892 100644
--- a/pandas/tools/util.py
+++ b/pandas/tools/util.py
@@ -48,22 +48,3 @@ def compose(*funcs):
"""Compose 2 or more callables"""
assert len(funcs) > 1, 'At least 2 callables must be passed to compose'
return reduce(_compose2, funcs)
-
-### FIXME: remove in 0.16
-def value_range(df):
- """
- Return the minimum and maximum of a dataframe in a series object
-
- Parameters
- ----------
- df : DataFrame
-
- Returns
- -------
- (maximum, minimum) : Series
-
- """
- from pandas import Series
- warnings.warn("value_range is deprecated. Use .describe() instead", FutureWarning)
-
- return Series((min(df.min()), max(df.max())), ('Minimum', 'Maximum'))
| These are the deprecations that are to be removed in 0.16, per #6581, except for the deprecations around the boxplot function.
| https://api.github.com/repos/pandas-dev/pandas/pulls/9582 | 2015-03-03T23:34:30Z | 2015-03-04T20:50:28Z | 2015-03-04T20:50:28Z | 2015-03-04T20:50:38Z |
DOC: Fixup image size | diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt
index e9f2dcf86e6a3..1550527706a9e 100644
--- a/doc/source/whatsnew/v0.16.0.txt
+++ b/doc/source/whatsnew/v0.16.0.txt
@@ -67,6 +67,7 @@ calculate the ratio, and plot
.plot(kind='scatter', x='SepalRatio', y='PetalRatio'))
.. image:: _static/whatsnew_assign.png
+ :scale: 50 %
See the :ref:`documentation <dsintro.chained_assignment>` for more. (:issue:`9229`)
| Should fix the image being too big: http://pandas-docs.github.io/pandas-docs-travis/whatsnew.html#new-features
| https://api.github.com/repos/pandas-dev/pandas/pulls/9575 | 2015-03-03T04:06:38Z | 2015-03-03T21:15:19Z | 2015-03-03T21:15:19Z | 2017-04-05T02:06:18Z |
fixing pandas.DataFrame.plot(): labels do not appear in legend and label kwd | diff --git a/doc/source/whatsnew/v0.16.1.txt b/doc/source/whatsnew/v0.16.1.txt
index 3c3742c968642..c874a9aaa5d93 100644
--- a/doc/source/whatsnew/v0.16.1.txt
+++ b/doc/source/whatsnew/v0.16.1.txt
@@ -50,6 +50,8 @@ Performance Improvements
Bug Fixes
~~~~~~~~~
+- Fixed bug (:issue:`9542`) where labels did not appear properly in legend of ``DataFrame.plot()``. Passing ``label=`` args also now works, and series indices are no longer mutated.
+
diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py
index 1cb11179b2430..b5d2b91aed1b1 100644
--- a/pandas/tests/test_graphics.py
+++ b/pandas/tests/test_graphics.py
@@ -1064,12 +1064,6 @@ def test_implicit_label(self):
ax = df.plot(x='a', y='b')
self._check_text_labels(ax.xaxis.get_label(), 'a')
- @slow
- def test_explicit_label(self):
- df = DataFrame(randn(10, 3), columns=['a', 'b', 'c'])
- ax = df.plot(x='a', y='b', label='LABEL')
- self._check_text_labels(ax.xaxis.get_label(), 'LABEL')
-
@slow
def test_donot_overwrite_index_name(self):
# GH 8494
@@ -2542,6 +2536,20 @@ def test_df_legend_labels(self):
ax = df3.plot(kind='scatter', x='g', y='h', label='data3', ax=ax)
self._check_legend_labels(ax, labels=['data1', 'data3'])
+ # ensure label args pass through and
+ # index name does not mutate
+ # column names don't mutate
+ df5 = df.set_index('a')
+ ax = df5.plot(y='b')
+ self._check_legend_labels(ax, labels=['b'])
+ ax = df5.plot(y='b', label='LABEL_b')
+ self._check_legend_labels(ax, labels=['LABEL_b'])
+ self._check_text_labels(ax.xaxis.get_label(), 'a')
+ ax = df5.plot(y='c', label='LABEL_c', ax=ax)
+ self._check_legend_labels(ax, labels=['LABEL_b','LABEL_c'])
+ self.assertTrue(df5.columns.tolist() == ['b','c'])
+
+
def test_legend_name(self):
multi = DataFrame(randn(4, 4),
columns=[np.array(['a', 'a', 'b', 'b']),
diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py
index cf9c890823f8f..55b21c4b75fa0 100644
--- a/pandas/tools/plotting.py
+++ b/pandas/tools/plotting.py
@@ -886,10 +886,11 @@ def _iter_data(self, data=None, keep_index=False, fillna=None):
from pandas.core.frame import DataFrame
if isinstance(data, (Series, np.ndarray, Index)):
+ label = self.label if self.label is not None else data.name
if keep_index is True:
- yield self.label, data
+ yield label, data
else:
- yield self.label, np.asarray(data)
+ yield label, np.asarray(data)
elif isinstance(data, DataFrame):
if self.sort_columns:
columns = com._try_sort(data.columns)
@@ -2306,10 +2307,9 @@ def _plot(data, x=None, y=None, subplots=False,
if y is not None:
if com.is_integer(y) and not data.columns.holds_integer():
y = data.columns[y]
- label = x if x is not None else data.index.name
- label = kwds.pop('label', label)
+ label = kwds['label'] if 'label' in kwds else y
series = data[y].copy() # Don't modify
- series.index.name = label
+ series.name = label
for kw in ['xerr', 'yerr']:
if (kw in kwds) and \
| Closes https://github.com/pydata/pandas/issues/9542, #8905
The following behavior has been tested:
- `df.plot(y='sin(x)')` -> gives a legend with label 'None' -> this should give no legend instead (as it plots one series, and then we don't automatically add a legend, see behaviour of df['sin(x)'].plot())
- `df.plot(y='sin(x)', legend=True)` -> gives a legend with label 'None' -> this should of course give a legend with label 'sin(x)' (behaviour as df['sin(x)'].plot(legend=True))
- `df.plot(y='sin(x)', label='something else', legend=True)` -> gives a legend with label 'None' -> should be a legend with label 'something else', as we want that the label kwarg overwrites the column name.
based on following data:
`x=np.linspace(-10,10,201)`
`y,z=np.sin(x),np.cos(x)`
`x,y,z=pd.Series(x),pd.Series(y),pd.Series(z)`
`df=pd.concat([x,y,z],axis=1)`
`df.columns=['x','sin(x)','cos(x)']`
`df=df.set_index('x')`
| https://api.github.com/repos/pandas-dev/pandas/pulls/9574 | 2015-03-03T03:39:15Z | 2015-03-31T01:29:08Z | 2015-03-31T01:29:08Z | 2015-05-01T16:06:11Z |
API: consistency with .ix and .loc for getitem operations (GH8613) | diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst
index 5ab72f633f49b..5079b4fa8ad6f 100644
--- a/doc/source/indexing.rst
+++ b/doc/source/indexing.rst
@@ -85,7 +85,7 @@ of multi-axis indexing.
- ``.iloc`` is primarily integer position based (from ``0`` to
``length-1`` of the axis), but may also be used with a boolean
- array. ``.iloc`` will raise ``IndexError`` if a requested
+ array. ``.iloc`` will raise ``IndexError`` if a requested
indexer is out-of-bounds, except *slice* indexers which allow
out-of-bounds indexing. (this conforms with python/numpy *slice*
semantics). Allowed inputs are:
@@ -292,6 +292,27 @@ Selection By Label
This is sometimes called ``chained assignment`` and should be avoided.
See :ref:`Returning a View versus Copy <indexing.view_versus_copy>`
+.. warning::
+
+ ``.loc`` is strict when you present slicers that are not compatible (or convertible) with the index type. For example
+ using integers in a ``DatetimeIndex``. These will raise a ``TypeError``.
+
+ .. ipython:: python
+
+ dfl = DataFrame(np.random.randn(5,4), columns=list('ABCD'), index=date_range('20130101',periods=5))
+ dfl
+
+ .. code-block:: python
+
+ In [4]: dfl.loc[2:3]
+ TypeError: cannot do slice indexing on <class 'pandas.tseries.index.DatetimeIndex'> with these indexers [2] of <type 'int'>
+
+ String likes in slicing *can* be convertible to the type of the index and lead to natural slicing.
+
+ .. ipython:: python
+
+ dfl.loc['20130102':'20130104']
+
pandas provides a suite of methods in order to have **purely label based indexing**. This is a strict inclusion based protocol.
**at least 1** of the labels for which you ask, must be in the index or a ``KeyError`` will be raised! When slicing, the start bound is *included*, **AND** the stop bound is *included*. Integers are valid labels, but they refer to the label **and not the position**.
@@ -1486,5 +1507,3 @@ This will **not** work at all, and so should be avoided
The chained assignment warnings / exceptions are aiming to inform the user of a possibly invalid
assignment. There may be false positives; situations where a chained assignment is inadvertantly
reported.
-
-
diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt
index 1550527706a9e..9cb474a53f25a 100644
--- a/doc/source/whatsnew/v0.16.0.txt
+++ b/doc/source/whatsnew/v0.16.0.txt
@@ -20,6 +20,8 @@ users upgrade to this version.
New features
~~~~~~~~~~~~
+.. _whatsnew_0160.enhancements:
+
- Reindex now supports ``method='nearest'`` for frames or series with a monotonic increasing or decreasing index (:issue:`9258`):
.. ipython:: python
@@ -29,7 +31,41 @@ New features
This method is also exposed by the lower level ``Index.get_indexer`` and ``Index.get_loc`` methods.
-- DataFrame assign method
+- Paths beginning with ~ will now be expanded to begin with the user's home directory (:issue:`9066`)
+- Added time interval selection in ``get_data_yahoo`` (:issue:`9071`)
+- Added ``Series.str.slice_replace()``, which previously raised ``NotImplementedError`` (:issue:`8888`)
+- Added ``Timestamp.to_datetime64()`` to complement ``Timedelta.to_timedelta64()`` (:issue:`9255`)
+- ``tseries.frequencies.to_offset()`` now accepts ``Timedelta`` as input (:issue:`9064`)
+- Lag parameter was added to the autocorrelation method of ``Series``, defaults to lag-1 autocorrelation (:issue:`9192`)
+- ``Timedelta`` will now accept ``nanoseconds`` keyword in constructor (:issue:`9273`)
+- SQL code now safely escapes table and column names (:issue:`8986`)
+
+- Added auto-complete for ``Series.str.<tab>``, ``Series.dt.<tab>`` and ``Series.cat.<tab>`` (:issue:`9322`)
+- Added ``StringMethods.isalnum()``, ``isalpha()``, ``isdigit()``, ``isspace()``, ``islower()``,
+ ``isupper()``, ``istitle()`` which behave as the same as standard ``str`` (:issue:`9282`)
+
+- Added ``StringMethods.find()`` and ``rfind()`` which behave as the same as standard ``str`` (:issue:`9386`)
+
+- ``Index.get_indexer`` now supports ``method='pad'`` and ``method='backfill'`` even for any target array, not just monotonic targets. These methods also work for monotonic decreasing as well as monotonic increasing indexes (:issue:`9258`).
+- ``Index.asof`` now works on all index types (:issue:`9258`).
+
+- Added ``StringMethods.isnumeric`` and ``isdecimal`` which behave as the same as standard ``str`` (:issue:`9439`)
+- The ``read_excel()`` function's :ref:`sheetname <_io.specifying_sheets>` argument now accepts a list and ``None``, to get multiple or all sheets respectively. If more than one sheet is specified, a dictionary is returned. (:issue:`9450`)
+
+ .. code-block:: python
+
+ # Returns the 1st and 4th sheet, as a dictionary of DataFrames.
+ pd.read_excel('path_to_file.xls',sheetname=['Sheet1',3])
+
+- A ``verbose`` argument has been augmented in ``io.read_excel()``, defaults to False. Set to True to print sheet names as they are parsed. (:issue:`9450`)
+- Added ``StringMethods.ljust()`` and ``rjust()`` which behave as the same as standard ``str`` (:issue:`9352`)
+- ``StringMethods.pad()`` and ``center()`` now accept ``fillchar`` option to specify filling character (:issue:`9352`)
+- Added ``StringMethods.zfill()`` which behave as the same as standard ``str`` (:issue:`9387`)
+
+DataFrame Assign
+~~~~~~~~~~~~~~~~
+
+.. _whatsnew_0160.enhancements.assign:
Inspired by `dplyr's
<http://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html#mutate>`__ ``mutate`` verb, DataFrame has a new
@@ -71,6 +107,55 @@ calculate the ratio, and plot
See the :ref:`documentation <dsintro.chained_assignment>` for more. (:issue:`9229`)
+
+Interaction with scipy.sparse
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+.. _whatsnew_0160.enhancements.sparse:
+
+Added :meth:`SparseSeries.to_coo` and :meth:`SparseSeries.from_coo` methods (:issue:`8048`) for converting to and from ``scipy.sparse.coo_matrix`` instances (see :ref:`here <sparse.scipysparse>`). For example, given a SparseSeries with MultiIndex we can convert to a `scipy.sparse.coo_matrix` by specifying the row and column labels as index levels:
+
+.. ipython:: python
+
+ from numpy import nan
+ s = Series([3.0, nan, 1.0, 3.0, nan, nan])
+ s.index = MultiIndex.from_tuples([(1, 2, 'a', 0),
+ (1, 2, 'a', 1),
+ (1, 1, 'b', 0),
+ (1, 1, 'b', 1),
+ (2, 1, 'b', 0),
+ (2, 1, 'b', 1)],
+ names=['A', 'B', 'C', 'D'])
+
+ s
+
+ # SparseSeries
+ ss = s.to_sparse()
+ ss
+
+ A, rows, columns = ss.to_coo(row_levels=['A', 'B'],
+ column_levels=['C', 'D'],
+ sort_labels=False)
+
+ A
+ A.todense()
+ rows
+ columns
+
+The from_coo method is a convenience method for creating a ``SparseSeries``
+from a ``scipy.sparse.coo_matrix``:
+
+.. ipython:: python
+
+ from scipy import sparse
+ A = sparse.coo_matrix(([3.0, 1.0, 2.0], ([1, 0, 0], [0, 2, 3])),
+ shape=(3, 4))
+ A
+ A.todense()
+
+ ss = SparseSeries.from_coo(A)
+ ss
+
.. _whatsnew_0160.api:
.. _whatsnew_0160.api_breaking:
@@ -211,96 +296,80 @@ Backwards incompatible API changes
p // 0
+Indexing Changes
+~~~~~~~~~~~~~~~~
-Deprecations
-~~~~~~~~~~~~
+.. _whatsnew_0160.api_breaking.indexing:
-.. _whatsnew_0160.deprecations:
+The behavior of a small sub-set of edge cases for using ``.loc`` have changed (:issue:`8613`). Furthermore we have improved the content of the error messages that are raised:
+- slicing with ``.loc`` where the start and/or stop bound is not found in the index is now allowed; this previously would raise a ``KeyError``. This makes the behavior the same as ``.ix`` in this case. This change is only for slicing, not when indexing with a single label.
-Enhancements
-~~~~~~~~~~~~
+ .. ipython:: python
-.. _whatsnew_0160.enhancements:
+ df = DataFrame(np.random.randn(5,4), columns=list('ABCD'), index=date_range('20130101',periods=5))
+ df
+ s = Series(range(5),[-2,-1,1,2,3])
+ s
-- Paths beginning with ~ will now be expanded to begin with the user's home directory (:issue:`9066`)
-- Added time interval selection in ``get_data_yahoo`` (:issue:`9071`)
-- Added ``Series.str.slice_replace()``, which previously raised ``NotImplementedError`` (:issue:`8888`)
-- Added ``Timestamp.to_datetime64()`` to complement ``Timedelta.to_timedelta64()`` (:issue:`9255`)
-- ``tseries.frequencies.to_offset()`` now accepts ``Timedelta`` as input (:issue:`9064`)
-- Lag parameter was added to the autocorrelation method of ``Series``, defaults to lag-1 autocorrelation (:issue:`9192`)
-- ``Timedelta`` will now accept ``nanoseconds`` keyword in constructor (:issue:`9273`)
-- SQL code now safely escapes table and column names (:issue:`8986`)
+ Previous Behavior
-- Added auto-complete for ``Series.str.<tab>``, ``Series.dt.<tab>`` and ``Series.cat.<tab>`` (:issue:`9322`)
-- Added ``StringMethods.isalnum()``, ``isalpha()``, ``isdigit()``, ``isspace()``, ``islower()``,
- ``isupper()``, ``istitle()`` which behave as the same as standard ``str`` (:issue:`9282`)
+ .. code-block:: python
-- Added ``StringMethods.find()`` and ``rfind()`` which behave as the same as standard ``str`` (:issue:`9386`)
+ In [4]: df.loc['2013-01-02':'2013-01-10']
+ KeyError: 'stop bound [2013-01-10] is not in the [index]'
-- ``Index.get_indexer`` now supports ``method='pad'`` and ``method='backfill'`` even for any target array, not just monotonic targets. These methods also work for monotonic decreasing as well as monotonic increasing indexes (:issue:`9258`).
-- ``Index.asof`` now works on all index types (:issue:`9258`).
+ In [6]: s.loc[-10:3]
+ KeyError: 'start bound [-10] is not the [index]'
-- Added ``StringMethods.isnumeric`` and ``isdecimal`` which behave as the same as standard ``str`` (:issue:`9439`)
-- The ``read_excel()`` function's :ref:`sheetname <_io.specifying_sheets>` argument now accepts a list and ``None``, to get multiple or all sheets respectively. If more than one sheet is specified, a dictionary is returned. (:issue:`9450`)
+ New Behavior
+
+ .. ipython:: python
+
+ df.loc['2013-01-02':'2013-01-10']
+ s.loc[-10:3]
+
+- allow slicing with float-like values on an integer index for ``.ix``. Previously this was only enabled for ``.loc``:
.. code-block:: python
- # Returns the 1st and 4th sheet, as a dictionary of DataFrames.
- pd.read_excel('path_to_file.xls',sheetname=['Sheet1',3])
+ Previous Behavior
-- A ``verbose`` argument has been augmented in ``io.read_excel()``, defaults to False. Set to True to print sheet names as they are parsed. (:issue:`9450`)
-- Added ``StringMethods.ljust()`` and ``rjust()`` which behave as the same as standard ``str`` (:issue:`9352`)
-- ``StringMethods.pad()`` and ``center()`` now accept ``fillchar`` option to specify filling character (:issue:`9352`)
-- Added ``StringMethods.zfill()`` which behave as the same as standard ``str`` (:issue:`9387`)
+ In [8]: s.ix[-1.0:2]
+ TypeError: the slice start value [-1.0] is not a proper indexer for this index type (Int64Index)
-Interaction with scipy.sparse
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ New Behavior
-.. _whatsnew_0160.enhancements.sparse:
+ .. ipython:: python
-Added :meth:`SparseSeries.to_coo` and :meth:`SparseSeries.from_coo` methods (:issue:`8048`) for converting to and from ``scipy.sparse.coo_matrix`` instances (see :ref:`here <sparse.scipysparse>`). For example, given a SparseSeries with MultiIndex we can convert to a `scipy.sparse.coo_matrix` by specifying the row and column labels as index levels:
+ In [8]: s.ix[-1.0:2]
+ Out[2]:
+ -1 1
+ 1 2
+ 2 3
+ dtype: int64
-.. ipython:: python
+- provide a useful exception for indexing with an invalid type for that index when using ``.loc``. For example trying to use ``.loc`` on an index of type ``DatetimeIndex`` or ``PeriodIndex`` or ``TimedeltaIndex``, with an integer (or a float).
- from numpy import nan
- s = Series([3.0, nan, 1.0, 3.0, nan, nan])
- s.index = MultiIndex.from_tuples([(1, 2, 'a', 0),
- (1, 2, 'a', 1),
- (1, 1, 'b', 0),
- (1, 1, 'b', 1),
- (2, 1, 'b', 0),
- (2, 1, 'b', 1)],
- names=['A', 'B', 'C', 'D'])
+ Previous Behavior
- s
+ .. code-block:: python
- # SparseSeries
- ss = s.to_sparse()
- ss
+ In [4]: df.loc[2:3]
+ KeyError: 'start bound [2] is not the [index]'
- A, rows, columns = ss.to_coo(row_levels=['A', 'B'],
- column_levels=['C', 'D'],
- sort_labels=False)
+ New Behavior
- A
- A.todense()
- rows
- columns
+ .. code-block:: python
-The from_coo method is a convenience method for creating a ``SparseSeries``
-from a ``scipy.sparse.coo_matrix``:
+ In [4]: df.loc[2:3]
+ TypeError: Cannot do slice indexing on <class 'pandas.tseries.index.DatetimeIndex'> with <type 'int'> keys
-.. ipython:: python
+Deprecations
+~~~~~~~~~~~~
- from scipy import sparse
- A = sparse.coo_matrix(([3.0, 1.0, 2.0], ([1, 0, 0], [0, 2, 3])),
- shape=(3, 4))
- A
- A.todense()
+.. _whatsnew_0160.deprecations:
- ss = SparseSeries.from_coo(A)
- ss
Performance
~~~~~~~~~~~
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 18500fd05b5f8..9e4e79f3d70cb 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1159,11 +1159,11 @@ def _clear_item_cache(self, i=None):
else:
self._item_cache.clear()
- def _slice(self, slobj, axis=0, typ=None):
+ def _slice(self, slobj, axis=0, kind=None):
"""
Construct a slice of this container.
- typ parameter is maintained for compatibility with Series slicing.
+ kind parameter is maintained for compatibility with Series slicing.
"""
axis = self._get_block_manager_axis(axis)
diff --git a/pandas/core/index.py b/pandas/core/index.py
index 0cad537855857..10dcdc5a7185a 100644
--- a/pandas/core/index.py
+++ b/pandas/core/index.py
@@ -632,18 +632,26 @@ def is_mixed(self):
def holds_integer(self):
return self.inferred_type in ['integer', 'mixed-integer']
- def _convert_scalar_indexer(self, key, typ=None):
- """ convert a scalar indexer, right now we are converting
+ def _convert_scalar_indexer(self, key, kind=None):
+ """
+ convert a scalar indexer
+
+ Parameters
+ ----------
+ key : label of the slice bound
+ kind : optional, type of the indexing operation (loc/ix/iloc/None)
+
+ right now we are converting
floats -> ints if the index supports it
"""
def to_int():
ikey = int(key)
if ikey != key:
- return self._convert_indexer_error(key, 'label')
+ return self._invalid_indexer('label', key)
return ikey
- if typ == 'iloc':
+ if kind == 'iloc':
if is_integer(key):
return key
elif is_float(key):
@@ -651,7 +659,7 @@ def to_int():
warnings.warn("scalar indexers for index type {0} should be integers and not floating point".format(
type(self).__name__),FutureWarning)
return key
- return self._convert_indexer_error(key, 'label')
+ return self._invalid_indexer('label', key)
if is_float(key):
if not self.is_floating():
@@ -661,14 +669,6 @@ def to_int():
return key
- def _validate_slicer(self, key, f):
- """ validate and raise if needed on a slice indexers according to the
- passed in function """
-
- for c in ['start','stop','step']:
- if not f(getattr(key,c)):
- self._convert_indexer_error(key.start, 'slice {0} value'.format(c))
-
def _convert_slice_indexer_getitem(self, key, is_index_slice=False):
""" called from the getitem slicers, determine how to treat the key
whether positional or not """
@@ -676,15 +676,22 @@ def _convert_slice_indexer_getitem(self, key, is_index_slice=False):
return key
return self._convert_slice_indexer(key)
- def _convert_slice_indexer(self, key, typ=None):
- """ convert a slice indexer. disallow floats in the start/stop/step """
+ def _convert_slice_indexer(self, key, kind=None):
+ """
+ convert a slice indexer. disallow floats in the start/stop/step
+
+ Parameters
+ ----------
+ key : label of the slice bound
+ kind : optional, type of the indexing operation (loc/ix/iloc/None)
+ """
# if we are not a slice, then we are done
if not isinstance(key, slice):
return key
# validate iloc
- if typ == 'iloc':
+ if kind == 'iloc':
# need to coerce to_int if needed
def f(c):
@@ -698,7 +705,7 @@ def f(c):
"and not floating point",FutureWarning)
return int(v)
- self._convert_indexer_error(v, 'slice {0} value'.format(c))
+ self._invalid_indexer('slice {0} value'.format(c), v)
return slice(*[ f(c) for c in ['start','stop','step']])
@@ -707,12 +714,18 @@ def validate(v):
if v is None or is_integer(v):
return True
- # dissallow floats
+ # dissallow floats (except for .ix)
elif is_float(v):
+ if kind == 'ix':
+ return True
+
return False
return True
- self._validate_slicer(key, validate)
+ for c in ['start','stop','step']:
+ v = getattr(key,c)
+ if not validate(v):
+ self._invalid_indexer('slice {0} value'.format(c), v)
# figure out if this is a positional indexer
start, stop, step = key.start, key.stop, key.step
@@ -724,7 +737,7 @@ def is_int(v):
is_index_slice = is_int(start) and is_int(stop)
is_positional = is_index_slice and not self.is_integer()
- if typ == 'getitem':
+ if kind == 'getitem':
return self._convert_slice_indexer_getitem(
key, is_index_slice=is_index_slice)
@@ -760,16 +773,16 @@ def is_int(v):
return indexer
- def _convert_list_indexer(self, key, typ=None):
+ def _convert_list_indexer(self, key, kind=None):
""" convert a list indexer. these should be locations """
return key
- def _convert_list_indexer_for_mixed(self, keyarr, typ=None):
+ def _convert_list_indexer_for_mixed(self, keyarr, kind=None):
""" passed a key that is tuplesafe that is integer based
and we have a mixed index (e.g. number/labels). figure out
the indexer. return None if we can't help
"""
- if (typ is None or typ in ['iloc','ix']) and (is_integer_dtype(keyarr) and not self.is_floating()):
+ if (kind is None or kind in ['iloc','ix']) and (is_integer_dtype(keyarr) and not self.is_floating()):
if self.inferred_type != 'integer':
keyarr = np.where(keyarr < 0,
len(self) + keyarr, keyarr)
@@ -787,11 +800,13 @@ def _convert_list_indexer_for_mixed(self, keyarr, typ=None):
return None
- def _convert_indexer_error(self, key, msg=None):
- if msg is None:
- msg = 'label'
- raise TypeError("the {0} [{1}] is not a proper indexer for this index "
- "type ({2})".format(msg, key, self.__class__.__name__))
+ def _invalid_indexer(self, form, key):
+ """ consistent invalid indexer message """
+ raise TypeError("cannot do {form} indexing on {klass} with these "
+ "indexers [{key}] of {kind}".format(form=form,
+ klass=type(self),
+ key=key,
+ kind=type(key)))
def get_duplicates(self):
from collections import defaultdict
@@ -839,8 +854,8 @@ def inferred_type(self):
""" return a string of the type inferred from the values """
return lib.infer_dtype(self)
- def is_type_compatible(self, typ):
- return typ == self.inferred_type
+ def is_type_compatible(self, kind):
+ return kind == self.inferred_type
@cache_readonly
def is_all_dates(self):
@@ -2077,7 +2092,7 @@ def _wrap_joined_index(self, joined, other):
name = self.name if self.name == other.name else None
return Index(joined, name=name)
- def slice_indexer(self, start=None, end=None, step=None):
+ def slice_indexer(self, start=None, end=None, step=None, kind=None):
"""
For an ordered Index, compute the slice indexer for input labels and
step
@@ -2089,6 +2104,7 @@ def slice_indexer(self, start=None, end=None, step=None):
end : label, default None
If None, defaults to the end
step : int, default None
+ kind : string, default None
Returns
-------
@@ -2098,7 +2114,7 @@ def slice_indexer(self, start=None, end=None, step=None):
-----
This function assumes that the data is sorted, so use at your own peril
"""
- start_slice, end_slice = self.slice_locs(start, end, step=step)
+ start_slice, end_slice = self.slice_locs(start, end, step=step, kind=kind)
# return a slice
if not lib.isscalar(start_slice):
@@ -2108,7 +2124,7 @@ def slice_indexer(self, start=None, end=None, step=None):
return slice(start_slice, end_slice, step)
- def _maybe_cast_slice_bound(self, label, side):
+ def _maybe_cast_slice_bound(self, label, side, kind):
"""
This function should be overloaded in subclasses that allow non-trivial
casting on label-slice bounds, e.g. datetime-like indices allowing
@@ -2118,12 +2134,30 @@ def _maybe_cast_slice_bound(self, label, side):
----------
label : object
side : {'left', 'right'}
+ kind : string / None
+
+ Returns
+ -------
+ label : object
Notes
-----
Value of `side` parameter should be validated in caller.
"""
+
+ # We are a plain index here (sub-class override this method if they
+ # wish to have special treatment for floats/ints, e.g. Float64Index and
+ # datetimelike Indexes
+ # reject them
+ if is_float(label):
+ self._invalid_indexer('slice',label)
+
+ # we are trying to find integer bounds on a non-integer based index
+ # this is rejected (generally .loc gets you here)
+ elif is_integer(label):
+ self._invalid_indexer('slice',label)
+
return label
def _searchsorted_monotonic(self, label, side='left'):
@@ -2139,7 +2173,7 @@ def _searchsorted_monotonic(self, label, side='left'):
raise ValueError('index must be monotonic increasing or decreasing')
- def get_slice_bound(self, label, side):
+ def get_slice_bound(self, label, side, kind):
"""
Calculate slice bound that corresponds to given label.
@@ -2150,6 +2184,7 @@ def get_slice_bound(self, label, side):
----------
label : object
side : {'left', 'right'}
+ kind : string / None, the type of indexer
"""
if side not in ('left', 'right'):
@@ -2158,10 +2193,12 @@ def get_slice_bound(self, label, side):
" must be either 'left' or 'right': %s" % (side,))
original_label = label
+
# For datetime indices label may be a string that has to be converted
# to datetime boundary according to its resolution.
- label = self._maybe_cast_slice_bound(label, side)
+ label = self._maybe_cast_slice_bound(label, side, kind)
+ # we need to look up the label
try:
slc = self.get_loc(label)
except KeyError as err:
@@ -2194,7 +2231,7 @@ def get_slice_bound(self, label, side):
else:
return slc
- def slice_locs(self, start=None, end=None, step=None):
+ def slice_locs(self, start=None, end=None, step=None, kind=None):
"""
Compute slice locations for input labels.
@@ -2204,6 +2241,9 @@ def slice_locs(self, start=None, end=None, step=None):
If None, defaults to the beginning
end : label, default None
If None, defaults to the end
+ step : int, defaults None
+ If None, defaults to 1
+ kind : string, defaults None
Returns
-------
@@ -2218,13 +2258,13 @@ def slice_locs(self, start=None, end=None, step=None):
start_slice = None
if start is not None:
- start_slice = self.get_slice_bound(start, 'left')
+ start_slice = self.get_slice_bound(start, 'left', kind)
if start_slice is None:
start_slice = 0
end_slice = None
if end is not None:
- end_slice = self.get_slice_bound(end, 'right')
+ end_slice = self.get_slice_bound(end, 'right', kind)
if end_slice is None:
end_slice = len(self)
@@ -2481,6 +2521,35 @@ class NumericIndex(Index):
"""
_is_numeric_dtype = True
+ def _maybe_cast_slice_bound(self, label, side, kind):
+ """
+ This function should be overloaded in subclasses that allow non-trivial
+ casting on label-slice bounds, e.g. datetime-like indices allowing
+ strings containing formatted datetimes.
+
+ Parameters
+ ----------
+ label : object
+ side : {'left', 'right'}
+ kind : string / None
+
+ Returns
+ -------
+ label : object
+
+ Notes
+ -----
+ Value of `side` parameter should be validated in caller.
+
+ """
+
+ # we are a numeric index, so we accept
+ # integer/floats directly
+ if not (is_integer(label) or is_float(label)):
+ self._invalid_indexer('slice',label)
+
+ return label
+
class Int64Index(NumericIndex):
"""
@@ -2654,27 +2723,30 @@ def astype(self, dtype):
self.__class__)
return Index(self.values, name=self.name, dtype=dtype)
- def _convert_scalar_indexer(self, key, typ=None):
- if typ == 'iloc':
+ def _convert_scalar_indexer(self, key, kind=None):
+ if kind == 'iloc':
return super(Float64Index, self)._convert_scalar_indexer(key,
- typ=typ)
+ kind=kind)
return key
- def _convert_slice_indexer(self, key, typ=None):
- """ convert a slice indexer, by definition these are labels
- unless we are iloc """
+ def _convert_slice_indexer(self, key, kind=None):
+ """
+ convert a slice indexer, by definition these are labels
+ unless we are iloc
+
+ Parameters
+ ----------
+ key : label of the slice bound
+ kind : optional, type of the indexing operation (loc/ix/iloc/None)
+ """
# if we are not a slice, then we are done
if not isinstance(key, slice):
return key
- if typ == 'iloc':
+ if kind == 'iloc':
return super(Float64Index, self)._convert_slice_indexer(key,
- typ=typ)
-
- # allow floats here
- validator = lambda v: v is None or is_integer(v) or is_float(v)
- self._validate_slicer(key, validator)
+ kind=kind)
# translate to locations
return self.slice_indexer(key.start, key.stop, key.step)
@@ -4099,12 +4171,12 @@ def _tuple_index(self):
"""
return Index(self.values)
- def get_slice_bound(self, label, side):
+ def get_slice_bound(self, label, side, kind):
if not isinstance(label, tuple):
label = label,
return self._partial_tup_index(label, side=side)
- def slice_locs(self, start=None, end=None, step=None):
+ def slice_locs(self, start=None, end=None, step=None, kind=None):
"""
For an ordered MultiIndex, compute the slice locations for input
labels. They can be tuples representing partial levels, e.g. for a
@@ -4119,6 +4191,7 @@ def slice_locs(self, start=None, end=None, step=None):
If None, defaults to the end
step : int or None
Slice step
+ kind : string, optional, defaults None
Returns
-------
@@ -4130,7 +4203,7 @@ def slice_locs(self, start=None, end=None, step=None):
"""
# This function adds nothing to its parent implementation (the magic
# happens in get_slice_bound method), but it adds meaningful doc.
- return super(MultiIndex, self).slice_locs(start, end, step)
+ return super(MultiIndex, self).slice_locs(start, end, step, kind=kind)
def _partial_tup_index(self, tup, side='left'):
if len(tup) > self.lexsort_depth:
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 1c951f58a17d8..29fc1d1e4ba78 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -91,8 +91,8 @@ def _get_label(self, label, axis=0):
def _get_loc(self, key, axis=0):
return self.obj._ixs(key, axis=axis)
- def _slice(self, obj, axis=0, typ=None):
- return self.obj._slice(obj, axis=axis, typ=typ)
+ def _slice(self, obj, axis=0, kind=None):
+ return self.obj._slice(obj, axis=axis, kind=kind)
def _get_setitem_indexer(self, key):
if self.axis is not None:
@@ -163,12 +163,12 @@ def _convert_scalar_indexer(self, key, axis):
# if we are accessing via lowered dim, use the last dim
ax = self.obj._get_axis(min(axis, self.ndim - 1))
# a scalar
- return ax._convert_scalar_indexer(key, typ=self.name)
+ return ax._convert_scalar_indexer(key, kind=self.name)
def _convert_slice_indexer(self, key, axis):
# if we are accessing via lowered dim, use the last dim
ax = self.obj._get_axis(min(axis, self.ndim - 1))
- return ax._convert_slice_indexer(key, typ=self.name)
+ return ax._convert_slice_indexer(key, kind=self.name)
def _has_valid_setitem_indexer(self, indexer):
return True
@@ -960,7 +960,7 @@ def _reindex(keys, level=None):
keyarr = _asarray_tuplesafe(key)
# handle a mixed integer scenario
- indexer = labels._convert_list_indexer_for_mixed(keyarr, typ=self.name)
+ indexer = labels._convert_list_indexer_for_mixed(keyarr, kind=self.name)
if indexer is not None:
return self.obj.take(indexer, axis=axis)
@@ -1107,7 +1107,7 @@ def _convert_to_indexer(self, obj, axis=0, is_setter=False):
objarr = _asarray_tuplesafe(obj)
# If have integer labels, defer to label-based indexing
- indexer = labels._convert_list_indexer_for_mixed(objarr, typ=self.name)
+ indexer = labels._convert_list_indexer_for_mixed(objarr, kind=self.name)
if indexer is not None:
return indexer
@@ -1163,7 +1163,7 @@ def _get_slice_axis(self, slice_obj, axis=0):
indexer = self._convert_slice_indexer(slice_obj, axis)
if isinstance(indexer, slice):
- return self._slice(indexer, axis=axis, typ='iloc')
+ return self._slice(indexer, axis=axis, kind='iloc')
else:
return self.obj.take(indexer, axis=axis, convert=False)
@@ -1221,7 +1221,7 @@ def _get_slice_axis(self, slice_obj, axis=0):
slice_obj.step)
if isinstance(indexer, slice):
- return self._slice(indexer, axis=axis, typ='iloc')
+ return self._slice(indexer, axis=axis, kind='iloc')
else:
return self.obj.take(indexer, axis=axis, convert=False)
@@ -1243,25 +1243,7 @@ def _has_valid_type(self, key, axis):
# boolean
if isinstance(key, slice):
-
- if ax.is_floating():
-
- # allowing keys to be slicers with no fallback
- pass
-
- else:
- if key.start is not None:
- if key.start not in ax:
- raise KeyError(
- "start bound [%s] is not the [%s]" %
- (key.start, self.obj._get_axis_name(axis))
- )
- if key.stop is not None:
- if key.stop not in ax:
- raise KeyError(
- "stop bound [%s] is not in the [%s]" %
- (key.stop, self.obj._get_axis_name(axis))
- )
+ return True
elif is_bool_indexer(key):
return True
@@ -1430,7 +1412,7 @@ def _get_slice_axis(self, slice_obj, axis=0):
slice_obj = self._convert_slice_indexer(slice_obj, axis)
if isinstance(slice_obj, slice):
- return self._slice(slice_obj, axis=axis, typ='iloc')
+ return self._slice(slice_obj, axis=axis, kind='iloc')
else:
return self.obj.take(slice_obj, axis=axis, convert=False)
@@ -1590,7 +1572,7 @@ def convert_to_index_sliceable(obj, key):
"""
idx = obj.index
if isinstance(key, slice):
- return idx._convert_slice_indexer(key, typ='getitem')
+ return idx._convert_slice_indexer(key, kind='getitem')
elif isinstance(key, compat.string_types):
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 901faef484377..036aca72c8230 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -491,7 +491,7 @@ def _ixs(self, i, axis=0):
raise
except:
if isinstance(i, slice):
- indexer = self.index._convert_slice_indexer(i, typ='iloc')
+ indexer = self.index._convert_slice_indexer(i, kind='iloc')
return self._get_values(indexer)
else:
label = self.index[i]
@@ -504,8 +504,8 @@ def _ixs(self, i, axis=0):
def _is_mixed_type(self):
return False
- def _slice(self, slobj, axis=0, typ=None):
- slobj = self.index._convert_slice_indexer(slobj, typ=typ or 'getitem')
+ def _slice(self, slobj, axis=0, kind=None):
+ slobj = self.index._convert_slice_indexer(slobj, kind=kind or 'getitem')
return self._get_values(slobj)
def __getitem__(self, key):
@@ -536,7 +536,7 @@ def __getitem__(self, key):
else:
# we can try to coerce the indexer (or this will raise)
- new_key = self.index._convert_scalar_indexer(key)
+ new_key = self.index._convert_scalar_indexer(key,kind='getitem')
if type(new_key) != type(key):
return self.__getitem__(new_key)
raise
@@ -555,7 +555,7 @@ def __getitem__(self, key):
def _get_with(self, key):
# other: fancy integer or otherwise
if isinstance(key, slice):
- indexer = self.index._convert_slice_indexer(key, typ='getitem')
+ indexer = self.index._convert_slice_indexer(key, kind='getitem')
return self._get_values(indexer)
elif isinstance(key, ABCDataFrame):
raise TypeError('Indexing a Series with DataFrame is not supported, '\
@@ -693,7 +693,7 @@ def _set_with_engine(self, key, value):
def _set_with(self, key, value):
# other: fancy integer or otherwise
if isinstance(key, slice):
- indexer = self.index._convert_slice_indexer(key, typ='getitem')
+ indexer = self.index._convert_slice_indexer(key, kind='getitem')
return self._set_values(indexer, value)
else:
if isinstance(key, tuple):
diff --git a/pandas/sparse/frame.py b/pandas/sparse/frame.py
index 821720f4035a8..30b06c8a93142 100644
--- a/pandas/sparse/frame.py
+++ b/pandas/sparse/frame.py
@@ -378,7 +378,7 @@ def set_value(self, index, col, value, takeable=False):
return dense.to_sparse(kind=self._default_kind,
fill_value=self._default_fill_value)
- def _slice(self, slobj, axis=0, typ=None):
+ def _slice(self, slobj, axis=0, kind=None):
if axis == 0:
new_index = self.index[slobj]
new_columns = self.columns
diff --git a/pandas/sparse/panel.py b/pandas/sparse/panel.py
index ee9edbe36ae28..d3f3f59f264c5 100644
--- a/pandas/sparse/panel.py
+++ b/pandas/sparse/panel.py
@@ -68,10 +68,10 @@ class SparsePanel(Panel):
def __init__(self, frames=None, items=None, major_axis=None, minor_axis=None,
default_fill_value=np.nan, default_kind='block',
copy=False):
-
+
if frames is None:
frames = {}
-
+
if isinstance(frames, np.ndarray):
new_frames = {}
for item, vals in zip(items, frames):
@@ -191,7 +191,7 @@ def _ixs(self, i, axis=0):
return self.xs(key, axis=axis)
- def _slice(self, slobj, axis=0, typ=None):
+ def _slice(self, slobj, axis=0, kind=None):
"""
for compat as we don't support Block Manager here
"""
diff --git a/pandas/tests/test_index.py b/pandas/tests/test_index.py
index 75c28681ecde5..ef05209ebe54c 100644
--- a/pandas/tests/test_index.py
+++ b/pandas/tests/test_index.py
@@ -950,16 +950,30 @@ def test_slice_locs(self):
self.assertEqual(idx.slice_locs(start=3), (3, n))
self.assertEqual(idx.slice_locs(3, 8), (3, 6))
self.assertEqual(idx.slice_locs(5, 10), (3, n))
- self.assertEqual(idx.slice_locs(5.0, 10.0), (3, n))
- self.assertEqual(idx.slice_locs(4.5, 10.5), (3, 8))
self.assertEqual(idx.slice_locs(end=8), (0, 6))
self.assertEqual(idx.slice_locs(end=9), (0, 7))
+ # reversed
idx2 = idx[::-1]
self.assertEqual(idx2.slice_locs(8, 2), (2, 6))
- self.assertEqual(idx2.slice_locs(8.5, 1.5), (2, 6))
self.assertEqual(idx2.slice_locs(7, 3), (2, 5))
- self.assertEqual(idx2.slice_locs(10.5, -1), (0, n))
+
+ # float slicing
+ idx = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=float))
+ n = len(idx)
+ self.assertEqual(idx.slice_locs(5.0, 10.0), (3, n))
+ self.assertEqual(idx.slice_locs(4.5, 10.5), (3, 8))
+ idx2 = idx[::-1]
+ self.assertEqual(idx2.slice_locs(8.5, 1.5), (2, 6))
+ self.assertEqual(idx2.slice_locs(10.5, -1), (0, n))
+
+ # int slicing with floats
+ idx = Index(np.array([0, 1, 2, 5, 6, 7, 9, 10], dtype=int))
+ self.assertEqual(idx.slice_locs(5.0, 10.0), (3, n))
+ self.assertEqual(idx.slice_locs(4.5, 10.5), (3, 8))
+ idx2 = idx[::-1]
+ self.assertEqual(idx2.slice_locs(8.5, 1.5), (2, 6))
+ self.assertEqual(idx2.slice_locs(10.5, -1), (0, n))
def test_slice_locs_dup(self):
idx = Index(['a', 'a', 'b', 'c', 'd', 'd'])
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 68c504b2a35c3..bdf2b43d7e945 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -20,7 +20,7 @@
from pandas.util.testing import (assert_almost_equal, assert_series_equal,
assert_frame_equal, assert_panel_equal,
assert_attr_equal)
-from pandas import concat
+from pandas import concat, lib
from pandas.io.common import PerformanceWarning
import pandas.util.testing as tm
@@ -211,8 +211,6 @@ def _print(result, error = None):
except AssertionError:
raise
- except TypeError:
- raise AssertionError(_print('type error'))
except Exception as detail:
# if we are in fails, the ok, otherwise raise it
@@ -608,7 +606,7 @@ def test_iloc_setitem(self):
expected = Series([0,1,0],index=[4,5,6])
assert_series_equal(s, expected)
- def test_ix_loc_setitem(self):
+ def test_ix_loc_setitem_consistency(self):
# GH 5771
# loc with slice and series
@@ -656,6 +654,80 @@ def test_ix_loc_setitem(self):
df2.ix[:,2] = pd.to_datetime(df['timestamp'], unit='s')
assert_frame_equal(df2,expected)
+ def test_ix_loc_consistency(self):
+
+ # GH 8613
+ # some edge cases where ix/loc should return the same
+ # this is not an exhaustive case
+
+ def compare(result, expected):
+ if lib.isscalar(expected):
+ self.assertEqual(result, expected)
+ else:
+ self.assertTrue(expected.equals(result))
+
+ # failure cases for .loc, but these work for .ix
+ df = pd.DataFrame(np.random.randn(5,4), columns=list('ABCD'))
+ for key in [ slice(1,3), tuple([slice(0,2),slice(0,2)]), tuple([slice(0,2),df.columns[0:2]]) ]:
+
+ for index in [ tm.makeStringIndex, tm.makeUnicodeIndex,
+ tm.makeDateIndex, tm.makePeriodIndex, tm.makeTimedeltaIndex ]:
+ df.index = index(len(df.index))
+ df.ix[key]
+
+ self.assertRaises(TypeError, lambda : df.loc[key])
+
+ df = pd.DataFrame(np.random.randn(5,4), columns=list('ABCD'), index=pd.date_range('2012-01-01', periods=5))
+
+ for key in [ '2012-01-03',
+ '2012-01-31',
+ slice('2012-01-03','2012-01-03'),
+ slice('2012-01-03','2012-01-04'),
+ slice('2012-01-03','2012-01-06',2),
+ slice('2012-01-03','2012-01-31'),
+ tuple([[True,True,True,False,True]]),
+ ]:
+
+ # getitem
+
+ # if the expected raises, then compare the exceptions
+ try:
+ expected = df.ix[key]
+ except KeyError:
+ self.assertRaises(KeyError, lambda : df.loc[key])
+ continue
+
+ result = df.loc[key]
+ compare(result, expected)
+
+ # setitem
+ df1 = df.copy()
+ df2 = df.copy()
+
+ df1.ix[key] = 10
+ df2.loc[key] = 10
+ compare(df2, df1)
+
+ # edge cases
+ s = Series([1,2,3,4], index=list('abde'))
+
+ result1 = s['a':'c']
+ result2 = s.ix['a':'c']
+ result3 = s.loc['a':'c']
+ assert_series_equal(result1,result2)
+ assert_series_equal(result1,result3)
+
+ # now work rather than raising KeyError
+ s = Series(range(5),[-2,-1,1,2,3])
+
+ result1 = s.ix[-10:3]
+ result2 = s.loc[-10:3]
+ assert_series_equal(result1,result2)
+
+ result1 = s.ix[0:3]
+ result2 = s.loc[0:3]
+ assert_series_equal(result1,result2)
+
def test_loc_setitem_multiindex(self):
# GH7190
@@ -776,7 +848,11 @@ def test_loc_getitem_label(self):
def test_loc_getitem_label_out_of_range(self):
# out of range label
- self.check_result('label range', 'loc', 'f', 'ix', 'f', typs = ['ints','labels','mixed','ts','floats'], fails=KeyError)
+ self.check_result('label range', 'loc', 'f', 'ix', 'f', typs = ['ints','labels','mixed','ts'], fails=KeyError)
+ self.check_result('label range', 'loc', 'f', 'ix', 'f', typs = ['floats'], fails=TypeError)
+ self.check_result('label range', 'loc', 20, 'ix', 20, typs = ['ints','labels','mixed'], fails=KeyError)
+ self.check_result('label range', 'loc', 20, 'ix', 20, typs = ['ts'], axes=0, fails=TypeError)
+ self.check_result('label range', 'loc', 20, 'ix', 20, typs = ['floats'], axes=0, fails=TypeError)
def test_loc_getitem_label_list(self):
@@ -814,9 +890,6 @@ def test_loc_getitem_bool(self):
def test_loc_getitem_int_slice(self):
- # int slices in int
- self.check_result('int slice1', 'loc', slice(2,4), 'ix', { 0 : [2,4], 1: [3,6], 2: [4,8] }, typs = ['ints'], fails=KeyError)
-
# ok
self.check_result('int slice2', 'loc', slice(2,4), 'ix', [2,4], typs = ['ints'], axes = 0)
self.check_result('int slice2', 'loc', slice(3,6), 'ix', [3,6], typs = ['ints'], axes = 1)
@@ -920,7 +993,7 @@ def f():
def test_loc_getitem_label_slice(self):
# label slices (with ints)
- self.check_result('lab slice', 'loc', slice(1,3), 'ix', slice(1,3), typs = ['labels','mixed','ts','floats','empty'], fails=KeyError)
+ self.check_result('lab slice', 'loc', slice(1,3), 'ix', slice(1,3), typs = ['labels','mixed','empty','ts','floats'], fails=TypeError)
# real label slices
self.check_result('lab slice', 'loc', slice('a','c'), 'ix', slice('a','c'), typs = ['labels'], axes=0)
@@ -928,23 +1001,18 @@ def test_loc_getitem_label_slice(self):
self.check_result('lab slice', 'loc', slice('W','Z'), 'ix', slice('W','Z'), typs = ['labels'], axes=2)
self.check_result('ts slice', 'loc', slice('20130102','20130104'), 'ix', slice('20130102','20130104'), typs = ['ts'], axes=0)
- self.check_result('ts slice', 'loc', slice('20130102','20130104'), 'ix', slice('20130102','20130104'), typs = ['ts'], axes=1, fails=KeyError)
- self.check_result('ts slice', 'loc', slice('20130102','20130104'), 'ix', slice('20130102','20130104'), typs = ['ts'], axes=2, fails=KeyError)
+ self.check_result('ts slice', 'loc', slice('20130102','20130104'), 'ix', slice('20130102','20130104'), typs = ['ts'], axes=1, fails=TypeError)
+ self.check_result('ts slice', 'loc', slice('20130102','20130104'), 'ix', slice('20130102','20130104'), typs = ['ts'], axes=2, fails=TypeError)
- self.check_result('mixed slice', 'loc', slice(2,8), 'ix', slice(2,8), typs = ['mixed'], axes=0, fails=KeyError)
+ self.check_result('mixed slice', 'loc', slice(2,8), 'ix', slice(2,8), typs = ['mixed'], axes=0, fails=TypeError)
self.check_result('mixed slice', 'loc', slice(2,8), 'ix', slice(2,8), typs = ['mixed'], axes=1, fails=KeyError)
self.check_result('mixed slice', 'loc', slice(2,8), 'ix', slice(2,8), typs = ['mixed'], axes=2, fails=KeyError)
- self.check_result('mixed slice', 'loc', slice(2,4,2), 'ix', slice(2,4,2), typs = ['mixed'], axes=0)
+ self.check_result('mixed slice', 'loc', slice(2,4,2), 'ix', slice(2,4,2), typs = ['mixed'], axes=0, fails=TypeError)
def test_loc_general(self):
- # GH 2922 (these are fails)
- df = DataFrame(np.random.rand(4,4),columns=['A','B','C','D'])
- self.assertRaises(KeyError, df.loc.__getitem__, tuple([slice(0,2),slice(0,2)]))
-
df = DataFrame(np.random.rand(4,4),columns=['A','B','C','D'], index=['A','B','C','D'])
- self.assertRaises(KeyError, df.loc.__getitem__, tuple([slice(0,2),df.columns[0:2]]))
# want this to work
result = df.loc[:,"A":"B"].iloc[0:2,:]
@@ -3239,10 +3307,10 @@ def test_partial_set_invalid(self):
# don't allow not string inserts
def f():
df.loc[100.0, :] = df.ix[0]
- self.assertRaises(ValueError, f)
+ self.assertRaises(TypeError, f)
def f():
df.loc[100,:] = df.ix[0]
- self.assertRaises(ValueError, f)
+ self.assertRaises(TypeError, f)
def f():
df.ix[100.0, :] = df.ix[0]
@@ -3887,8 +3955,8 @@ def check_invalid(index, loc=None, iloc=None, ix=None, getitem=None):
check_invalid(index())
check_invalid(Index(np.arange(5) * 2.5),loc=KeyError, ix=KeyError, getitem=KeyError)
- def check_getitem(index):
-
+ def check_index(index, error):
+ index = index()
s = Series(np.arange(len(index)),index=index)
# positional selection
@@ -3898,22 +3966,26 @@ def check_getitem(index):
result4 = s.iloc[5.0]
# by value
- self.assertRaises(KeyError, lambda : s.loc[5])
- self.assertRaises(KeyError, lambda : s.loc[5.0])
+ self.assertRaises(error, lambda : s.loc[5])
+ self.assertRaises(error, lambda : s.loc[5.0])
# this is fallback, so it works
result5 = s.ix[5]
result6 = s.ix[5.0]
+
self.assertEqual(result1, result2)
self.assertEqual(result1, result3)
self.assertEqual(result1, result4)
self.assertEqual(result1, result5)
self.assertEqual(result1, result6)
- # all index types except float/int
- for index in [ tm.makeStringIndex, tm.makeUnicodeIndex,
- tm.makeDateIndex, tm.makePeriodIndex ]:
- check_getitem(index())
+ # string-like
+ for index in [ tm.makeStringIndex, tm.makeUnicodeIndex ]:
+ check_index(index, KeyError)
+
+ # datetimelike
+ for index in [ tm.makeDateIndex, tm.makeTimedeltaIndex, tm.makePeriodIndex ]:
+ check_index(index, TypeError)
# exact indexing when found on IntIndex
s = Series(np.arange(10),dtype='int64')
@@ -3932,6 +4004,12 @@ def check_getitem(index):
def test_slice_indexer(self):
+ def check_iloc_compat(s):
+ # invalid type for iloc (but works with a warning)
+ self.assert_produces_warning(FutureWarning, lambda : s.iloc[6.0:8])
+ self.assert_produces_warning(FutureWarning, lambda : s.iloc[6.0:8.0])
+ self.assert_produces_warning(FutureWarning, lambda : s.iloc[6:8.0])
+
def check_slicing_positional(index):
s = Series(np.arange(len(index))+10,index=index)
@@ -3943,8 +4021,8 @@ def check_slicing_positional(index):
assert_series_equal(result1, result2)
assert_series_equal(result1, result3)
- # not in the index
- self.assertRaises(KeyError, lambda : s.loc[2:5])
+ # loc will fail
+ self.assertRaises(TypeError, lambda : s.loc[2:5])
# make all float slicing fail
self.assertRaises(TypeError, lambda : s[2.0:5])
@@ -3955,91 +4033,83 @@ def check_slicing_positional(index):
self.assertRaises(TypeError, lambda : s.ix[2.0:5.0])
self.assertRaises(TypeError, lambda : s.ix[2:5.0])
- self.assertRaises(KeyError, lambda : s.loc[2.0:5])
- self.assertRaises(KeyError, lambda : s.loc[2.0:5.0])
- self.assertRaises(KeyError, lambda : s.loc[2:5.0])
+ self.assertRaises(TypeError, lambda : s.loc[2.0:5])
+ self.assertRaises(TypeError, lambda : s.loc[2.0:5.0])
+ self.assertRaises(TypeError, lambda : s.loc[2:5.0])
- # these work for now
- #self.assertRaises(TypeError, lambda : s.iloc[2.0:5])
- #self.assertRaises(TypeError, lambda : s.iloc[2.0:5.0])
- #self.assertRaises(TypeError, lambda : s.iloc[2:5.0])
+ check_iloc_compat(s)
# all index types except int, float
for index in [ tm.makeStringIndex, tm.makeUnicodeIndex,
- tm.makeDateIndex, tm.makePeriodIndex ]:
+ tm.makeDateIndex, tm.makeTimedeltaIndex, tm.makePeriodIndex ]:
check_slicing_positional(index())
- # int
+ ############
+ # IntIndex #
+ ############
index = tm.makeIntIndex()
- s = Series(np.arange(len(index))+10,index)
+ s = Series(np.arange(len(index))+10,index+5)
# this is positional
result1 = s[2:5]
result4 = s.iloc[2:5]
assert_series_equal(result1, result4)
- # these are all value based
+ # these are all label based
result2 = s.ix[2:5]
result3 = s.loc[2:5]
- result4 = s.loc[2.0:5]
- result5 = s.loc[2.0:5.0]
- result6 = s.loc[2:5.0]
assert_series_equal(result2, result3)
- assert_series_equal(result2, result4)
- assert_series_equal(result2, result5)
- assert_series_equal(result2, result6)
- # make all float slicing fail
- self.assertRaises(TypeError, lambda : s[2.0:5])
- self.assertRaises(TypeError, lambda : s[2.0:5.0])
- self.assertRaises(TypeError, lambda : s[2:5.0])
+ # float slicers on an int index
+ expected = Series([11,12,13],index=[6,7,8])
+ for method in [lambda x: x.loc, lambda x: x.ix]:
+ result = method(s)[6.0:8.5]
+ assert_series_equal(result, expected)
+
+ result = method(s)[5.5:8.5]
+ assert_series_equal(result, expected)
+
+ result = method(s)[5.5:8.0]
+ assert_series_equal(result, expected)
- self.assertRaises(TypeError, lambda : s.ix[2.0:5])
- self.assertRaises(TypeError, lambda : s.ix[2.0:5.0])
- self.assertRaises(TypeError, lambda : s.ix[2:5.0])
+ # make all float slicing fail for [] with an int index
+ self.assertRaises(TypeError, lambda : s[6.0:8])
+ self.assertRaises(TypeError, lambda : s[6.0:8.0])
+ self.assertRaises(TypeError, lambda : s[6:8.0])
- # these work for now
- #self.assertRaises(TypeError, lambda : s.iloc[2.0:5])
- #self.assertRaises(TypeError, lambda : s.iloc[2.0:5.0])
- #self.assertRaises(TypeError, lambda : s.iloc[2:5.0])
+ check_iloc_compat(s)
- # float
- index = tm.makeFloatIndex()
- s = Series(np.arange(len(index))+10,index=index)
+ ##############
+ # FloatIndex #
+ ##############
+ s.index = s.index.astype('float64')
# these are all value based
- result1 = s[2:5]
- result2 = s.ix[2:5]
- result3 = s.loc[2:5]
+ result1 = s[6:8]
+ result2 = s.ix[6:8]
+ result3 = s.loc[6:8]
assert_series_equal(result1, result2)
assert_series_equal(result1, result3)
- # these are all valid
- result1a = s[2.0:5]
- result2a = s[2.0:5.0]
- result3a = s[2:5.0]
- assert_series_equal(result1a, result2a)
- assert_series_equal(result1a, result3a)
-
- result1b = s.ix[2.0:5]
- result2b = s.ix[2.0:5.0]
- result3b = s.ix[2:5.0]
- assert_series_equal(result1b, result2b)
- assert_series_equal(result1b, result3b)
-
- result1c = s.loc[2.0:5]
- result2c = s.loc[2.0:5.0]
- result3c = s.loc[2:5.0]
- assert_series_equal(result1c, result2c)
- assert_series_equal(result1c, result3c)
-
- assert_series_equal(result1a, result1b)
- assert_series_equal(result1a, result1c)
-
- # these work for now
- #self.assertRaises(TypeError, lambda : s.iloc[2.0:5])
- #self.assertRaises(TypeError, lambda : s.iloc[2.0:5.0])
- #self.assertRaises(TypeError, lambda : s.iloc[2:5.0])
+ # these are valid for all methods
+ # these are treated like labels (e.g. the rhs IS included)
+ def compare(slicers, expected):
+ for method in [lambda x: x, lambda x: x.loc, lambda x: x.ix ]:
+ for slices in slicers:
+
+ result = method(s)[slices]
+ assert_series_equal(result, expected)
+
+ compare([slice(6.0,8),slice(6.0,8.0),slice(6,8.0)],
+ s[(s.index>=6.0)&(s.index<=8)])
+ compare([slice(6.5,8),slice(6.5,8.5)],
+ s[(s.index>=6.5)&(s.index<=8.5)])
+ compare([slice(6,8.5)],
+ s[(s.index>=6.0)&(s.index<=8.5)])
+ compare([slice(6.5,6.5)],
+ s[(s.index>=6.5)&(s.index<=6.5)])
+
+ check_iloc_compat(s)
def test_set_ix_out_of_bounds_axis_0(self):
df = pd.DataFrame(randn(2, 5), index=["row%s" % i for i in range(2)], columns=["col%s" % i for i in range(5)])
@@ -4097,9 +4167,7 @@ def test_deprecate_float_indexers(self):
import warnings
warnings.filterwarnings(action='error', category=FutureWarning)
- for index in [ tm.makeStringIndex, tm.makeUnicodeIndex,
- tm.makeDateIndex, tm.makePeriodIndex ]:
-
+ def check_index(index):
i = index(5)
for s in [ Series(np.arange(len(i)),index=i), DataFrame(np.random.randn(len(i),len(i)),index=i,columns=i) ]:
@@ -4114,8 +4182,11 @@ def f():
# fallsback to position selection ,series only
s = Series(np.arange(len(i)),index=i)
s[3]
- self.assertRaises(FutureWarning, lambda :
- s[3.0])
+ self.assertRaises(FutureWarning, lambda : s[3.0])
+
+ for index in [ tm.makeStringIndex, tm.makeUnicodeIndex,
+ tm.makeDateIndex, tm.makeTimedeltaIndex, tm.makePeriodIndex ]:
+ check_index(index)
# ints
i = index(5)
diff --git a/pandas/tseries/base.py b/pandas/tseries/base.py
index a1904d38ab530..048a9ff4b93a6 100644
--- a/pandas/tseries/base.py
+++ b/pandas/tseries/base.py
@@ -8,6 +8,7 @@
from pandas import compat
import numpy as np
from pandas.core import common as com
+from pandas.core.common import is_integer, is_float
import pandas.tslib as tslib
import pandas.lib as lib
from pandas.core.index import Index
@@ -297,6 +298,21 @@ def resolution(self):
from pandas.tseries.frequencies import get_reso_string
return get_reso_string(self._resolution)
+ def _convert_scalar_indexer(self, key, kind=None):
+ """
+ we don't allow integer or float indexing on datetime-like when using loc
+
+ Parameters
+ ----------
+ key : label of the slice bound
+ kind : optional, type of the indexing operation (loc/ix/iloc/None)
+ """
+
+ if kind in ['loc'] and lib.isscalar(key) and (is_integer(key) or is_float(key)):
+ self._invalid_indexer('index',key)
+
+ return super(DatetimeIndexOpsMixin, self)._convert_scalar_indexer(key, kind=kind)
+
def _add_datelike(self, other):
raise NotImplementedError
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index 60281b6b875b9..24d12078fd7f0 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -10,7 +10,7 @@
from pandas.core.common import (_NS_DTYPE, _INT64_DTYPE,
_values_from_object, _maybe_box,
- ABCSeries)
+ ABCSeries, is_integer, is_float)
from pandas.core.index import Index, Int64Index, Float64Index
import pandas.compat as compat
from pandas.compat import u
@@ -215,9 +215,9 @@ def __new__(cls, data=None,
freq = None
if periods is not None:
- if com.is_float(periods):
+ if is_float(periods):
periods = int(periods)
- elif not com.is_integer(periods):
+ elif not is_integer(periods):
raise ValueError('Periods must be a number, got %s' %
str(periods))
@@ -1262,7 +1262,7 @@ def get_loc(self, key, method=None):
except (KeyError, ValueError):
raise KeyError(key)
- def _maybe_cast_slice_bound(self, label, side):
+ def _maybe_cast_slice_bound(self, label, side, kind):
"""
If label is a string, cast it to datetime according to resolution.
@@ -1270,16 +1270,19 @@ def _maybe_cast_slice_bound(self, label, side):
----------
label : object
side : {'left', 'right'}
+ kind : string / None
+
+ Returns
+ -------
+ label : object
Notes
-----
Value of `side` parameter should be validated in caller.
"""
- if isinstance(label, float):
- raise TypeError('Cannot index datetime64 with float keys')
- if isinstance(label, time):
- raise KeyError('Cannot index datetime64 with time keys')
+ if is_float(label) or isinstance(label, time) or is_integer(label):
+ self._invalid_indexer('slice',label)
if isinstance(label, compat.string_types):
freq = getattr(self, 'freqstr',
@@ -1298,7 +1301,7 @@ def _get_string_slice(self, key, use_lhs=True, use_rhs=True):
use_rhs=use_rhs)
return loc
- def slice_indexer(self, start=None, end=None, step=None):
+ def slice_indexer(self, start=None, end=None, step=None, kind=None):
"""
Return indexer for specified label slice.
Index.slice_indexer, customized to handle time slicing.
@@ -1333,11 +1336,11 @@ def slice_indexer(self, start=None, end=None, step=None):
(end is None or isinstance(end, compat.string_types))):
mask = True
if start is not None:
- start_casted = self._maybe_cast_slice_bound(start, 'left')
+ start_casted = self._maybe_cast_slice_bound(start, 'left', kind)
mask = start_casted <= self
if end is not None:
- end_casted = self._maybe_cast_slice_bound(end, 'right')
+ end_casted = self._maybe_cast_slice_bound(end, 'right', kind)
mask = (self <= end_casted) & mask
indexer = mask.nonzero()[0][::step]
@@ -1556,7 +1559,7 @@ def delete(self, loc):
new_dates = np.delete(self.asi8, loc)
freq = None
- if lib.is_integer(loc):
+ if is_integer(loc):
if loc in (0, -len(self), -1, len(self) - 1):
freq = self.freq
else:
diff --git a/pandas/tseries/period.py b/pandas/tseries/period.py
index 074ed720991ce..1a2381441ab8d 100644
--- a/pandas/tseries/period.py
+++ b/pandas/tseries/period.py
@@ -22,7 +22,8 @@
import pandas.core.common as com
from pandas.core.common import (isnull, _INT64_DTYPE, _maybe_box,
- _values_from_object, ABCSeries)
+ _values_from_object, ABCSeries,
+ is_integer, is_float)
from pandas import compat
from pandas.lib import Timestamp, Timedelta
import pandas.lib as lib
@@ -166,9 +167,9 @@ def __new__(cls, data=None, ordinal=None, freq=None, start=None, end=None,
freq = frequencies.get_standard_freq(freq)
if periods is not None:
- if com.is_float(periods):
+ if is_float(periods):
periods = int(periods)
- elif not com.is_integer(periods):
+ elif not is_integer(periods):
raise ValueError('Periods must be a number, got %s' %
str(periods))
@@ -533,7 +534,7 @@ def get_loc(self, key, method=None):
try:
return self._engine.get_loc(key)
except KeyError:
- if com.is_integer(key):
+ if is_integer(key):
raise
try:
@@ -548,7 +549,7 @@ def get_loc(self, key, method=None):
except KeyError:
raise KeyError(key)
- def _maybe_cast_slice_bound(self, label, side):
+ def _maybe_cast_slice_bound(self, label, side, kind):
"""
If label is a string or a datetime, cast it to Period.ordinal according to
resolution.
@@ -557,6 +558,7 @@ def _maybe_cast_slice_bound(self, label, side):
----------
label : object
side : {'left', 'right'}
+ kind : string / None
Returns
-------
@@ -576,6 +578,8 @@ def _maybe_cast_slice_bound(self, label, side):
return bounds[0 if side == 'left' else 1]
except Exception:
raise KeyError(label)
+ elif is_integer(label) or is_float(label):
+ self._invalid_indexer('slice',label)
return label
diff --git a/pandas/tseries/tdi.py b/pandas/tseries/tdi.py
index 897a28e8f5ea9..e01ff54feab57 100644
--- a/pandas/tseries/tdi.py
+++ b/pandas/tseries/tdi.py
@@ -7,7 +7,7 @@
from pandas.core.common import (ABCSeries, _TD_DTYPE, _INT64_DTYPE,
is_timedelta64_dtype, _maybe_box,
- _values_from_object, isnull)
+ _values_from_object, isnull, is_integer, is_float)
from pandas.core.index import Index, Int64Index
import pandas.compat as compat
from pandas.compat import u
@@ -156,9 +156,9 @@ def __new__(cls, data=None, unit=None,
freq = None
if periods is not None:
- if com.is_float(periods):
+ if is_float(periods):
periods = int(periods)
- elif not com.is_integer(periods):
+ elif not is_integer(periods):
raise ValueError('Periods must be a number, got %s' %
str(periods))
@@ -675,7 +675,7 @@ def get_loc(self, key, method=None):
except (KeyError, ValueError):
raise KeyError(key)
- def _maybe_cast_slice_bound(self, label, side):
+ def _maybe_cast_slice_bound(self, label, side, kind):
"""
If label is a string, cast it to timedelta according to resolution.
@@ -684,10 +684,11 @@ def _maybe_cast_slice_bound(self, label, side):
----------
label : object
side : {'left', 'right'}
+ kind : string / None
Returns
-------
- bound : Timedelta or object
+ label : object
"""
if isinstance(label, compat.string_types):
@@ -698,12 +699,16 @@ def _maybe_cast_slice_bound(self, label, side):
else:
return (lbound + _resolution_map[parsed.resolution]() -
Timedelta(1, 'ns'))
+ elif is_integer(label) or is_float(label):
+ self._invalid_indexer('slice',label)
+
return label
def _get_string_slice(self, key, use_lhs=True, use_rhs=True):
freq = getattr(self, 'freqstr',
getattr(self, 'inferred_freq', None))
-
+ if is_integer(key) or is_float(key):
+ self._invalid_indexer('slice',key)
loc = self._partial_td_slice(key, freq, use_lhs=use_lhs,
use_rhs=use_rhs)
return loc
@@ -866,7 +871,7 @@ def delete(self, loc):
new_tds = np.delete(self.asi8, loc)
freq = 'infer'
- if lib.is_integer(loc):
+ if is_integer(loc):
if loc in (0, -len(self), -1, len(self) - 1):
freq = self.freq
else:
| closes #8613
```
In [1]: df = DataFrame(np.random.randn(5,4), columns=list('ABCD'), index=date_range('20130101',periods=5))
In [2]: df
Out[2]:
A B C D
2013-01-01 -1.380065 1.221596 0.279703 -0.119258
2013-01-02 1.684202 -0.202251 -0.961145 -1.595015
2013-01-03 -0.623634 -2.377577 -3.024554 -0.298809
2013-01-04 -1.251699 0.456356 1.257002 1.465878
2013-01-05 0.687818 -2.125079 1.454911 1.914207
In [5]: s = Series(range(5),[-2,-1,1,2,3])
In [6]: s
Out[6]:
-2 0
-1 1
1 2
2 3
3 4
dtype: int64
In [7]: df.loc['2013-01-02':'2013-01-10']
Out[7]:
A B C D
2013-01-02 1.684202 -0.202251 -0.961145 -1.595015
2013-01-03 -0.623634 -2.377577 -3.024554 -0.298809
2013-01-04 -1.251699 0.456356 1.257002 1.465878
2013-01-05 0.687818 -2.125079 1.454911 1.914207
In [9]: s.loc[-10:3]
Out[9]:
-2 0
-1 1
1 2
2 3
3 4
dtype: int64
```
```
# this used to be a KeyError
In [15]: df.loc[2:3]
TypeError: Cannot index datetime64 with <type 'int'> keys
```
Slicing with float indexers; now works for ix (loc worked before)
```
In [3]: s.loc[-1.0:2]
Out[3]:
-1 1
1 2
2 3
dtype: int64
In [4]: s.ix[-1.0:2]
Out[4]:
-1 1
1 2
2 3
dtype: int64
# [] raises
In [5]: s[-1.0:2]
TypeError: cannot do slice start value indexing on <class 'pandas.core.index.Int64Index'> with these indexers [-1.0] of <type 'float'>
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/9566 | 2015-02-28T21:01:15Z | 2015-03-04T20:46:25Z | 2015-03-04T20:46:25Z | 2015-03-13T17:47:35Z |
BUG: Fix read_csv on S3 files for python 3 | diff --git a/ci/requirements-2.7.txt b/ci/requirements-2.7.txt
index f3df26e7a0c24..0d515f300f5a7 100644
--- a/ci/requirements-2.7.txt
+++ b/ci/requirements-2.7.txt
@@ -13,7 +13,7 @@ lxml=3.2.1
scipy
xlsxwriter=0.4.6
statsmodels
-boto=2.26.1
+boto=2.36.0
bottleneck=0.8.0
psycopg2=2.5.2
patsy
diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt
index ead3c79430bf9..5b3d67957730e 100644
--- a/doc/source/whatsnew/v0.16.0.txt
+++ b/doc/source/whatsnew/v0.16.0.txt
@@ -344,3 +344,7 @@ Bug Fixes
- Bug in groupby MultiIndex with missing pair (:issue:`9049`, :issue:`9344`)
- Fixed bug in ``Series.groupby`` where grouping on ``MultiIndex`` levels would ignore the sort argument (:issue:`9444`)
- Fix bug in ``DataFrame.Groupby`` where sort=False is ignored in case of Categorical columns. (:issue:`8868`)
+
+
+
+- Fixed bug with reading CSV files from Amazon S3 on python 3 raising a TypeError (:issue:`9452`)
diff --git a/pandas/io/common.py b/pandas/io/common.py
index 737a55a6752c1..65cfdff1df14b 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -154,7 +154,8 @@ def get_filepath_or_buffer(filepath_or_buffer, encoding=None):
b = conn.get_bucket(parsed_url.netloc)
k = boto.s3.key.Key(b)
k.key = parsed_url.path
- filepath_or_buffer = BytesIO(k.get_contents_as_string())
+ filepath_or_buffer = BytesIO(k.get_contents_as_string(
+ encoding=encoding))
return filepath_or_buffer, None
diff --git a/pandas/io/tests/test_parsers.py b/pandas/io/tests/test_parsers.py
index bf68460364ef4..35530a7f5e07f 100644
--- a/pandas/io/tests/test_parsers.py
+++ b/pandas/io/tests/test_parsers.py
@@ -3802,9 +3802,6 @@ def setUp(self):
except ImportError:
raise nose.SkipTest("boto not installed")
- if compat.PY3:
- raise nose.SkipTest("boto incompatible with Python 3")
-
@tm.network
def test_parse_public_s3_bucket(self):
import nose.tools as nt
| Closes https://github.com/pydata/pandas/issues/9452
Needed to pass along encoding parameter.
No tests... Kind of hard since it's only s3 only.
| https://api.github.com/repos/pandas-dev/pandas/pulls/9561 | 2015-02-27T02:29:26Z | 2015-03-06T03:20:52Z | 2015-03-06T03:20:52Z | 2017-04-05T02:06:14Z |
Moved caching in AbstractHolidayCalendar to the instance level | diff --git a/doc/source/whatsnew/v0.16.1.txt b/doc/source/whatsnew/v0.16.1.txt
index 352f079f38e96..2f18592f886e0 100644
--- a/doc/source/whatsnew/v0.16.1.txt
+++ b/doc/source/whatsnew/v0.16.1.txt
@@ -154,3 +154,4 @@ Bug Fixes
- Bug where dividing a dataframe containing values of type ``Decimal`` by another ``Decimal`` would raise. (:issue:`9787`)
- Bug where using DataFrames asfreq would remove the name of the index. (:issue:`9885`)
+- Changed caching in ``AbstractHolidayCalendar`` to be at the instance level rather than at the class level as the latter can result in unexpected behaviour. (:issue:`9552`)
diff --git a/pandas/tseries/holiday.py b/pandas/tseries/holiday.py
index c31e25115c6a4..799be98a329fa 100644
--- a/pandas/tseries/holiday.py
+++ b/pandas/tseries/holiday.py
@@ -279,7 +279,7 @@ class AbstractHolidayCalendar(object):
rules = []
start_date = Timestamp(datetime(1970, 1, 1))
end_date = Timestamp(datetime(2030, 12, 31))
- _holiday_cache = None
+ _cache = None
def __init__(self, name=None, rules=None):
"""
@@ -351,14 +351,6 @@ def holidays(self, start=None, end=None, return_name=False):
else:
return holidays.index
- @property
- def _cache(self):
- return self.__class__._holiday_cache
-
- @_cache.setter
- def _cache(self, values):
- self.__class__._holiday_cache = values
-
@staticmethod
def merge_class(base, other):
"""
diff --git a/pandas/tseries/tests/test_holiday.py b/pandas/tseries/tests/test_holiday.py
index 0880e84f1fcde..7d233ba78e7b6 100644
--- a/pandas/tseries/tests/test_holiday.py
+++ b/pandas/tseries/tests/test_holiday.py
@@ -1,6 +1,7 @@
from datetime import datetime
import pandas.util.testing as tm
+from pandas import DatetimeIndex
from pandas.tseries.holiday import (
USFederalHolidayCalendar, USMemorialDay, USThanksgivingDay,
nearest_workday, next_monday_or_tuesday, next_monday,
@@ -50,6 +51,29 @@ def test_calendar(self):
self.assertEqual(list(holidays_2.to_pydatetime()),
self.holiday_list)
+ def test_calendar_caching(self):
+ # Test for issue #9552
+
+ class TestCalendar(AbstractHolidayCalendar):
+ def __init__(self, name=None, rules=None):
+ super(TestCalendar, self).__init__(
+ name=name,
+ rules=rules
+ )
+
+ jan1 = TestCalendar(rules=[Holiday('jan1', year=2015, month=1, day=1)])
+ jan2 = TestCalendar(rules=[Holiday('jan2', year=2015, month=1, day=2)])
+
+ tm.assert_index_equal(
+ jan1.holidays(),
+ DatetimeIndex(['01-Jan-2015'])
+ )
+ tm.assert_index_equal(
+ jan2.holidays(),
+ DatetimeIndex(['02-Jan-2015'])
+ )
+
+
class TestHoliday(tm.TestCase):
def setUp(self):
| Closes #9552
| https://api.github.com/repos/pandas-dev/pandas/pulls/9555 | 2015-02-26T09:11:20Z | 2015-04-14T16:40:34Z | 2015-04-14T16:40:34Z | 2015-04-14T17:19:27Z |
Squashed version of #9515. | diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt
index 0468c220bcb98..b0e2147c20674 100644
--- a/doc/source/whatsnew/v0.16.0.txt
+++ b/doc/source/whatsnew/v0.16.0.txt
@@ -293,7 +293,7 @@ Bug Fixes
- Bug in ``DataFrame.where`` and ``Series.where`` coerce numerics to string incorrectly (:issue:`9280`)
- Bug in ``DataFrame.where`` and ``Series.where`` raise ``ValueError`` when string list-like is passed. (:issue:`9280`)
- Accessing ``Series.str`` methods on with non-string values now raises ``TypeError`` instead of producing incorrect results (:issue:`9184`)
-
+- Bug in ``DatetimeIndex.__contains__`` when index has duplicates and is not monotonic increasing (:issue:`9512`)
- Fixed division by zero error for ``Series.kurt()`` when all values are equal (:issue:`9197`)
diff --git a/pandas/tseries/base.py b/pandas/tseries/base.py
index 266e69cf3484b..a1904d38ab530 100644
--- a/pandas/tseries/base.py
+++ b/pandas/tseries/base.py
@@ -65,7 +65,7 @@ def _format_with_header(self, header, **kwargs):
def __contains__(self, key):
try:
res = self.get_loc(key)
- return np.isscalar(res) or type(res) == slice
+ return np.isscalar(res) or type(res) == slice or np.any(res)
except (KeyError, TypeError):
return False
diff --git a/pandas/tseries/tests/test_base.py b/pandas/tseries/tests/test_base.py
index b63f1fb0a031a..3c9a94286509a 100644
--- a/pandas/tseries/tests/test_base.py
+++ b/pandas/tseries/tests/test_base.py
@@ -292,6 +292,12 @@ def test_value_counts_unique(self):
tm.assert_index_equal(idx.unique(), exp_idx)
+ def test_nonunique_contains(self):
+ # GH 9512
+ for idx in map(DatetimeIndex, ([0, 1, 0], [0, 0, -1], [0, -1, -1],
+ ['2015', '2015', '2016'], ['2015', '2015', '2014'])):
+ tm.assertIn(idx[0], idx)
+
class TestTimedeltaIndexOps(Ops):
@@ -684,6 +690,14 @@ def test_value_counts_unique(self):
tm.assert_index_equal(idx.unique(), exp_idx)
+ def test_nonunique_contains(self):
+ # GH 9512
+ for idx in map(TimedeltaIndex, ([0, 1, 0], [0, 0, -1], [0, -1, -1],
+ ['00:01:00', '00:01:00', '00:02:00'],
+ ['00:01:00', '00:01:00', '00:00:01'])):
+ tm.assertIn(idx[0], idx)
+
+
class TestPeriodIndexOps(Ops):
def setUp(self):
| Fixes #9512
Closes #9515
| https://api.github.com/repos/pandas-dev/pandas/pulls/9525 | 2015-02-19T20:58:07Z | 2015-02-20T00:04:45Z | 2015-02-20T00:04:45Z | 2015-02-20T00:04:47Z |
BUG: Bug in .loc partial setting with a np.datetime64 (GH9516) | diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt
index 0468c220bcb98..52d1b7b537d5a 100644
--- a/doc/source/whatsnew/v0.16.0.txt
+++ b/doc/source/whatsnew/v0.16.0.txt
@@ -227,7 +227,7 @@ Bug Fixes
column with timezone info) to the according sqlalchemy type (:issue:`9085`).
- Fixed bug in ``to_sql`` ``dtype`` argument not accepting an instantiated
SQLAlchemy type (:issue:`9083`).
-
+- Bug in ``.loc`` partial setting with a ``np.datetime64`` (:issue:`9516`)
- Items in ``Categorical.unique()`` (and ``s.unique()`` if ``s`` is of dtype ``category``) now appear in the order in which they are originally found, not in sorted order (:issue:`9331`). This is now consistent with the behavior for other dtypes in pandas.
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 426fce0797ad2..1c951f58a17d8 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -246,6 +246,7 @@ def _setitem_with_indexer(self, indexer, value):
new_indexer = convert_from_missing_indexer_tuple(
indexer, self.obj.axes)
self._setitem_with_indexer(new_indexer, value)
+
return self.obj
# reindex the axis
diff --git a/pandas/tests/test_indexing.py b/pandas/tests/test_indexing.py
index 424e5009f99c0..68c504b2a35c3 100644
--- a/pandas/tests/test_indexing.py
+++ b/pandas/tests/test_indexing.py
@@ -3171,6 +3171,22 @@ def test_partial_setting_with_datetimelike_dtype(self):
df.loc[mask, 'C'] = df.loc[mask].index
assert_frame_equal(df, expected)
+ def test_loc_setitem_datetime(self):
+
+ # GH 9516
+ dt1 = Timestamp('20130101 09:00:00')
+ dt2 = Timestamp('20130101 10:00:00')
+
+ for conv in [lambda x: x, lambda x: x.to_datetime64(),
+ lambda x: x.to_pydatetime(), lambda x: np.datetime64(x)]:
+
+ df = pd.DataFrame()
+ df.loc[conv(dt1),'one'] = 100
+ df.loc[conv(dt2),'one'] = 200
+
+ expected = DataFrame({'one' : [100.0,200.0]},index=[dt1,dt2])
+ assert_frame_equal(df, expected)
+
def test_series_partial_set(self):
# partial set with new index
# Regression from GH4825
diff --git a/pandas/tseries/index.py b/pandas/tseries/index.py
index 2205c6c4f4a64..da1f1dce435b8 100644
--- a/pandas/tseries/index.py
+++ b/pandas/tseries/index.py
@@ -1509,7 +1509,7 @@ def insert(self, loc, item):
"""
freq = None
- if isinstance(item, datetime):
+ if isinstance(item, (datetime, np.datetime64)):
zone = tslib.get_timezone(self.tz)
izone = tslib.get_timezone(getattr(item, 'tzinfo', None))
if zone != izone:
| closes #9516
| https://api.github.com/repos/pandas-dev/pandas/pulls/9522 | 2015-02-19T12:24:15Z | 2015-02-19T13:19:45Z | 2015-02-19T13:19:45Z | 2015-02-19T13:19:46Z |
BUG: multiple level unstack with nulls | diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt
index 0468c220bcb98..fc30e24588d15 100644
--- a/doc/source/whatsnew/v0.16.0.txt
+++ b/doc/source/whatsnew/v0.16.0.txt
@@ -235,7 +235,7 @@ Bug Fixes
- Fixed bug on bug endian platforms which produced incorrect results in ``StataReader`` (:issue:`8688`).
- Bug in ``MultiIndex.has_duplicates`` when having many levels causes an indexer overflow (:issue:`9075`, :issue:`5873`)
-- Bug in ``pivot`` and ``unstack`` where ``nan`` values would break index alignment (:issue:`4862`, :issue:`7401`, :issue:`7403`, :issue:`7405`, :issue:`7466`)
+- Bug in ``pivot`` and ``unstack`` where ``nan`` values would break index alignment (:issue:`4862`, :issue:`7401`, :issue:`7403`, :issue:`7405`, :issue:`7466`, :issue:`9497`)
- Bug in left ``join`` on multi-index with ``sort=True`` or null values (:issue:`9210`).
- Bug in ``MultiIndex`` where inserting new keys would fail (:issue:`9250`).
- Bug in ``groupby`` when key space exceeds ``int64`` bounds (:issue:`9096`).
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 0be046bbdec42..635edaf60a8b7 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -1382,7 +1382,8 @@ def ngroups(self):
def recons_labels(self):
comp_ids, obs_ids, _ = self.group_info
labels = (ping.labels for ping in self.groupings)
- return decons_obs_group_ids(comp_ids, obs_ids, self.shape, labels)
+ return decons_obs_group_ids(comp_ids,
+ obs_ids, self.shape, labels, xnull=True)
@cache_readonly
def result_index(self):
@@ -3570,13 +3571,26 @@ def decons_group_index(comp_labels, shape):
return label_list[::-1]
-def decons_obs_group_ids(comp_ids, obs_ids, shape, labels):
- """reconstruct labels from observed ids"""
+def decons_obs_group_ids(comp_ids, obs_ids, shape, labels, xnull):
+ """
+ reconstruct labels from observed group ids
+
+ Parameters
+ ----------
+ xnull: boolean,
+ if nulls are excluded; i.e. -1 labels are passed through
+ """
from pandas.hashtable import unique_label_indices
+ if not xnull:
+ lift = np.fromiter(((a == -1).any() for a in labels), dtype='i8')
+ shape = np.asarray(shape, dtype='i8') + lift
+
if not _int64_overflow_possible(shape):
# obs ids are deconstructable! take the fast route!
- return decons_group_index(obs_ids, shape)
+ out = decons_group_index(obs_ids, shape)
+ return out if xnull or not lift.any() \
+ else [x - y for x, y in zip(out, lift)]
i = unique_label_indices(comp_ids)
i8copy = lambda a: a.astype('i8', subok=False, copy=True)
diff --git a/pandas/core/reshape.py b/pandas/core/reshape.py
index 6eb46de11210a..aa5877e656a52 100644
--- a/pandas/core/reshape.py
+++ b/pandas/core/reshape.py
@@ -260,7 +260,8 @@ def _unstack_multiple(data, clocs):
group_index = get_group_index(clabels, shape, sort=False, xnull=False)
comp_ids, obs_ids = _compress_group_index(group_index, sort=False)
- recons_labels = decons_obs_group_ids(comp_ids, obs_ids, shape, clabels)
+ recons_labels = decons_obs_group_ids(comp_ids,
+ obs_ids, shape, clabels, xnull=False)
dummy_index = MultiIndex(levels=rlevels + [obs_ids],
labels=rlabels + [comp_ids],
diff --git a/pandas/tests/test_frame.py b/pandas/tests/test_frame.py
index 66e008aa16b3e..86b7dfef79618 100644
--- a/pandas/tests/test_frame.py
+++ b/pandas/tests/test_frame.py
@@ -12494,6 +12494,24 @@ def verify(df):
left = df.ix[17264:].copy().set_index(['s_id','dosage','agent'])
assert_frame_equal(left.unstack(), right)
+ # GH9497 - multiple unstack with nulls
+ df = DataFrame({'1st':[1, 2, 1, 2, 1, 2],
+ '2nd':pd.date_range('2014-02-01', periods=6, freq='D'),
+ 'jim':100 + np.arange(6),
+ 'joe':(np.random.randn(6) * 10).round(2)})
+
+ df['3rd'] = df['2nd'] - pd.Timestamp('2014-02-02')
+ df.loc[1, '2nd'] = df.loc[3, '2nd'] = nan
+ df.loc[1, '3rd'] = df.loc[4, '3rd'] = nan
+
+ left = df.set_index(['1st', '2nd', '3rd']).unstack(['2nd', '3rd'])
+ self.assertEqual(left.notnull().values.sum(), 2 * len(df))
+
+ for col in ['jim', 'joe']:
+ for _, r in df.iterrows():
+ key = r['1st'], (col, r['2nd'], r['3rd'])
+ self.assertEqual(r[col], left.loc[key])
+
def test_stack_datetime_column_multiIndex(self):
# GH 8039
t = datetime(2014, 1, 1)
| closes https://github.com/pydata/pandas/issues/9497
```
>>> mi
jim joe
1st 2nd 3rd
1 2014-02-01 -1 days 100 -20.87
2 NaT NaT 101 5.76
1 2014-02-03 1 days 102 -4.94
2 NaT 2 days 103 -0.79
1 2014-02-05 NaT 104 -12.51
2 2014-02-06 4 days 105 -9.89
>>> mi.unstack(['2nd', '3rd']).fillna('.')
jim joe
2nd 2014-02-01 NaT 2014-02-03 NaT 2014-02-05 2014-02-06 2014-02-01 NaT 2014-02-03 NaT 2014-02-05 2014-02-06
3rd -1 days NaT 1 days 2 days NaT 4 days -1 days NaT 1 days 2 days NaT 4 days
1st
1 100 . 102 . 104 . -20.87 . -4.94 . -12.51 .
2 . 101 . 103 . 105 . 5.76 . -0.79 . -9.89
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/9517 | 2015-02-19T02:50:53Z | 2015-03-05T23:25:34Z | 2015-03-05T23:25:33Z | 2015-03-06T02:52:19Z |
BUG: period_helper.c is not excluded from clean | diff --git a/setup.py b/setup.py
index 34bf4685d5dd5..4b2e8c6e01889 100755
--- a/setup.py
+++ b/setup.py
@@ -274,7 +274,7 @@ def initialize_options(self):
ujson_lib = pjoin(base,'ujson','lib')
self._clean_exclude = [pjoin(dt,'np_datetime.c'),
pjoin(dt,'np_datetime_strings.c'),
- pjoin(src,'period.c'),
+ pjoin(src,'period_helper.c'),
pjoin(parser,'tokenizer.c'),
pjoin(parser,'io.c'),
pjoin(ujson_python,'ujson.c'),
| I missed this when I was rebasing.
| https://api.github.com/repos/pandas-dev/pandas/pulls/9508 | 2015-02-17T20:47:51Z | 2015-02-17T21:29:04Z | 2015-02-17T21:29:04Z | 2015-02-17T23:26:53Z |
PERF: Cython optimizations for period module, round one | diff --git a/pandas/src/period.pyx b/pandas/src/period.pyx
index e57bdc3b33c5e..05e8ed22fc316 100644
--- a/pandas/src/period.pyx
+++ b/pandas/src/period.pyx
@@ -1,6 +1,11 @@
from datetime import datetime, date, timedelta
import operator
+from cpython cimport (
+ PyObject_RichCompareBool,
+ Py_EQ, Py_NE,
+)
+
from numpy cimport (int8_t, int32_t, int64_t, import_array, ndarray,
NPY_INT64, NPY_DATETIME, NPY_TIMEDELTA)
import numpy as np
@@ -27,6 +32,7 @@ from tslib cimport (
_is_utc,
_is_tzlocal,
_get_dst_info,
+ _nat_scalar_rules,
)
from sys import version_info
@@ -606,16 +612,7 @@ cdef ndarray[int64_t] localize_dt64arr_to_period(ndarray[int64_t] stamps,
return result
-def _period_field_accessor(name, alias):
- def f(self):
- from pandas.tseries.frequencies import get_freq_code as _gfc
- base, mult = _gfc(self.freq)
- return get_period_field(alias, self.ordinal, base)
- f.__name__ = name
- return property(f)
-
-
-class Period(object):
+cdef class Period(object):
"""
Represents an period of time
@@ -634,14 +631,17 @@ class Period(object):
minute : int, default 0
second : int, default 0
"""
- __slots__ = ['freq', 'ordinal']
+ cdef public:
+ int64_t ordinal
+ object freq
+
_comparables = ['name','freqstr']
_typ = 'period'
@classmethod
def _from_ordinal(cls, ordinal, freq):
""" fast creation from an ordinal and freq that are already validated! """
- self = object.__new__(cls)
+ self = Period.__new__(cls)
self.ordinal = ordinal
self.freq = freq
return self
@@ -659,7 +659,6 @@ class Period(object):
self.freq = None
# ordinal is the period offset from the gregorian proleptic epoch
- self.ordinal = None
if ordinal is not None and value is not None:
raise ValueError(("Only value or ordinal but not both should be "
@@ -669,26 +668,25 @@ class Period(object):
raise ValueError("Ordinal must be an integer")
if freq is None:
raise ValueError('Must supply freq for ordinal value')
- self.ordinal = ordinal
elif value is None:
if freq is None:
raise ValueError("If value is None, freq cannot be None")
- self.ordinal = _ordinal_from_fields(year, month, quarter, day,
+ ordinal = _ordinal_from_fields(year, month, quarter, day,
hour, minute, second, freq)
elif isinstance(value, Period):
other = value
if freq is None or _gfc(freq) == _gfc(other.freq):
- self.ordinal = other.ordinal
+ ordinal = other.ordinal
freq = other.freq
else:
converted = other.asfreq(freq)
- self.ordinal = converted.ordinal
+ ordinal = converted.ordinal
elif lib.is_null_datetimelike(value) or value in tslib._nat_strings:
- self.ordinal = tslib.iNaT
+ ordinal = tslib.iNaT
if freq is None:
raise ValueError("If value is NaT, freq cannot be None "
"because it cannot be inferred")
@@ -722,26 +720,30 @@ class Period(object):
# TODO: Better error message - this is slightly confusing
raise ValueError('Only mult == 1 supported')
- if self.ordinal is None:
- self.ordinal = period_ordinal(dt.year, dt.month, dt.day,
+ if ordinal is None:
+ self.ordinal = get_period_ordinal(dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second, dt.microsecond, 0,
base)
+ else:
+ self.ordinal = ordinal
self.freq = frequencies._get_freq_str(base)
- def __eq__(self, other):
+ def __richcmp__(self, other, op):
if isinstance(other, Period):
from pandas.tseries.frequencies import get_freq_code as _gfc
if other.freq != self.freq:
raise ValueError("Cannot compare non-conforming periods")
if self.ordinal == tslib.iNaT or other.ordinal == tslib.iNaT:
- return False
- return (self.ordinal == other.ordinal
- and _gfc(self.freq) == _gfc(other.freq))
- return NotImplemented
-
- def __ne__(self, other):
- return not self == other
+ return _nat_scalar_rules[op]
+ return PyObject_RichCompareBool(self.ordinal, other.ordinal, op)
+ else:
+ if op == Py_EQ:
+ return NotImplemented
+ elif op == Py_NE:
+ return NotImplemented
+ raise TypeError('Cannot compare type %r with type %r' %
+ (type(self).__name__, type(other).__name__))
def __hash__(self):
return hash((self.ordinal, self.freq))
@@ -807,25 +809,6 @@ class Period(object):
else: # pragma: no cover
return NotImplemented
- def _comp_method(func, name):
- def f(self, other):
- if isinstance(other, Period):
- if other.freq != self.freq:
- raise ValueError("Cannot compare non-conforming periods")
- if self.ordinal == tslib.iNaT or other.ordinal == tslib.iNaT:
- return False
- return func(self.ordinal, other.ordinal)
- else:
- raise TypeError(other)
-
- f.__name__ = name
- return f
-
- __lt__ = _comp_method(operator.lt, '__lt__')
- __le__ = _comp_method(operator.le, '__le__')
- __gt__ = _comp_method(operator.gt, '__gt__')
- __ge__ = _comp_method(operator.ge, '__ge__')
-
def asfreq(self, freq, how='E'):
"""
Convert Period to desired frequency, either at the start or end of the
@@ -898,19 +881,50 @@ class Period(object):
dt64 = period_ordinal_to_dt64(val.ordinal, base)
return Timestamp(dt64, tz=tz)
- year = _period_field_accessor('year', 0)
- month = _period_field_accessor('month', 3)
- day = _period_field_accessor('day', 4)
- hour = _period_field_accessor('hour', 5)
- minute = _period_field_accessor('minute', 6)
- second = _period_field_accessor('second', 7)
- weekofyear = _period_field_accessor('week', 8)
- week = weekofyear
- dayofweek = _period_field_accessor('dayofweek', 10)
- weekday = dayofweek
- dayofyear = _period_field_accessor('dayofyear', 9)
- quarter = _period_field_accessor('quarter', 2)
- qyear = _period_field_accessor('qyear', 1)
+ cdef _field(self, alias):
+ from pandas.tseries.frequencies import get_freq_code as _gfc
+ base, mult = _gfc(self.freq)
+ return get_period_field(alias, self.ordinal, base)
+
+ property year:
+ def __get__(self):
+ return self._field(0)
+ property month:
+ def __get__(self):
+ return self._field(3)
+ property day:
+ def __get__(self):
+ return self._field(4)
+ property hour:
+ def __get__(self):
+ return self._field(5)
+ property minute:
+ def __get__(self):
+ return self._field(6)
+ property second:
+ def __get__(self):
+ return self._field(7)
+ property weekofyear:
+ def __get__(self):
+ return self._field(8)
+ property week:
+ def __get__(self):
+ return self.weekofyear
+ property dayofweek:
+ def __get__(self):
+ return self._field(10)
+ property weekday:
+ def __get__(self):
+ return self.dayofweek
+ property dayofyear:
+ def __get__(self):
+ return self._field(9)
+ property quarter:
+ def __get__(self):
+ return self._field(2)
+ property qyear:
+ def __get__(self):
+ return self._field(1)
@classmethod
def now(cls, freq=None):
@@ -1094,7 +1108,7 @@ def _ordinal_from_fields(year, month, quarter, day, hour, minute,
if quarter is not None:
year, month = _quarter_to_myear(year, quarter, freq)
- return period_ordinal(year, month, day, hour, minute, second, 0, 0, base)
+ return get_period_ordinal(year, month, day, hour, minute, second, 0, 0, base)
def _quarter_to_myear(year, quarter, freq):
diff --git a/pandas/tslib.pxd b/pandas/tslib.pxd
index d8fc57fe85bfd..3cb7e94c65100 100644
--- a/pandas/tslib.pxd
+++ b/pandas/tslib.pxd
@@ -6,3 +6,4 @@ cpdef object maybe_get_tz(object)
cdef bint _is_utc(object)
cdef bint _is_tzlocal(object)
cdef object _get_dst_info(object)
+cdef bint _nat_scalar_rules[6]
| Each commit passes `test_fast.sh`, so performance can be measured between commits.
I can break any of these commits into separate PRs if needed.
| https://api.github.com/repos/pandas-dev/pandas/pulls/9504 | 2015-02-17T16:38:03Z | 2015-03-01T21:18:33Z | 2015-03-01T21:18:33Z | 2015-03-01T21:18:33Z |
BUG: Incorrect dtypes inferred on datetimelike looking series & on xs slices (GH9477) | diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt
index 63119e90a1337..ead3c79430bf9 100644
--- a/doc/source/whatsnew/v0.16.0.txt
+++ b/doc/source/whatsnew/v0.16.0.txt
@@ -246,6 +246,7 @@ Bug Fixes
- Fixed bug in ``to_sql`` ``dtype`` argument not accepting an instantiated
SQLAlchemy type (:issue:`9083`).
- Bug in ``.loc`` partial setting with a ``np.datetime64`` (:issue:`9516`)
+- Incorrect dtypes inferred on datetimelike looking series & on xs slices (:issue:`9477`)
- Items in ``Categorical.unique()`` (and ``s.unique()`` if ``s`` is of dtype ``category``) now appear in the order in which they are originally found, not in sorted order (:issue:`9331`). This is now consistent with the behavior for other dtypes in pandas.
diff --git a/pandas/core/common.py b/pandas/core/common.py
index 78c0c6c5dbd0f..4de63cf59bd1c 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -2030,6 +2030,7 @@ def _possibly_infer_to_datetimelike(value, convert_dates=False):
Parameters
----------
+ value : np.array
convert_dates : boolean, default False
if True try really hard to convert dates (such as datetime.date), other
leave inferred dtype 'date' alone
@@ -2068,9 +2069,9 @@ def _try_timedelta(v):
inferred_type = lib.infer_dtype(sample)
if inferred_type in ['datetime', 'datetime64'] or (convert_dates and inferred_type in ['date']):
- value = _try_datetime(v)
+ value = _try_datetime(v).reshape(shape)
elif inferred_type in ['timedelta', 'timedelta64']:
- value = _try_timedelta(v)
+ value = _try_timedelta(v).reshape(shape)
# its possible to have nulls intermixed within the datetime or timedelta
# these will in general have an inferred_type of 'mixed', so have to try
@@ -2081,9 +2082,9 @@ def _try_timedelta(v):
elif inferred_type in ['mixed']:
if lib.is_possible_datetimelike_array(_ensure_object(v)):
- value = _try_timedelta(v)
+ value = _try_timedelta(v).reshape(shape)
if lib.infer_dtype(value) in ['mixed']:
- value = _try_datetime(v)
+ value = _try_datetime(v).reshape(shape)
return value
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 733de1fc202e5..d64353db8cda6 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -27,7 +27,7 @@
_default_index, _maybe_upcast, is_sequence,
_infer_dtype_from_scalar, _values_from_object,
is_list_like, _get_dtype, _maybe_box_datetimelike,
- is_categorical_dtype)
+ is_categorical_dtype, is_object_dtype, _possibly_infer_to_datetimelike)
from pandas.core.generic import NDFrame, _shared_docs
from pandas.core.index import Index, MultiIndex, _ensure_index
from pandas.core.indexing import (maybe_droplevels,
@@ -396,7 +396,15 @@ def _get_axes(N, K, index=index, columns=columns):
raise_with_traceback(e)
index, columns = _get_axes(*values.shape)
- return create_block_manager_from_blocks([values.T], [columns, index])
+ values = values.T
+
+ # if we don't have a dtype specified, then try to convert objects
+ # on the entire block; this is to convert if we have datetimelike's
+ # embedded in an object type
+ if dtype is None and is_object_dtype(values):
+ values = _possibly_infer_to_datetimelike(values)
+
+ return create_block_manager_from_blocks([values], [columns, index])
@property
def axes(self):
@@ -1537,7 +1545,7 @@ def _sizeof_fmt(num, size_qualifier):
# cases (e.g., it misses categorical data even with object
# categories)
size_qualifier = ('+' if 'object' in counts
- or self.index.dtype.kind == 'O' else '')
+ or is_object_dtype(self.index) else '')
mem_usage = self.memory_usage(index=True).sum()
lines.append("memory usage: %s\n" %
_sizeof_fmt(mem_usage, size_qualifier))
@@ -2257,6 +2265,8 @@ def reindexer(value):
elif (isinstance(value, Index) or is_sequence(value)):
from pandas.core.series import _sanitize_index
+
+ # turn me into an ndarray
value = _sanitize_index(value, self.index, copy=False)
if not isinstance(value, (np.ndarray, Index)):
if isinstance(value, list) and len(value) > 0:
@@ -2267,6 +2277,11 @@ def reindexer(value):
value = value.copy().T
else:
value = value.copy()
+
+ # possibly infer to datetimelike
+ if is_object_dtype(value.dtype):
+ value = _possibly_infer_to_datetimelike(value.ravel()).reshape(value.shape)
+
else:
# upcast the scalar
dtype, value = _infer_dtype_from_scalar(value)
@@ -2341,7 +2356,7 @@ def lookup(self, row_labels, col_labels):
for i, (r, c) in enumerate(zip(row_labels, col_labels)):
result[i] = self.get_value(r, c)
- if result.dtype == 'O':
+ if is_object_dtype(result):
result = lib.maybe_convert_objects(result)
return result
@@ -4232,7 +4247,7 @@ def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None,
values = self.values
result = f(values)
- if result.dtype == np.object_:
+ if is_object_dtype(result.dtype):
try:
if filter_type is None or filter_type == 'numeric':
result = result.astype(np.float64)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 9a4a91cf01ff6..18500fd05b5f8 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1467,8 +1467,11 @@ def xs(self, key, axis=0, level=None, copy=None, drop_level=True):
if not is_list_like(new_values) or self.ndim == 1:
return _maybe_box_datetimelike(new_values)
- result = Series(new_values, index=self.columns,
- name=self.index[loc])
+ result = Series(new_values,
+ index=self.columns,
+ name=self.index[loc],
+ copy=copy,
+ dtype=new_values.dtype)
else:
result = self.iloc[loc]
diff --git a/pandas/core/internals.py b/pandas/core/internals.py
index 359463b10d3d0..4453c7eaf1fda 100644
--- a/pandas/core/internals.py
+++ b/pandas/core/internals.py
@@ -13,8 +13,8 @@
ABCSparseSeries, _infer_dtype_from_scalar,
is_null_datelike_scalar, _maybe_promote,
is_timedelta64_dtype, is_datetime64_dtype,
- _possibly_infer_to_datetimelike, array_equivalent,
- _maybe_convert_string_to_object, is_categorical)
+ array_equivalent, _maybe_convert_string_to_object,
+ is_categorical)
from pandas.core.index import Index, MultiIndex, _ensure_index
from pandas.core.indexing import maybe_convert_indices, length_of_indexer
from pandas.core.categorical import Categorical, maybe_to_categorical
@@ -2074,25 +2074,8 @@ def make_block(values, placement, klass=None, ndim=None,
klass = ComplexBlock
elif is_categorical(values):
klass = CategoricalBlock
-
else:
-
- # we want to infer here if its a datetimelike if its object type
- # this is pretty strict in that it requires a datetime/timedelta
- # value IN addition to possible nulls/strings
- # an array of ONLY strings will not be inferred
- if np.prod(values.shape):
- result = _possibly_infer_to_datetimelike(values)
- vtype = result.dtype.type
- if issubclass(vtype, np.datetime64):
- klass = DatetimeBlock
- values = result
- elif (issubclass(vtype, np.timedelta64)):
- klass = TimeDeltaBlock
- values = result
-
- if klass is None:
- klass = ObjectBlock
+ klass = ObjectBlock
return klass(values, ndim=ndim, fastpath=fastpath,
placement=placement)
diff --git a/pandas/io/packers.py b/pandas/io/packers.py
index a8ad8c058a2b4..b3e2e16af54c2 100644
--- a/pandas/io/packers.py
+++ b/pandas/io/packers.py
@@ -490,7 +490,9 @@ def decode(obj):
index = obj['index']
return globals()[obj['klass']](unconvert(obj['data'], dtype,
obj['compress']),
- index=index, name=obj['name'])
+ index=index,
+ dtype=dtype,
+ name=obj['name'])
elif typ == 'block_manager':
axes = obj['axes']
diff --git a/pandas/tests/test_series.py b/pandas/tests/test_series.py
index 04dad68703577..79467db1ee264 100644
--- a/pandas/tests/test_series.py
+++ b/pandas/tests/test_series.py
@@ -569,6 +569,7 @@ def test_scalar_conversion(self):
self.assertEqual(int(Series([1.])), 1)
self.assertEqual(long(Series([1.])), 1)
+
def test_astype(self):
s = Series(np.random.randn(5),name='foo')
@@ -778,6 +779,28 @@ def test_constructor_dtype_nocast(self):
s2[1] = 5
self.assertEqual(s[1], 5)
+ def test_constructor_datelike_coercion(self):
+
+ # GH 9477
+ # incorrectly infering on dateimelike looking when object dtype is specified
+ s = Series([Timestamp('20130101'),'NOV'],dtype=object)
+ self.assertEqual(s.iloc[0],Timestamp('20130101'))
+ self.assertEqual(s.iloc[1],'NOV')
+ self.assertTrue(s.dtype == object)
+
+ # the dtype was being reset on the slicing and re-inferred to datetime even
+ # thought the blocks are mixed
+ belly = '216 3T19'.split()
+ wing1 = '2T15 4H19'.split()
+ wing2 = '416 4T20'.split()
+ mat = pd.to_datetime('2016-01-22 2019-09-07'.split())
+ df = pd.DataFrame({'wing1':wing1, 'wing2':wing2, 'mat':mat}, index=belly)
+
+ result = df.loc['3T19']
+ self.assertTrue(result.dtype == object)
+ result = df.loc['216']
+ self.assertTrue(result.dtype == object)
+
def test_constructor_dtype_datetime64(self):
import pandas.tslib as tslib
| closes #9477
| https://api.github.com/repos/pandas-dev/pandas/pulls/9501 | 2015-02-16T23:44:53Z | 2015-02-24T13:49:22Z | 2015-02-24T13:49:22Z | 2015-02-24T13:49:22Z |
BLD: revise setup.py to clean properly on windows platforms | diff --git a/setup.py b/setup.py
index c7edc2ebd66f8..42d666dcb8f5c 100755
--- a/setup.py
+++ b/setup.py
@@ -265,16 +265,23 @@ def initialize_options(self):
self.all = True
self._clean_me = []
self._clean_trees = []
- self._clean_exclude = ['pandas/src/datetime/np_datetime.c',
- 'pandas/src/datetime/np_datetime_strings.c',
- 'pandas/src/period.c',
- 'pandas/src/parser/tokenizer.c',
- 'pandas/src/parser/io.c',
- 'pandas/src/ujson/python/ujson.c',
- 'pandas/src/ujson/python/objToJSON.c',
- 'pandas/src/ujson/python/JSONtoObj.c',
- 'pandas/src/ujson/lib/ultrajsonenc.c',
- 'pandas/src/ujson/lib/ultrajsondec.c',
+
+ base = pjoin('pandas','src')
+ dt = pjoin(base,'datetime')
+ src = base
+ parser = pjoin(base,'parser')
+ ujson_python = pjoin(base,'ujson','python')
+ ujson_lib = pjoin(base,'ujson','lib')
+ self._clean_exclude = [pjoin(dt,'np_datetime.c'),
+ pjoin(dt,'np_datetime_strings.c'),
+ pjoin(src,'period.c'),
+ pjoin(parser,'tokenizer.c'),
+ pjoin(parser,'io.c'),
+ pjoin(ujson_python,'ujson.c'),
+ pjoin(ujson_python,'objToJSON.c'),
+ pjoin(ujson_python,'JSONtoObj.c'),
+ pjoin(ujson_lib,'ultrajsonenc.c'),
+ pjoin(ujson_lib,'ultrajsondec.c'),
]
for root, dirs, files in os.walk('pandas'):
| https://api.github.com/repos/pandas-dev/pandas/pulls/9500 | 2015-02-16T22:03:01Z | 2015-02-16T22:43:57Z | 2015-02-16T22:43:57Z | 2015-02-16T22:43:57Z | |
TST: fix read_pickle for win32 compat | diff --git a/pandas/io/tests/generate_legacy_pickles.py b/pandas/io/tests/generate_legacy_pickles.py
index 56ef1aa9b0f19..e1cf541fe6195 100644
--- a/pandas/io/tests/generate_legacy_pickles.py
+++ b/pandas/io/tests/generate_legacy_pickles.py
@@ -11,7 +11,6 @@ def _create_sp_series():
# nan-based
arr = np.arange(15, dtype=np.float64)
- index = np.arange(15)
arr[7:12] = nan
arr[-1:] = nan
@@ -28,11 +27,10 @@ def _create_sp_tsseries():
# nan-based
arr = np.arange(15, dtype=np.float64)
- index = np.arange(15)
arr[7:12] = nan
arr[-1:] = nan
- date_index = bdate_range('1/1/2011', periods=len(index))
+ date_index = bdate_range('1/1/2011', periods=len(arr))
bseries = SparseTimeSeries(arr, index=date_index, kind='block')
bseries.name = 'btsseries'
return bseries
@@ -99,7 +97,7 @@ def create_data():
columns=['A', 'B', 'A']),
cat_onecol=DataFrame(dict(A=Categorical(['foo', 'bar']))),
cat_and_float=DataFrame(dict(A=Categorical(['foo', 'bar', 'baz']),
- B=np.arange(3))),
+ B=np.arange(3).astype(np.int64))),
)
panel = dict(float = Panel(dict(ItemA = frame['float'], ItemB = frame['float']+1)),
dup = Panel(np.arange(30).reshape(3, 5, 2).astype(np.float64),
| https://api.github.com/repos/pandas-dev/pandas/pulls/9499 | 2015-02-16T14:55:58Z | 2015-02-16T15:37:45Z | 2015-02-16T15:37:45Z | 2015-02-16T15:37:45Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.