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 |
|---|---|---|---|---|---|---|---|
BLD: force ABI compat on 3.6 / conda-forge build by specifying all deps | diff --git a/ci/requirements-3.6.build b/ci/requirements-3.6.build
index 1c4b46aea3865..31ffd5acc7fcc 100644
--- a/ci/requirements-3.6.build
+++ b/ci/requirements-3.6.build
@@ -2,5 +2,7 @@ python=3.6*
python-dateutil
pytz
nomkl
-numpy
cython
+
+# pin numpy that is built for all our deps
+numpy=1.13.1=py36_blas_openblas_201
| closes #17617 | https://api.github.com/repos/pandas-dev/pandas/pulls/17619 | 2017-09-21T19:22:11Z | 2017-09-21T20:19:48Z | 2017-09-21T20:19:48Z | 2017-09-21T20:50:16Z |
PERF: Implement RangeIndex min/max using RangeIndex properties | diff --git a/asv_bench/benchmarks/index_object.py b/asv_bench/benchmarks/index_object.py
index 3fb53ce9b3c98..454d9ccdda102 100644
--- a/asv_bench/benchmarks/index_object.py
+++ b/asv_bench/benchmarks/index_object.py
@@ -199,3 +199,23 @@ def time_datetime_level_values_full(self):
def time_datetime_level_values_sliced(self):
self.mi[:10].values
+
+
+class Range(object):
+ goal_time = 0.2
+
+ def setup(self):
+ self.idx_inc = RangeIndex(start=0, stop=10**7, step=3)
+ self.idx_dec = RangeIndex(start=10**7, stop=-1, step=-3)
+
+ def time_max(self):
+ self.idx_inc.max()
+
+ def time_max_trivial(self):
+ self.idx_dec.max()
+
+ def time_min(self):
+ self.idx_dec.min()
+
+ def time_min_trivial(self):
+ self.idx_inc.min()
diff --git a/doc/source/api.rst b/doc/source/api.rst
index 6b3e6bedcb24b..96c7f68f57aaa 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -1416,6 +1416,20 @@ Selecting
Index.slice_indexer
Index.slice_locs
+.. _api.numericindex:
+
+Numeric Index
+-------------
+
+.. autosummary::
+ :toctree: generated/
+ :template: autosummary/class_without_autosummary.rst
+
+ RangeIndex
+ Int64Index
+ UInt64Index
+ Float64Index
+
.. _api.categoricalindex:
CategoricalIndex
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index 8bc9834ebef09..6157d73a76b31 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -473,6 +473,7 @@ Performance Improvements
- Improved performance of :meth:`Categorical.set_categories` by not materializing the values (:issue:`17508`)
- :attr:`Timestamp.microsecond` no longer re-computes on attribute access (:issue:`17331`)
- Improved performance of the :class:`CategoricalIndex` for data that is already categorical dtype (:issue:`17513`)
+- Improved performance of :meth:`RangeIndex.min` and :meth:`RangeIndex.max` by using ``RangeIndex`` properties to perform the computations (:issue:`17607`)
.. _whatsnew_0210.bug_fixes:
diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py
index b759abaed4e56..16523257c2f77 100644
--- a/pandas/core/indexes/range.py
+++ b/pandas/core/indexes/range.py
@@ -269,6 +269,24 @@ def copy(self, name=None, deep=False, dtype=None, **kwargs):
return RangeIndex(name=name, fastpath=True,
**dict(self._get_data_as_items()))
+ def _minmax(self, meth):
+ no_steps = len(self) - 1
+ if no_steps == -1:
+ return np.nan
+ elif ((meth == 'min' and self._step > 0) or
+ (meth == 'max' and self._step < 0)):
+ return self._start
+
+ return self._start + self._step * no_steps
+
+ def min(self):
+ """The minimum value of the RangeIndex"""
+ return self._minmax('min')
+
+ def max(self):
+ """The maximum value of the RangeIndex"""
+ return self._minmax('max')
+
def argsort(self, *args, **kwargs):
"""
Returns the indices that would sort the index and its
diff --git a/pandas/tests/indexes/test_range.py b/pandas/tests/indexes/test_range.py
index d206c36ee51c9..8dc5a40ced4bf 100644
--- a/pandas/tests/indexes/test_range.py
+++ b/pandas/tests/indexes/test_range.py
@@ -10,7 +10,7 @@
import numpy as np
-from pandas import (notna, Series, Index, Float64Index,
+from pandas import (isna, notna, Series, Index, Float64Index,
Int64Index, RangeIndex)
import pandas.util.testing as tm
@@ -994,3 +994,22 @@ def test_append(self):
# Append single item rather than list
result2 = indices[0].append(indices[1])
tm.assert_index_equal(result2, expected, exact=True)
+
+ @pytest.mark.parametrize('start,stop,step',
+ [(0, 400, 3), (500, 0, -6), (-10**6, 10**6, 4),
+ (10**6, -10**6, -4), (0, 10, 20)])
+ def test_max_min(self, start, stop, step):
+ # GH17607
+ idx = RangeIndex(start, stop, step)
+ expected = idx._int64index.max()
+ result = idx.max()
+ assert result == expected
+
+ expected = idx._int64index.min()
+ result = idx.min()
+ assert result == expected
+
+ # empty
+ idx = RangeIndex(start, stop, -step)
+ assert isna(idx.max())
+ assert isna(idx.min())
| - [X] closes #17607
- [X] tests added / passed
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [X] whatsnew entry
Benchmarks are essentially the same as what's referenced in the issue. Maybe a few ns slower since I combined logic into a helper function vs having identical code (other than `elif`) for both min/max, which was the case I did the benchmarks posted in the issue. Updated benchmarks:
```
before after ratio
[fedf9228] [4cb0de8d]
- 25.4±0ms 1.77±0.06μs 0.00 index_object.Range.time_min
- 26.0±0.9ms 1.71±0.06μs 0.00 index_object.Range.time_max
- 25.4±0ms 1.51±0μs 0.00 index_object.Range.time_max_trivial
- 25.4±0ms 1.30±0μs 0.00 index_object.Range.time_min_trivial
SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY.
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/17611 | 2017-09-21T05:42:19Z | 2017-09-22T13:15:13Z | 2017-09-22T13:15:13Z | 2017-10-22T05:47:13Z |
Fix make_signature TypeError in py3 | diff --git a/pandas/tests/util/test_util.py b/pandas/tests/util/test_util.py
index abd82cfa89f94..ffc9703abff41 100644
--- a/pandas/tests/util/test_util.py
+++ b/pandas/tests/util/test_util.py
@@ -9,7 +9,7 @@
import pytest
from pandas.compat import intern
from pandas.util._move import move_into_mutable_buffer, BadMove, stolenbuf
-from pandas.util._decorators import deprecate_kwarg
+from pandas.util._decorators import deprecate_kwarg, make_signature
from pandas.util._validators import (validate_args, validate_kwargs,
validate_args_and_kwargs,
validate_bool_kwarg)
@@ -467,3 +467,17 @@ def test_set_locale(self):
current_locale = locale.getlocale()
assert current_locale == self.current_locale
+
+
+def test_make_signature():
+ # See GH 17608
+ # Case where the func does not have default kwargs
+ sig = make_signature(validate_kwargs)
+ assert sig == (['fname', 'kwargs', 'compat_args'],
+ ['fname', 'kwargs', 'compat_args'])
+
+ # Case where the func does have default kwargs
+ sig = make_signature(deprecate_kwarg)
+ assert sig == (['old_arg_name', 'new_arg_name',
+ 'mapping=None', 'stacklevel=2'],
+ ['old_arg_name', 'new_arg_name', 'mapping', 'stacklevel'])
diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py
index bb7ffe45c689b..1237ee67a3345 100644
--- a/pandas/util/_decorators.py
+++ b/pandas/util/_decorators.py
@@ -242,7 +242,7 @@ def make_signature(func):
defaults = ('',) * n_wo_defaults
else:
n_wo_defaults = len(spec.args) - len(spec.defaults)
- defaults = ('',) * n_wo_defaults + spec.defaults
+ defaults = ('',) * n_wo_defaults + tuple(spec.defaults)
args = []
for i, (var, default) in enumerate(zip(spec.args, defaults)):
args.append(var if default == '' else var + '=' + repr(default))
| xref #17608
- [ ] closes #xxxx
- [x] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17609 | 2017-09-21T04:13:19Z | 2017-09-22T19:50:54Z | 2017-09-22T19:50:54Z | 2017-10-30T16:23:30Z |
Removed duplicated _constructor_sliced definition in sparse.frame | diff --git a/pandas/core/sparse/frame.py b/pandas/core/sparse/frame.py
index 1e98e919baa33..7aa49efa82f61 100644
--- a/pandas/core/sparse/frame.py
+++ b/pandas/core/sparse/frame.py
@@ -49,7 +49,6 @@ class SparseDataFrame(DataFrame):
Default fill_value for converting Series to SparseSeries
(default: nan). Will not override SparseSeries passed in.
"""
- _constructor_sliced = SparseSeries
_subtyp = 'sparse_frame'
def __init__(self, data=None, index=None, columns=None, default_kind=None,
| Removal of duplicated code in core.sparse.frame | https://api.github.com/repos/pandas-dev/pandas/pulls/17604 | 2017-09-20T13:06:19Z | 2017-09-20T21:19:08Z | 2017-09-20T21:19:08Z | 2017-09-20T21:19:30Z |
BUG: Correctly localize naive datetime strings with Series and datetimetztype (#17415) | diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt
index 92eeed89ada2a..ae99dfd2d7902 100644
--- a/doc/source/whatsnew/v0.23.0.txt
+++ b/doc/source/whatsnew/v0.23.0.txt
@@ -380,7 +380,7 @@ Conversion
- Fixed bug where comparing :class:`DatetimeIndex` failed to raise ``TypeError`` when attempting to compare timezone-aware and timezone-naive datetimelike objects (:issue:`18162`)
- Bug in :class:`DatetimeIndex` where the repr was not showing high-precision time values at the end of a day (e.g., 23:59:59.999999999) (:issue:`19030`)
- Bug where dividing a scalar timedelta-like object with :class:`TimedeltaIndex` performed the reciprocal operation (:issue:`19125`)
--
+- Bug in localization of a naive, datetime string in a ``Series`` constructor with a ``datetime64[ns, tz]`` dtype (:issue:`174151`)
Indexing
^^^^^^^^
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 5fcb5f09dfae7..d4e291029e67d 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -20,7 +20,7 @@
is_integer_dtype,
is_datetime_or_timedelta_dtype,
is_bool_dtype, is_scalar,
- _string_dtypes,
+ is_string_dtype, _string_dtypes,
pandas_dtype,
_ensure_int8, _ensure_int16,
_ensure_int32, _ensure_int64,
@@ -1003,12 +1003,20 @@ def maybe_cast_to_datetime(value, dtype, errors='raise'):
if is_datetime64:
value = to_datetime(value, errors=errors)._values
elif is_datetime64tz:
- # input has to be UTC at this point, so just
- # localize
- value = (to_datetime(value, errors=errors)
- .tz_localize('UTC')
- .tz_convert(dtype.tz)
- )
+ # The string check can be removed once issue #13712
+ # is solved. String data that is passed with a
+ # datetime64tz is assumed to be naive which should
+ # be localized to the timezone.
+ is_dt_string = is_string_dtype(value)
+ value = to_datetime(value, errors=errors)
+ if is_dt_string:
+ # Strings here are naive, so directly localize
+ value = value.tz_localize(dtype.tz)
+ else:
+ # Numeric values are UTC at this point,
+ # so localize and convert
+ value = (value.tz_localize('UTC')
+ .tz_convert(dtype.tz))
elif is_timedelta64:
value = to_timedelta(value, errors=errors)._values
except (AttributeError, ValueError, TypeError):
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index 5de5f1f0584f4..a3e40f65e922f 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -707,6 +707,14 @@ def test_constructor_with_datetime_tz(self):
expected = Series(pd.DatetimeIndex(['NaT', 'NaT'], tz='US/Eastern'))
assert_series_equal(s, expected)
+ @pytest.mark.parametrize('arg',
+ ['2013-01-01 00:00:00', pd.NaT, np.nan, None])
+ def test_constructor_with_naive_string_and_datetimetz_dtype(self, arg):
+ # GH 17415: With naive string
+ result = Series([arg], dtype='datetime64[ns, CET]')
+ expected = Series(pd.Timestamp(arg)).dt.tz_localize('CET')
+ assert_series_equal(result, expected)
+
def test_construction_interval(self):
# construction from interval & array of intervals
index = IntervalIndex.from_breaks(np.arange(3), closed='right')
| - [x] closes #17415
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17603 | 2017-09-20T06:27:17Z | 2018-01-12T11:40:33Z | 2018-01-12T11:40:32Z | 2018-01-12T18:02:08Z |
remove unused cimport of is_null_datetimelike | diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx
index 8cbc65633c786..d159761c3f5e6 100644
--- a/pandas/_libs/algos.pyx
+++ b/pandas/_libs/algos.pyx
@@ -33,7 +33,6 @@ from libc.math cimport sqrt, fabs
from util cimport numeric, get_nat
cimport lib
-from lib cimport is_null_datetimelike
from pandas._libs import lib
cdef int64_t iNaT = get_nat()
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17598 | 2017-09-20T02:30:07Z | 2017-09-20T12:04:30Z | 2017-09-20T12:04:30Z | 2017-10-30T16:24:57Z |
Simplify to_pydatetime() | diff --git a/asv_bench/benchmarks/timestamp.py b/asv_bench/benchmarks/timestamp.py
index e4f3023037580..e8cb4c9d1c75b 100644
--- a/asv_bench/benchmarks/timestamp.py
+++ b/asv_bench/benchmarks/timestamp.py
@@ -81,3 +81,9 @@ def time_replace_across_dst(self):
def time_replace_None(self):
self.ts_tz.replace(tzinfo=None)
+
+ def time_to_pydatetime(self):
+ self.ts.to_pydatetime()
+
+ def time_to_pydatetime_tz(self):
+ self.ts_tz.to_pydatetime()
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx
index 8238552b44e03..6ba37062ac869 100644
--- a/pandas/_libs/tslib.pyx
+++ b/pandas/_libs/tslib.pyx
@@ -1158,18 +1158,13 @@ cdef class _Timestamp(datetime):
If warn=True, issue a warning if nanoseconds is nonzero.
"""
- cdef:
- pandas_datetimestruct dts
- _TSObject ts
-
if self.nanosecond != 0 and warn:
warnings.warn("Discarding nonzero nanoseconds in conversion",
UserWarning, stacklevel=2)
- ts = convert_to_tsobject(self, self.tzinfo, None, 0, 0)
- dts = ts.dts
- return datetime(dts.year, dts.month, dts.day,
- dts.hour, dts.min, dts.sec,
- dts.us, ts.tzinfo)
+
+ return datetime(self.year, self.month, self.day,
+ self.hour, self.minute, self.second,
+ self.microsecond, self.tzinfo)
cpdef to_datetime64(self):
""" Returns a numpy.datetime64 object with 'ns' precision """
| Up until #17331, `Timestamp.microsecond` was very slow. So previously it was faster to go through `convert_to_tsobject` to get a new `datetime` instance than it was to just return
`datetime(self.year, self.month, self.day, self.hour, self.minute, self.second, self.microsecond, self.tzinfo)`
Now it is slightly faster (and much simpler) to do it this way.
Before:
```
In [2]: ts = pd.Timestamp.now()
In [3]: %timeit ts.to_pydatetime()
The slowest run took 13.88 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.44 µs per loop
```
After:
```
In [2]: ts = pd.Timestamp.now()
In [3]: %timeit ts.to_pydatetime()
The slowest run took 8.51 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.29 µs per loop
```
With a tz-aware Timestamp the speedup is much bigger:
Before:
```
In [4]: import pytz
In [5]: ts2 = ts.replace(tzinfo=pytz.timezone('US/Pacific'))
In [6]: %timeit ts2.to_pydatetime()
The slowest run took 39.71 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 68.9 µs per loop
```
After:
```
In [7]: import pytz
In [8]: ts2 = ts.replace(tzinfo=pytz.timezone('US/Pacific'))
In [9]: %timeit ts2.to_pydatetime()
The slowest run took 8.29 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.47 µs per loop
```
| https://api.github.com/repos/pandas-dev/pandas/pulls/17592 | 2017-09-19T17:45:59Z | 2017-09-22T13:22:55Z | 2017-09-22T13:22:55Z | 2017-10-30T16:23:33Z |
Separate properties module | diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index 53ca41e4b2489..01548e17d39ab 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -1907,5 +1907,4 @@ cdef class BlockPlacement:
include "reduce.pyx"
-include "properties.pyx"
include "inference.pyx"
diff --git a/pandas/_libs/src/properties.pyx b/pandas/_libs/properties.pyx
similarity index 95%
rename from pandas/_libs/src/properties.pyx
rename to pandas/_libs/properties.pyx
index 4a3fd4b771a17..22d66356ebdc3 100644
--- a/pandas/_libs/src/properties.pyx
+++ b/pandas/_libs/properties.pyx
@@ -1,5 +1,8 @@
+
+from cython cimport Py_ssize_t
+
from cpython cimport (
- PyDict_Contains, PyDict_GetItem, PyDict_GetItem, PyDict_SetItem)
+ PyDict_Contains, PyDict_GetItem, PyDict_SetItem)
cdef class cache_readonly(object):
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index a71bf7be1bc75..e0a9fdb08dcb2 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -9,7 +9,7 @@
import numpy as np
import pandas as pd
-from pandas._libs import tslib, lib
+from pandas._libs import tslib, lib, properties
from pandas.core.dtypes.common import (
_ensure_int64,
_ensure_object,
@@ -258,7 +258,7 @@ def _setup_axes(cls, axes, info_axis=None, stat_axis=None, aliases=None,
if build_axes:
def set_axis(a, i):
- setattr(cls, a, lib.AxisProperty(i))
+ setattr(cls, a, properties.AxisProperty(i))
cls._internal_names_set.add(a)
if axes_are_reversed:
diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py
index bb7ffe45c689b..31e27817913c5 100644
--- a/pandas/util/_decorators.py
+++ b/pandas/util/_decorators.py
@@ -1,5 +1,5 @@
from pandas.compat import callable, signature
-from pandas._libs.lib import cache_readonly # noqa
+from pandas._libs.properties import cache_readonly # noqa
import types
import warnings
from textwrap import dedent
diff --git a/setup.py b/setup.py
index 0e4e22b875e1d..d28c4ba8be5b0 100755
--- a/setup.py
+++ b/setup.py
@@ -437,7 +437,7 @@ def get_tag(self):
cmdclass['build_src'] = DummyBuildSrc
cmdclass['build_ext'] = CheckingBuildExt
-lib_depends = ['reduce', 'inference', 'properties']
+lib_depends = ['reduce', 'inference']
def srcpath(name=None, suffix='.pyx', subdir='src'):
@@ -478,6 +478,7 @@ def pxd(name):
ext_data = {
'_libs.lib': {'pyxfile': '_libs/lib',
'depends': lib_depends + tseries_depends},
+ '_libs.properties': {'pyxfile': '_libs/properties', 'include': []},
'_libs.hashtable': {'pyxfile': '_libs/hashtable',
'pxdfiles': ['_libs/hashtable'],
'depends': (['pandas/_libs/src/klib/khash_python.h']
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17590 | 2017-09-19T14:57:31Z | 2017-09-22T13:10:31Z | 2017-09-22T13:10:31Z | 2017-10-30T16:23:32Z |
BUG: wrap __idiv__ to avoid making a copy (#12962) | diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index c808babeee5d9..254d4c010f1e2 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -585,6 +585,7 @@ PyPy
Other
^^^^^
+- Bug where some inplace operators were not being wrapped and produced a copy when invoked (:issue:`12962`)
- Bug in :func:`eval` where the ``inplace`` parameter was being incorrectly handled (:issue:`16732`)
- Several ``NaT`` method docstrings (e.g. :func:`NaT.ctime`) were incorrect (:issue:`17327`)
- The documentation has had references to versions < v0.17 removed and cleaned up (:issue:`17442`, :issue:`17442`, :issue:`17404` & :issue:`17504`)
diff --git a/pandas/core/ops.py b/pandas/core/ops.py
index 221f6ff8b92c6..d37acf48ed9c2 100644
--- a/pandas/core/ops.py
+++ b/pandas/core/ops.py
@@ -186,8 +186,10 @@ def add_special_arithmetic_methods(cls, arith_method=None,
arith_method : function (optional)
factory for special arithmetic methods, with op string:
f(op, name, str_rep, default_axis=None, fill_zeros=None, **eval_kwargs)
- comp_method : function, optional,
+ comp_method : function (optional)
factory for rich comparison - signature: f(op, name, str_rep)
+ bool_method : function (optional)
+ factory for boolean methods - signature: f(op, name, str_rep)
use_numexpr : bool, default True
whether to accelerate with numexpr, defaults to True
force : bool, default False
@@ -234,9 +236,16 @@ def f(self, other):
__isub__=_wrap_inplace_method(new_methods["__sub__"]),
__imul__=_wrap_inplace_method(new_methods["__mul__"]),
__itruediv__=_wrap_inplace_method(new_methods["__truediv__"]),
- __ipow__=_wrap_inplace_method(new_methods["__pow__"]), ))
+ __ifloordiv__=_wrap_inplace_method(new_methods["__floordiv__"]),
+ __imod__=_wrap_inplace_method(new_methods["__mod__"]),
+ __ipow__=_wrap_inplace_method(new_methods["__pow__"])))
if not compat.PY3:
- new_methods["__idiv__"] = new_methods["__div__"]
+ new_methods["__idiv__"] = _wrap_inplace_method(new_methods["__div__"])
+ if bool_method:
+ 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__"])))
add_methods(cls, new_methods=new_methods, force=force, select=select,
exclude=exclude)
diff --git a/pandas/tests/frame/test_operators.py b/pandas/tests/frame/test_operators.py
index 5052bef24e95a..53118ad79713a 100644
--- a/pandas/tests/frame/test_operators.py
+++ b/pandas/tests/frame/test_operators.py
@@ -1161,6 +1161,33 @@ def test_inplace_ops_identity(self):
assert_frame_equal(df2, expected)
assert df._data is df2._data
+ @pytest.mark.parametrize('op', ['add', 'and', 'div', 'floordiv', 'mod',
+ 'mul', 'or', 'pow', 'sub', 'truediv',
+ 'xor'])
+ def test_inplace_ops_identity2(self, op):
+
+ if compat.PY3 and op == 'div':
+ return
+
+ df = DataFrame({'a': [1., 2., 3.],
+ 'b': [1, 2, 3]})
+
+ operand = 2
+ if op in ('and', 'or', 'xor'):
+ # cannot use floats for boolean ops
+ df['a'] = [True, False, True]
+
+ df_copy = df.copy()
+ iop = '__i{}__'.format(op)
+ op = '__{}__'.format(op)
+
+ # no id change and value is correct
+ getattr(df, iop)(operand)
+ expected = getattr(df_copy, op)(operand)
+ assert_frame_equal(df, expected)
+ expected = id(df)
+ assert id(df) == expected
+
def test_alignment_non_pandas(self):
index = ['A', 'B', 'C']
columns = ['X', 'Y', 'Z']
| - [x] closes #12962
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatnew- just calls _wrap_inplace_method and extends test_inplace_ops_identity
| https://api.github.com/repos/pandas-dev/pandas/pulls/17589 | 2017-09-19T14:28:54Z | 2017-09-25T11:12:27Z | 2017-09-25T11:12:27Z | 2017-09-25T11:12:30Z |
COMPAT: pyarrow >= 0.7.0 compat | diff --git a/doc/source/io.rst b/doc/source/io.rst
index fcf7f6029197b..ab1ad74ee8516 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -4492,7 +4492,7 @@ Several caveats.
- The format will NOT write an ``Index``, or ``MultiIndex`` for the ``DataFrame`` and will raise an
error if a non-default one is provided. You can simply ``.reset_index(drop=True)`` in order to store the index.
- Duplicate column names and non-string columns names are not supported
-- Categorical dtypes are currently not-supported (for ``pyarrow``).
+- Categorical dtypes can be serialized to parquet, but will de-serialize as ``object`` dtype.
- Non supported types include ``Period`` and actual python object types. These will raise a helpful error message
on an attempt at serialization.
diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py
index 78c72e2a05566..2d69f6d38475e 100644
--- a/pandas/tests/io/test_parquet.py
+++ b/pandas/tests/io/test_parquet.py
@@ -2,11 +2,12 @@
import pytest
import datetime
+from distutils.version import LooseVersion
from warnings import catch_warnings
import numpy as np
import pandas as pd
-from pandas.compat import PY3, is_platform_windows
+from pandas.compat import PY3
from pandas.io.parquet import (to_parquet, read_parquet, get_engine,
PyArrowImpl, FastParquetImpl)
from pandas.util import testing as tm
@@ -42,8 +43,24 @@ def engine(request):
def pa():
if not _HAVE_PYARROW:
pytest.skip("pyarrow is not installed")
- if is_platform_windows():
- pytest.skip("pyarrow-parquet not building on windows")
+ return 'pyarrow'
+
+
+@pytest.fixture
+def pa_lt_070():
+ if not _HAVE_PYARROW:
+ pytest.skip("pyarrow is not installed")
+ if LooseVersion(pyarrow.__version__) >= '0.7.0':
+ pytest.skip("pyarrow is >= 0.7.0")
+ return 'pyarrow'
+
+
+@pytest.fixture
+def pa_ge_070():
+ if not _HAVE_PYARROW:
+ pytest.skip("pyarrow is not installed")
+ if LooseVersion(pyarrow.__version__) < '0.7.0':
+ pytest.skip("pyarrow is < 0.7.0")
return 'pyarrow'
@@ -302,10 +319,6 @@ def test_unsupported(self, pa):
df = pd.DataFrame({'a': pd.period_range('2013', freq='M', periods=3)})
self.check_error_on_write(df, pa, ValueError)
- # categorical
- df = pd.DataFrame({'a': pd.Categorical(list('abc'))})
- self.check_error_on_write(df, pa, NotImplementedError)
-
# timedelta
df = pd.DataFrame({'a': pd.timedelta_range('1 day',
periods=3)})
@@ -315,6 +328,23 @@ def test_unsupported(self, pa):
df = pd.DataFrame({'a': ['a', 1, 2.0]})
self.check_error_on_write(df, pa, ValueError)
+ def test_categorical(self, pa_ge_070):
+ pa = pa_ge_070
+
+ # supported in >= 0.7.0
+ df = pd.DataFrame({'a': pd.Categorical(list('abc'))})
+
+ # de-serialized as object
+ expected = df.assign(a=df.a.astype(object))
+ self.check_round_trip(df, pa, expected)
+
+ def test_categorical_unsupported(self, pa_lt_070):
+ pa = pa_lt_070
+
+ # supported in >= 0.7.0
+ df = pd.DataFrame({'a': pd.Categorical(list('abc'))})
+ self.check_error_on_write(df, pa, NotImplementedError)
+
class TestParquetFastParquet(Base):
| closes #17581
| https://api.github.com/repos/pandas-dev/pandas/pulls/17588 | 2017-09-19T10:01:34Z | 2017-09-19T11:47:37Z | 2017-09-19T11:47:37Z | 2017-09-19T13:15:24Z |
BUG:Time Grouper bug fix when applied for list groupers | diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index 1094e96bd0d20..3276310fa3e6e 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -704,6 +704,7 @@ Groupby/Resample/Rolling
- Bug in ``DataFrame.groupby`` where index and column keys were not recognized correctly when the number of keys equaled the number of elements on the groupby axis (:issue:`16859`)
- Bug in ``groupby.nunique()`` with ``TimeGrouper`` which cannot handle ``NaT`` correctly (:issue:`17575`)
- Bug in ``DataFrame.groupby`` where a single level selection from a ``MultiIndex`` unexpectedly sorts (:issue:`17537`)
+- Bug in ``TimeGrouper`` differs when passes as a list and as a scalar (:issue:`17530`)
Sparse
^^^^^^
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 2f2056279558d..9379ade4be7a6 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -256,11 +256,13 @@ def __init__(self, key=None, level=None, freq=None, axis=0, sort=False):
def ax(self):
return self.grouper
- def _get_grouper(self, obj):
+ def _get_grouper(self, obj, validate=True):
"""
Parameters
----------
obj : the subject object
+ validate : boolean, default True
+ if True, validate the grouper
Returns
-------
@@ -271,7 +273,8 @@ def _get_grouper(self, obj):
self.grouper, exclusions, self.obj = _get_grouper(self.obj, [self.key],
axis=self.axis,
level=self.level,
- sort=self.sort)
+ sort=self.sort,
+ validate=validate)
return self.binner, self.grouper, self.obj
def _set_grouper(self, obj, sort=False):
@@ -326,12 +329,6 @@ def _set_grouper(self, obj, sort=False):
self.grouper = ax
return self.grouper
- def _get_binner_for_grouping(self, obj):
- """ default to the standard binner here """
- group_axis = obj._get_axis(self.axis)
- return Grouping(group_axis, None, obj=obj, name=self.key,
- level=self.level, sort=self.sort, in_axis=False)
-
@property
def groups(self):
return self.grouper.groups
@@ -1733,16 +1730,34 @@ class BaseGrouper(object):
"""
This is an internal Grouper class, which actually holds
the generated groups
+
+ Parameters
+ ----------
+ axis : int
+ the axis to group
+ groupings : array of grouping
+ all the grouping instances to handle in this grouper
+ for example for grouper list to groupby, need to pass the list
+ sort : boolean, default True
+ whether this grouper will give sorted result or not
+ group_keys : boolean, default True
+ mutated : boolean, default False
+ indexer : intp array, optional
+ the indexer created by Grouper
+ some groupers (TimeGrouper) will sort its axis and its
+ group_info is also sorted, so need the indexer to reorder
+
"""
def __init__(self, axis, groupings, sort=True, group_keys=True,
- mutated=False):
+ mutated=False, indexer=None):
self._filter_empty_groups = self.compressed = len(groupings) != 1
self.axis = axis
self.groupings = groupings
self.sort = sort
self.group_keys = group_keys
self.mutated = mutated
+ self.indexer = indexer
@property
def shape(self):
@@ -1888,6 +1903,15 @@ def group_info(self):
comp_ids = _ensure_int64(comp_ids)
return comp_ids, obs_group_ids, ngroups
+ @cache_readonly
+ def label_info(self):
+ # return the labels of items in original grouped axis
+ labels, _, _ = self.group_info
+ if self.indexer is not None:
+ sorter = np.lexsort((labels, self.indexer))
+ labels = labels[sorter]
+ return labels
+
def _get_compressed_labels(self):
all_labels = [ping.labels for ping in self.groupings]
if len(all_labels) > 1:
@@ -2288,11 +2312,42 @@ def generate_bins_generic(values, binner, closed):
class BinGrouper(BaseGrouper):
- def __init__(self, bins, binlabels, filter_empty=False, mutated=False):
+ """
+ This is an internal Grouper class
+
+ Parameters
+ ----------
+ bins : the split index of binlabels to group the item of axis
+ binlabels : the label list
+ filter_empty : boolean, default False
+ mutated : boolean, default False
+ indexer : a intp array
+
+ Examples
+ --------
+ bins: [2, 4, 6, 8, 10]
+ binlabels: DatetimeIndex(['2005-01-01', '2005-01-03',
+ '2005-01-05', '2005-01-07', '2005-01-09'],
+ dtype='datetime64[ns]', freq='2D')
+
+ the group_info, which contains the label of each item in grouped
+ axis, the index of label in label list, group number, is
+
+ (array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4]), array([0, 1, 2, 3, 4]), 5)
+
+ means that, the grouped axis has 10 items, can be grouped into 5
+ labels, the first and second items belong to the first label, the
+ third and forth items belong to the second label, and so on
+
+ """
+
+ def __init__(self, bins, binlabels, filter_empty=False, mutated=False,
+ indexer=None):
self.bins = _ensure_int64(bins)
self.binlabels = _ensure_index(binlabels)
self._filter_empty_groups = filter_empty
self.mutated = mutated
+ self.indexer = indexer
@cache_readonly
def groups(self):
@@ -2460,6 +2515,19 @@ def __init__(self, index, grouper=None, obj=None, name=None, level=None,
self.grouper, self._labels, self._group_index = \
index._get_grouper_for_level(self.grouper, level)
+ # a passed Grouper like, directly get the grouper in the same way
+ # as single grouper groupby, use the group_info to get labels
+ elif isinstance(self.grouper, Grouper):
+ # get the new grouper; we already have disambiguated
+ # what key/level refer to exactly, don't need to
+ # check again as we have by this point converted these
+ # to an actual value (rather than a pd.Grouper)
+ _, grouper, _ = self.grouper._get_grouper(self.obj, validate=False)
+ if self.name is None:
+ self.name = grouper.result_index.name
+ self.obj = self.grouper.obj
+ self.grouper = grouper
+
else:
if self.grouper is None and self.name is not None:
self.grouper = self.obj[self.name]
@@ -2482,16 +2550,6 @@ def __init__(self, index, grouper=None, obj=None, name=None, level=None,
categories=c,
ordered=self.grouper.ordered))
- # a passed Grouper like
- elif isinstance(self.grouper, Grouper):
-
- # get the new grouper
- grouper = self.grouper._get_binner_for_grouping(self.obj)
- self.obj = self.grouper.obj
- self.grouper = grouper
- if self.name is None:
- self.name = grouper.name
-
# we are done
if isinstance(self.grouper, Grouping):
self.grouper = self.grouper.grouper
@@ -2536,6 +2594,10 @@ def ngroups(self):
@cache_readonly
def indices(self):
+ # we have a list of groupers
+ if isinstance(self.grouper, BaseGrouper):
+ return self.grouper.indices
+
values = _ensure_categorical(self.grouper)
return values._reverse_indexer()
@@ -2553,9 +2615,14 @@ def group_index(self):
def _make_labels(self):
if self._labels is None or self._group_index is None:
- labels, uniques = algorithms.factorize(
- self.grouper, sort=self.sort)
- uniques = Index(uniques, name=self.name)
+ # we have a list of groupers
+ if isinstance(self.grouper, BaseGrouper):
+ labels = self.grouper.label_info
+ uniques = self.grouper.result_index
+ else:
+ labels, uniques = algorithms.factorize(
+ self.grouper, sort=self.sort)
+ uniques = Index(uniques, name=self.name)
self._labels = labels
self._group_index = uniques
@@ -2566,7 +2633,7 @@ def groups(self):
def _get_grouper(obj, key=None, axis=0, level=None, sort=True,
- mutated=False):
+ mutated=False, validate=True):
"""
create and return a BaseGrouper, which is an internal
mapping of how to create the grouper indexers.
@@ -2583,6 +2650,8 @@ def _get_grouper(obj, key=None, axis=0, level=None, sort=True,
are and then creates a Grouping for each one, combined into
a BaseGrouper.
+ If validate, then check for key/level overlaps
+
"""
group_axis = obj._get_axis(axis)
@@ -2707,7 +2776,7 @@ def is_in_obj(gpr):
elif is_in_axis(gpr): # df.groupby('name')
if gpr in obj:
- if gpr in obj.index.names:
+ if validate and gpr in obj.index.names:
warnings.warn(
("'%s' is both a column name and an index level.\n"
"Defaulting to column but "
diff --git a/pandas/core/resample.py b/pandas/core/resample.py
index 083fbcaaabe46..6edbb99641542 100644
--- a/pandas/core/resample.py
+++ b/pandas/core/resample.py
@@ -250,7 +250,7 @@ def _get_binner(self):
"""
binner, bins, binlabels = self._get_binner_for_time()
- bin_grouper = BinGrouper(bins, binlabels)
+ bin_grouper = BinGrouper(bins, binlabels, indexer=self.groupby.indexer)
return binner, bin_grouper
def _assure_grouper(self):
@@ -1105,35 +1105,12 @@ def _get_resampler(self, obj, kind=None):
"TimedeltaIndex or PeriodIndex, "
"but got an instance of %r" % type(ax).__name__)
- def _get_grouper(self, obj):
+ def _get_grouper(self, obj, validate=True):
# create the resampler and return our binner
r = self._get_resampler(obj)
r._set_binner()
return r.binner, r.grouper, r.obj
- def _get_binner_for_grouping(self, obj):
- # return an ordering of the transformed group labels,
- # suitable for multi-grouping, e.g the labels for
- # the resampled intervals
- binner, grouper, obj = self._get_grouper(obj)
-
- l = []
- for key, group in grouper.get_iterator(self.ax):
- l.extend([key] * len(group))
-
- if isinstance(self.ax, PeriodIndex):
- grouper = binner.__class__(l, freq=binner.freq, name=binner.name)
- else:
- # resampling causes duplicated values, specifying freq is invalid
- grouper = binner.__class__(l, name=binner.name)
-
- # since we may have had to sort
- # may need to reorder groups here
- if self.indexer is not None:
- indexer = self.indexer.argsort(kind='quicksort')
- grouper = grouper.take(indexer)
- return grouper
-
def _get_time_bins(self, ax):
if not isinstance(ax, DatetimeIndex):
raise TypeError('axis must be a DatetimeIndex, but got '
diff --git a/pandas/tests/groupby/test_timegrouper.py b/pandas/tests/groupby/test_timegrouper.py
index fafcbf947e3df..c8503b16a0e16 100644
--- a/pandas/tests/groupby/test_timegrouper.py
+++ b/pandas/tests/groupby/test_timegrouper.py
@@ -623,3 +623,22 @@ def test_nunique_with_timegrouper_and_nat(self):
result = test.groupby(grouper)['data'].nunique()
expected = test[test.time.notnull()].groupby(grouper)['data'].nunique()
tm.assert_series_equal(result, expected)
+
+ def test_scalar_call_versus_list_call(self):
+ # Issue: 17530
+ data_frame = {
+ 'location': ['shanghai', 'beijing', 'shanghai'],
+ 'time': pd.Series(['2017-08-09 13:32:23', '2017-08-11 23:23:15',
+ '2017-08-11 22:23:15'],
+ dtype='datetime64[ns]'),
+ 'value': [1, 2, 3]
+ }
+ data_frame = pd.DataFrame(data_frame).set_index('time')
+ grouper = pd.Grouper(freq='D')
+
+ grouped = data_frame.groupby(grouper)
+ result = grouped.count()
+ grouped = data_frame.groupby([grouper])
+ expected = grouped.count()
+
+ assert_frame_equal(result, expected)
| - [x] closes #17530
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
* save the axis indexer for Base/BinGrouper. As BinGrouper has get the sorted labels, need to use indexer to reorder them into right place for unsorted axis values
* add label_info property to get unsorted labels
* enable Grouping to use Base/BinGrouper instance generated by _get_grouper. Get label_info and group_info to get right labels and label indexes from Base/BinGrouper instance
* add test for #17530
* add comment | https://api.github.com/repos/pandas-dev/pandas/pulls/17587 | 2017-09-19T03:23:13Z | 2017-10-01T17:48:57Z | 2017-10-01T17:48:57Z | 2017-10-06T06:36:03Z |
Allow for dict-like argument to Categorical.rename_categories | diff --git a/doc/source/categorical.rst b/doc/source/categorical.rst
index 65361886436d6..ff5e550ebd97f 100644
--- a/doc/source/categorical.rst
+++ b/doc/source/categorical.rst
@@ -206,6 +206,10 @@ by using the :func:`Categorical.rename_categories` method:
s.cat.categories = ["Group %s" % g for g in s.cat.categories]
s
s.cat.rename_categories([1,2,3])
+ s
+ # You can also pass a dict-like object to map the renaming
+ s.cat.rename_categories({1: 'x', 2: 'y', 3: 'z'})
+ s
.. note::
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index 5a353544a4283..f440ca6e82828 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -115,6 +115,7 @@ Other Enhancements
- :func:`DataFrame.items` and :func:`Series.items` is now present in both Python 2 and 3 and is lazy in all cases (:issue:`13918`, :issue:`17213`)
- :func:`Styler.where` has been implemented. It is as a convenience for :func:`Styler.applymap` and enables simple DataFrame styling on the Jupyter notebook (:issue:`17474`).
- :func:`MultiIndex.is_monotonic_decreasing` has been implemented. Previously returned ``False`` in all cases. (:issue:`16554`)
+- :func:`Categorical.rename_categories` now accepts a dict-like argument as `new_categories` and only updates the categories found in that dict. (:issue:`17336`)
.. _whatsnew_0210.api_breaking:
diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py
index ddca93f07ad5e..6f7eafe43dbbb 100644
--- a/pandas/core/categorical.py
+++ b/pandas/core/categorical.py
@@ -25,7 +25,8 @@
is_categorical_dtype,
is_integer_dtype, is_bool,
is_list_like, is_sequence,
- is_scalar)
+ is_scalar,
+ is_dict_like)
from pandas.core.common import is_null_slice, _maybe_box_datetimelike
from pandas.core.algorithms import factorize, take_1d, unique1d
@@ -792,19 +793,20 @@ def set_categories(self, new_categories, ordered=None, rename=False,
def rename_categories(self, new_categories, inplace=False):
""" Renames categories.
- The new categories has to be a list-like object. All items must be
- unique and the number of items in the new categories must be the same
- as the number of items in the old categories.
+ The new categories can be either a list-like dict-like object.
+ If it is list-like, all items must be unique and the number of items
+ in the new categories must be the same as the number of items in the
+ old categories.
Raises
------
ValueError
- If the new categories do not have the same number of items than the
- current categories or do not validate as categories
+ If new categories are list-like and do not have the same number of
+ items than the current categories or do not validate as categories
Parameters
----------
- new_categories : Index-like
+ new_categories : Index-like or dict-like (>=0.21.0)
The renamed categories.
inplace : boolean (default: False)
Whether or not to rename the categories inplace or return a copy of
@@ -824,7 +826,12 @@ def rename_categories(self, new_categories, inplace=False):
"""
inplace = validate_bool_kwarg(inplace, 'inplace')
cat = self if inplace else self.copy()
- cat.categories = new_categories
+
+ if is_dict_like(new_categories):
+ cat.categories = [new_categories.get(item, item)
+ for item in cat.categories]
+ else:
+ cat.categories = new_categories
if not inplace:
return cat
diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py
index c361b430cfd8a..e6fa5d1af55be 100644
--- a/pandas/tests/test_categorical.py
+++ b/pandas/tests/test_categorical.py
@@ -983,6 +983,40 @@ def test_rename_categories(self):
with pytest.raises(ValueError):
cat.rename_categories([1, 2])
+ def test_rename_categories_dict(self):
+ # GH 17336
+ cat = pd.Categorical(['a', 'b', 'c', 'd'])
+ res = cat.rename_categories({'a': 4, 'b': 3, 'c': 2, 'd': 1})
+ expected = Index([4, 3, 2, 1])
+ tm.assert_index_equal(res.categories, expected)
+
+ # Test for inplace
+ res = cat.rename_categories({'a': 4, 'b': 3, 'c': 2, 'd': 1},
+ inplace=True)
+ assert res is None
+ tm.assert_index_equal(cat.categories, expected)
+
+ # Test for dicts of smaller length
+ cat = pd.Categorical(['a', 'b', 'c', 'd'])
+ res = cat.rename_categories({'a': 1, 'c': 3})
+
+ expected = Index([1, 'b', 3, 'd'])
+ tm.assert_index_equal(res.categories, expected)
+
+ # Test for dicts with bigger length
+ cat = pd.Categorical(['a', 'b', 'c', 'd'])
+ res = cat.rename_categories({'a': 1, 'b': 2, 'c': 3,
+ 'd': 4, 'e': 5, 'f': 6})
+ expected = Index([1, 2, 3, 4])
+ tm.assert_index_equal(res.categories, expected)
+
+ # Test for dicts with no items from old categories
+ cat = pd.Categorical(['a', 'b', 'c', 'd'])
+ res = cat.rename_categories({'f': 1, 'g': 3})
+
+ expected = Index(['a', 'b', 'c', 'd'])
+ tm.assert_index_equal(res.categories, expected)
+
@pytest.mark.parametrize('codes, old, new, expected', [
([0, 1], ['a', 'b'], ['a', 'b'], [0, 1]),
([0, 1], ['b', 'a'], ['b', 'a'], [0, 1]),
| - [x] closes #17336
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
`Categorical.rename_categories` can now take a dict as `new_categories` and updates the categories to those found in the mapping.
It will only change the categories found in the dict, and leave all others the same.
The dict can be smaller or larger, and may or may not contain mappings referencing the old categories.
Have a good day/night! 🐼 🐍 | https://api.github.com/repos/pandas-dev/pandas/pulls/17586 | 2017-09-19T02:26:41Z | 2017-09-21T22:45:21Z | 2017-09-21T22:45:20Z | 2017-09-21T23:07:46Z |
Remove unused cimports | diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx
index 9500e685367c8..1cb7b18fa4f61 100644
--- a/pandas/_libs/groupby.pyx
+++ b/pandas/_libs/groupby.pyx
@@ -7,8 +7,6 @@ cimport cython
cnp.import_array()
-cimport util
-
from numpy cimport (ndarray,
double_t,
int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t,
diff --git a/pandas/_libs/join.pyx b/pandas/_libs/join.pyx
index 503bdda75875f..33c3650fa0425 100644
--- a/pandas/_libs/join.pyx
+++ b/pandas/_libs/join.pyx
@@ -8,8 +8,6 @@ from cython cimport Py_ssize_t
np.import_array()
-cimport util
-
from numpy cimport (ndarray,
int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t,
uint32_t, uint64_t, float16_t, float32_t, float64_t)
diff --git a/pandas/_libs/period.pyx b/pandas/_libs/period.pyx
index 49353f7b0491c..75164748128e2 100644
--- a/pandas/_libs/period.pyx
+++ b/pandas/_libs/period.pyx
@@ -27,13 +27,12 @@ from datetime cimport (
INT32_MIN)
-cimport util, lib
+cimport util
from util cimport is_period_object, is_string_object
-from lib cimport is_null_datetimelike, is_period
-from pandas._libs import tslib, lib
-from pandas._libs.tslib import (Timedelta, Timestamp, iNaT,
- NaT)
+from lib cimport is_null_datetimelike
+from pandas._libs import tslib
+from pandas._libs.tslib import Timestamp, iNaT, NaT
from tslibs.timezones cimport (
is_utc, is_tzlocal, get_utcoffset, _get_dst_info, maybe_get_tz)
from tslib cimport _nat_scalar_rules
@@ -485,7 +484,7 @@ def extract_freq(ndarray[object] values):
try:
# now Timestamp / NaT has freq attr
- if is_period(p):
+ if is_period_object(p):
return p.freq
except AttributeError:
pass
@@ -728,8 +727,7 @@ cdef class _Period(object):
return hash((self.ordinal, self.freqstr))
def _add_delta(self, other):
- if isinstance(other, (timedelta, np.timedelta64,
- offsets.Tick, Timedelta)):
+ if isinstance(other, (timedelta, np.timedelta64, offsets.Tick)):
offset = frequencies.to_offset(self.freq.rule_code)
if isinstance(offset, offsets.Tick):
nanos = tslib._delta_to_nanoseconds(other)
@@ -754,12 +752,11 @@ cdef class _Period(object):
def __add__(self, other):
if is_period_object(self):
if isinstance(other, (timedelta, np.timedelta64,
- offsets.DateOffset,
- Timedelta)):
+ offsets.DateOffset)):
return self._add_delta(other)
elif other is NaT:
return NaT
- elif lib.is_integer(other):
+ elif util.is_integer_object(other):
ordinal = self.ordinal + other * self.freq.n
return Period(ordinal=ordinal, freq=self.freq)
else: # pragma: no cover
@@ -772,11 +769,10 @@ cdef class _Period(object):
def __sub__(self, other):
if is_period_object(self):
if isinstance(other, (timedelta, np.timedelta64,
- offsets.DateOffset,
- Timedelta)):
+ offsets.DateOffset)):
neg_other = -other
return self + neg_other
- elif lib.is_integer(other):
+ elif util.is_integer_object(other):
ordinal = self.ordinal - other * self.freq.n
return Period(ordinal=ordinal, freq=self.freq)
elif is_period_object(other):
@@ -1159,7 +1155,7 @@ class Period(_Period):
raise ValueError(("Only value or ordinal but not both should be "
"given but not both"))
elif ordinal is not None:
- if not lib.is_integer(ordinal):
+ if not util.is_integer_object(ordinal):
raise ValueError("Ordinal must be an integer")
if freq is None:
raise ValueError('Must supply freq for ordinal value')
@@ -1196,8 +1192,8 @@ class Period(_Period):
elif is_null_datetimelike(value) or value in tslib._nat_strings:
ordinal = iNaT
- elif is_string_object(value) or lib.is_integer(value):
- if lib.is_integer(value):
+ elif is_string_object(value) or util.is_integer_object(value):
+ if util.is_integer_object(value):
value = str(value)
value = value.upper()
dt, _, reso = parse_time_string(value, freq)
diff --git a/pandas/_libs/reshape.pyx b/pandas/_libs/reshape.pyx
index d6996add374a9..db2e8b43d1ead 100644
--- a/pandas/_libs/reshape.pyx
+++ b/pandas/_libs/reshape.pyx
@@ -8,8 +8,6 @@ from cython cimport Py_ssize_t
np.import_array()
-cimport util
-
from numpy cimport (ndarray,
int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t,
uint32_t, uint64_t, float16_t, float32_t, float64_t)
diff --git a/pandas/_libs/src/offsets.pyx b/pandas/_libs/src/offsets.pyx
deleted file mode 100644
index c963e256d0aa5..0000000000000
--- a/pandas/_libs/src/offsets.pyx
+++ /dev/null
@@ -1,367 +0,0 @@
-
-ctypedef enum time_res:
- r_min = 0
- r_microsecond
- r_second
- r_minute
- r_hour
- r_day
- r_month
- r_year
- r_max = 98
- r_invalid = 99
-
-
-cdef conversion_factor(time_res res1, time_res res2):
- cdef:
- time_res min_res, max_res
- int64_t factor
-
- min_res = min(res1, res2)
- max_res = max(res1, res2)
- factor = 1
-
- if min_res == max_res:
- return factor
-
- while min_res < max_res:
- if min_res < r_microsecond:
- raise "Cannot convert from less than us"
- elif min_res == r_microsecond:
- factor *= 1000000
- min_res = r_second
- elif min_res == r_second:
- factor *= 60
- min_res = r_minute
- elif min_res == r_minute:
- factor *= 60
- min_res = r_hour
- elif min_res == r_hour:
- factor *= 24
- min_res = r_day
- else:
- raise "Cannot convert to month or year"
-
- return factor
-
-# Logic to generate ranges
-# -----------------------------------------------------------------------------
-
-cdef inline int64_t weekend_adjustment(int64_t dow, int bkwd):
- if dow > 4: # sat or sun?
- if bkwd: # roll back 1 or 2 days
- return (4 - dow)
- else: # roll forward 2 or 1 days
- return (7 - dow)
- return 0
-
-cdef int64_t us_in_day = conversion_factor(r_microsecond, r_day)
-
-cdef class _Offset:
- """
- Base class to generate timestamps. Set the anchor, and then move offsets
- with next & prev. Retrieve timestamp with ts attribute.
- """
- cdef:
- int64_t t, dow, biz, dayoffset
- object start
- _TSObject ts
-
- def __cinit__(self):
- self.t=0
- self.dow=0
- self.biz=0
- self.dayoffset=0
-
- cpdef anchor(self, object start=None):
- if start is not None:
- self.start = start
- self.ts = convert_to_tsobject(self.start, None, None)
- self._setup()
-
- cdef _setup(self):
- pass
-
- cpdef next(self):
- pass
-
- cpdef __next__(self):
- """wrapper around next"""
- return self.next()
-
- cpdef prev(self):
- pass
-
- cdef int64_t _ts(self):
- """
- Access the current timestamp value, with a possible weekday
- adjustment.
- """
- cdef int64_t adj
-
- if self.biz != 0:
- adj = weekend_adjustment(self.dow, self.biz < 0)
- return self.t + us_in_day * adj
- else:
- return self.t
-
- cdef int64_t _get_anchor(self):
- """
- Retrieve an anchor relating to current offset we're on.
- """
- return self.t - self.dayoffset * us_in_day
-
- property ts:
- def __get__(self):
- return self._ts()
-
-cdef class YearOffset(_Offset):
- """
- Generate annual timestamps from provided start time; apply dayoffset to
- each timestamp. If biz > 0, we choose the next business day at each time;
- previous if < 0.
-
- Parameters
- ----------
- dayoffset : int
- biz : int
- """
- cdef:
- int64_t y, ly
-
- def __init__(self, int64_t dayoffset=0, int64_t biz=0, object anchor=None):
- self.dayoffset = dayoffset
- self.biz = biz
-
- if anchor is not None:
- self.anchor(anchor)
-
- cdef _setup(self):
- cdef _TSObject ts = self.ts
-
- self.t = ts.value + self.dayoffset * us_in_day
- self.y = ts.dts.year
-
- self.ly = (ts.dts.month > 2 or
- ts.dts.month == 2 and ts.dts.day == 29)
-
- if self.biz != 0:
- self.dow = (ts_dayofweek(ts) + self.dayoffset) % 7
-
- cpdef next(self):
- cdef int64_t days
-
- days = 365 + is_leapyear(self.y + self.ly)
-
- self.t += days * us_in_day
- self.y += 1
-
- if self.biz != 0:
- self.dow = (self.dow + days) % 7
-
- cpdef prev(self):
- cdef int64_t days
-
- days = 365 + is_leapyear(self.y - (1 - self.ly))
-
- self.t -= days * us_in_day
- self.y -= 1
-
- if self.biz != 0:
- self.dow = (self.dow - days) % 7
-
-cdef class MonthOffset(_Offset):
- """
- Generate monthly timestamps from provided start time, and apply dayoffset
- to each timestamp. Stride to construct strided timestamps (eg quarterly).
- If biz > 0, we choose the next business day at each time; previous if < 0.
-
- Parameters
- ----------
- dayoffset : int
- stride : int, > 0
- biz : int
- """
- cdef:
- Py_ssize_t stride, ly, m
- int64_t y
-
- def __init__(self, int64_t dayoffset=0, Py_ssize_t stride=1,
- int64_t biz=0, object anchor=None):
- self.dayoffset = dayoffset
- self.stride = stride
- self.biz = biz
-
- if stride <= 0:
- raise ValueError("Stride must be positive")
-
- if anchor is not None:
- self.anchor(anchor)
-
- cdef _setup(self):
- cdef _TSObject ts = self.ts
-
- self.t = ts.value + (self.dayoffset * us_in_day)
-
- # for day counting
- self.m = ts.dts.month - 1
- self.y = ts.dts.year
- self.ly = is_leapyear(self.y)
-
- if self.biz != 0:
- self.dow = (ts_dayofweek(ts) + self.dayoffset) % 7
-
- cpdef next(self):
- cdef:
- int64_t tmp, days
- Py_ssize_t j
-
- days = 0
- for j in range(0, self.stride):
- if self.m >= 12:
- self.m -= 12
- self.y += 1
- self.ly = is_leapyear(self.y)
- days += days_per_month_table[self.ly][self.m]
- self.m += 1
-
- self.t += days * us_in_day
-
- if self.biz != 0:
- self.dow = (self.dow + days) % 7
-
- cpdef prev(self):
- cdef:
- int64_t tmp, days
- Py_ssize_t j
-
- days = 0
- for j in range(0, self.stride):
- self.m -= 1
- if self.m < 0:
- self.m += 12
- self.y -= 1
- self.ly = is_leapyear(self.y)
- days += days_per_month_table[self.ly][self.m]
-
- self.t -= days * us_in_day
-
- if self.biz != 0:
- self.dow = (self.dow - days) % 7
-
-cdef class DayOfMonthOffset(_Offset):
- """
- Generate relative monthly timestamps from month & year of provided start
- time. For example, fridays of the third week of each month (week=3, day=4);
- or, thursdays of the last week of each month (week=-1, day=3).
-
- Parameters
- ----------
- week : int
- day : int, 0 to 6
- """
- cdef:
- Py_ssize_t ly, m
- int64_t y, day, week
-
- def __init__(self, int64_t week=0, int64_t day=0, object anchor=None):
- self.week = week
- self.day = day
-
- if self.day < 0 or self.day > 6:
- raise ValueError("Day offset must be 0 to 6")
-
- if anchor is not None:
- self.anchor(anchor)
-
- cdef _setup(self):
- cdef _TSObject ts = self.ts
-
- # rewind to beginning of month
- self.t = ts.value - (ts.dts.day - 1) * us_in_day
- self.dow = dayofweek(ts.dts.year, ts.dts.month, 1)
-
- # for day counting
- self.m = ts.dts.month - 1
- self.y = ts.dts.year
- self.ly = is_leapyear(self.y)
-
- cpdef next(self):
- cdef:
- int64_t tmp, days
-
- days = days_per_month_table[self.ly][self.m]
- self.t += days * us_in_day
- self.dow = (self.dow + days) % 7
-
- self.m += 1
- if self.m >= 12:
- self.m -= 12
- self.y += 1
- self.ly = is_leapyear(self.y)
-
- cpdef prev(self):
- cdef:
- int64_t tmp, days
-
- days = days_per_month_table[self.ly][(self.m - 1) % 12]
- self.t -= days * us_in_day
- self.dow = (self.dow - days) % 7
-
- self.m -= 1
- if self.m < 0:
- self.m += 12
- self.y -= 1
- self.ly = is_leapyear(self.y)
-
- cdef int64_t _ts(self):
- """
- Overwrite default adjustment
- """
- cdef int64_t adj = (self.week * 7) + (self.day - self.dow) % 7
- return self.t + us_in_day * adj
-
-cdef class DayOffset(_Offset):
- """
- Generate daily timestamps beginning with first valid time >= start time. If
- biz != 0, we skip weekends. Stride, to construct weekly timestamps.
-
- Parameters
- ----------
- stride : int, > 0
- biz : boolean
- """
- cdef:
- Py_ssize_t stride
-
- def __init__(self, int64_t stride=1, int64_t biz=0, object anchor=None):
- self.stride = stride
- self.biz = biz
-
- if self.stride <= 0:
- raise ValueError("Stride must be positive")
-
- if anchor is not None:
- self.anchor(anchor)
-
- cdef _setup(self):
- cdef _TSObject ts = self.ts
- self.t = ts.value
- if self.biz != 0:
- self.dow = ts_dayofweek(ts)
-
- cpdef next(self):
- self.t += (self.stride * us_in_day)
- if self.biz != 0:
- self.dow = (self.dow + self.stride) % 7
- if self.dow >= 5:
- self.t += (7 - self.dow) * us_in_day
- self.dow = 0
-
- cpdef prev(self):
- self.t -= (self.stride * us_in_day)
- if self.biz != 0:
- self.dow = (self.dow - self.stride) % 7
- if self.dow >= 5:
- self.t += (4 - self.dow) * us_in_day
- self.dow = 4
diff --git a/setup.py b/setup.py
index d28c4ba8be5b0..555cf9dc4a9b3 100755
--- a/setup.py
+++ b/setup.py
@@ -512,7 +512,7 @@ def pxd(name):
'pxdfiles': ['_libs/src/util', '_libs/hashtable'],
'depends': _pxi_dep['join']},
'_libs.reshape': {'pyxfile': '_libs/reshape',
- 'depends': _pxi_dep['reshape']},
+ 'depends': _pxi_dep['reshape'], 'include': []},
'_libs.interval': {'pyxfile': '_libs/interval',
'pxdfiles': ['_libs/hashtable'],
'depends': _pxi_dep['interval']},
@@ -528,7 +528,7 @@ def pxd(name):
'pandas/_libs/src/parser/io.c']},
'_libs.sparse': {'pyxfile': '_libs/sparse',
'depends': (['pandas/_libs/sparse.pyx'] +
- _pxi_dep['sparse'])},
+ _pxi_dep['sparse']), 'include': []},
'_libs.testing': {'pyxfile': '_libs/testing',
'depends': ['pandas/_libs/testing.pyx']},
'_libs.hashing': {'pyxfile': '_libs/hashing',
| This helps a little bit with the complexity of the libs interdependencies.
Make properties.pyx its own module, since we will end up needing it to be separate when `tseries.offsets` gets moved into cython.
Remove the long-defunct _libs/src/offsets.pyx.
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17585 | 2017-09-19T00:51:30Z | 2017-09-23T19:44:53Z | 2017-09-23T19:44:53Z | 2017-10-30T16:23:29Z |
Remove experimental warning from custom offsets | diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py
index 6a518937b1195..452d30322b4cf 100644
--- a/pandas/tseries/offsets.py
+++ b/pandas/tseries/offsets.py
@@ -951,14 +951,9 @@ def next_bday(self):
class CustomBusinessDay(BusinessDay):
"""
- **EXPERIMENTAL** DateOffset subclass representing possibly n business days
+ DateOffset subclass representing possibly n custom business days,
excluding holidays
- .. warning:: EXPERIMENTAL
-
- This class is not officially supported and the API is likely to change
- in future versions. Use this at your own risk.
-
Parameters
----------
n : int, default 1
@@ -1405,12 +1400,8 @@ def onOffset(self, dt):
class CustomBusinessMonthEnd(BusinessMixin, MonthOffset):
"""
- **EXPERIMENTAL** DateOffset of one custom business month
-
- .. warning:: EXPERIMENTAL
-
- This class is not officially supported and the API is likely to change
- in future versions. Use this at your own risk.
+ DateOffset subclass representing one custom business month, incrementing
+ between end of month dates
Parameters
----------
@@ -1479,12 +1470,8 @@ def apply(self, other):
class CustomBusinessMonthBegin(BusinessMixin, MonthOffset):
"""
- **EXPERIMENTAL** DateOffset of one custom business month
-
- .. warning:: EXPERIMENTAL
-
- This class is not officially supported and the API is likely to change
- in future versions. Use this at your own risk.
+ DateOffset subclass representing one custom business month, incrementing
+ between beginning of month dates
Parameters
----------
| Per discussion here: https://github.com/pandas-dev/pandas/pull/17554#pullrequestreview-63229522
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
I edited the docstring descriptions slightly. Feel free to suggest cleaner descriptions, if my edits don't suffice. Should there be a whatsnew entry related to removing the experimental status?
| https://api.github.com/repos/pandas-dev/pandas/pulls/17584 | 2017-09-19T00:25:47Z | 2017-09-22T07:22:20Z | 2017-09-22T07:22:19Z | 2017-09-22T08:27:36Z |
DOC: Add a more welcoming tone for new contributors | diff --git a/doc/README.rst b/doc/README.rst
index 0ea3234dec348..b2c66611b68bb 100644
--- a/doc/README.rst
+++ b/doc/README.rst
@@ -3,9 +3,11 @@
Contributing to the documentation
=================================
-If you're not the developer type, contributing to the documentation is still
-of huge value. You don't even have to be an expert on
-*pandas* to do so! Something as simple as rewriting small passages for clarity
+Whether you are someone who loves writing, teaching, or development,
+contributing to the documentation is a huge value. If you don't see yourself
+as a developer type, please don't stress and know that we want you to
+contribute. You don't even have to be an expert on *pandas* to do so!
+Something as simple as rewriting small passages for clarity
as you reference the docs is a simple but effective way to contribute. The
next person to read that passage will be in your debt!
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index c808babeee5d9..74360f06bfd02 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -389,7 +389,7 @@ New Behavior:
---------------------------------------------------------------------------
ValueError: Of the three parameters: start, end, and periods, exactly two must be specified
- In [3]: pd.period_range(start='2017Q1', end='2017Q4', periods=6, freq='Q')
+ In [3]: pd.period_range(start='2017Q1', end='2017Q4', periods=6, freq='Q')
---------------------------------------------------------------------------
ValueError: Of the three parameters: start, end, and periods, exactly two must be specified
| - [x] closes #17579
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17580 | 2017-09-18T22:31:01Z | 2017-09-20T21:22:37Z | 2017-09-20T21:22:37Z | 2017-09-20T21:32:40Z |
BUG: Fix make_sparse mask generation | diff --git a/asv_bench/benchmarks/sparse.py b/asv_bench/benchmarks/sparse.py
index b958f5e0e5c34..a46205026481e 100644
--- a/asv_bench/benchmarks/sparse.py
+++ b/asv_bench/benchmarks/sparse.py
@@ -2,7 +2,7 @@
from .pandas_vb_common import *
import scipy.sparse
-from pandas import SparseSeries, SparseDataFrame
+from pandas import SparseSeries, SparseDataFrame, SparseArray
class sparse_series_to_frame(object):
@@ -23,6 +23,69 @@ def time_sparse_series_to_frame(self):
SparseDataFrame(self.series)
+class sparse_array_constructor(object):
+ goal_time = 0.2
+
+ def setup(self):
+ np.random.seed(1)
+ self.int64_10percent = self.make_numeric_array(length=1000000, dense_size=100000, fill_value=0, dtype=np.int64)
+ self.int64_1percent = self.make_numeric_array(length=1000000, dense_size=10000, fill_value=0, dtype=np.int64)
+
+ self.float64_10percent = self.make_numeric_array(length=1000000, dense_size=100000, fill_value=np.nan, dtype=np.float64)
+ self.float64_1percent = self.make_numeric_array(length=1000000, dense_size=10000, fill_value=np.nan, dtype=np.float64)
+
+ self.object_nan_fill_value_10percent = self.make_object_array(length=1000000, dense_size=100000, fill_value=np.nan)
+ self.object_nan_fill_value_1percent = self.make_object_array(length=1000000, dense_size=10000, fill_value=np.nan)
+
+ self.object_non_nan_fill_value_10percent = self.make_object_array(length=1000000, dense_size=100000, fill_value=0)
+ self.object_non_nan_fill_value_1percent = self.make_object_array(length=1000000, dense_size=10000, fill_value=0)
+
+ def make_numeric_array(self, length, dense_size, fill_value, dtype):
+ arr = np.array([fill_value] * length, dtype=dtype)
+ indexer = np.unique(np.random.randint(0, length, dense_size))
+ arr[indexer] = np.random.randint(0, 100, len(indexer))
+ return (arr, fill_value, dtype)
+
+ def make_object_array(self, length, dense_size, fill_value):
+ elems = np.array(['a', 0.0, False, 1, 2], dtype=np.object)
+ arr = np.array([fill_value] * length, dtype=np.object)
+ indexer = np.unique(np.random.randint(0, length, dense_size))
+ arr[indexer] = np.random.choice(elems, len(indexer))
+ return (arr, fill_value, np.object)
+
+ def time_sparse_array_constructor_int64_10percent(self):
+ arr, fill_value, dtype = self.int64_10percent
+ SparseArray(arr, fill_value=fill_value, dtype=dtype)
+
+ def time_sparse_array_constructor_int64_1percent(self):
+ arr, fill_value, dtype = self.int64_1percent
+ SparseArray(arr, fill_value=fill_value, dtype=dtype)
+
+ def time_sparse_array_constructor_float64_10percent(self):
+ arr, fill_value, dtype = self.float64_10percent
+ SparseArray(arr, fill_value=fill_value, dtype=dtype)
+
+ def time_sparse_array_constructor_float64_1percent(self):
+ arr, fill_value, dtype = self.float64_1percent
+ SparseArray(arr, fill_value=fill_value, dtype=dtype)
+
+ def time_sparse_array_constructor_object_nan_fill_value_10percent(self):
+ arr, fill_value, dtype = self.object_nan_fill_value_10percent
+ SparseArray(arr, fill_value=fill_value, dtype=dtype)
+
+ def time_sparse_array_constructor_object_nan_fill_value_1percent(self):
+ arr, fill_value, dtype = self.object_nan_fill_value_1percent
+ SparseArray(arr, fill_value=fill_value, dtype=dtype)
+
+ def time_sparse_array_constructor_object_non_nan_fill_value_10percent(self):
+ arr, fill_value, dtype = self.object_non_nan_fill_value_10percent
+ SparseArray(arr, fill_value=fill_value, dtype=dtype)
+
+ def time_sparse_array_constructor_object_non_nan_fill_value_1percent(self):
+ arr, fill_value, dtype = self.object_non_nan_fill_value_1percent
+ SparseArray(arr, fill_value=fill_value, dtype=dtype)
+
+
class sparse_frame_constructor(object):
goal_time = 0.2
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index 06f19782682b0..54d0489753ffb 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -608,6 +608,7 @@ Sparse
- Bug in ``SparseSeries`` raises ``AttributeError`` when a dictionary is passed in as data (:issue:`16905`)
- Bug in :func:`SparseDataFrame.fillna` not filling all NaNs when frame was instantiated from SciPy sparse matrix (:issue:`16112`)
- Bug in :func:`SparseSeries.unstack` and :func:`SparseDataFrame.stack` (:issue:`16614`, :issue:`15045`)
+- Bug in :func:`make_sparse` treating two numeric/boolean data, which have same bits, as same when array ``dtype`` is ``object`` (:issue:`17574`)
Reshaping
^^^^^^^^^
diff --git a/pandas/_libs/sparse.pyx b/pandas/_libs/sparse.pyx
index 1cc7f5ace95ea..fac678e531c8b 100644
--- a/pandas/_libs/sparse.pyx
+++ b/pandas/_libs/sparse.pyx
@@ -848,3 +848,22 @@ def reindex_integer(ndarray[float64_t, ndim=1] values,
IntIndex sparse_index,
ndarray[int32_t, ndim=1] indexer):
pass
+
+
+# -----------------------------------------------------------------------------
+# SparseArray mask create operations
+
+def make_mask_object_ndarray(ndarray[object, ndim=1] arr, object fill_value):
+ cdef object value
+ cdef Py_ssize_t i
+ cdef Py_ssize_t new_length = len(arr)
+ cdef ndarray[int8_t, ndim=1] mask
+
+ mask = np.ones(new_length, dtype=np.int8)
+
+ for i in range(new_length):
+ value = arr[i]
+ if value == fill_value and type(value) == type(fill_value):
+ mask[i] = 0
+
+ return mask.view(dtype=np.bool)
diff --git a/pandas/core/sparse/array.py b/pandas/core/sparse/array.py
index f965c91999a03..3b45a013734c9 100644
--- a/pandas/core/sparse/array.py
+++ b/pandas/core/sparse/array.py
@@ -19,6 +19,7 @@
from pandas.core.dtypes.common import (
_ensure_platform_int,
is_float, is_integer,
+ is_object_dtype,
is_integer_dtype,
is_bool_dtype,
is_list_like,
@@ -789,7 +790,13 @@ def make_sparse(arr, kind='block', fill_value=None):
if is_string_dtype(arr):
arr = arr.astype(object)
- mask = arr != fill_value
+ if is_object_dtype(arr.dtype):
+ # element-wise equality check method in numpy doesn't treat
+ # each element type, eg. 0, 0.0, and False are treated as
+ # same. So we have to check the both of its type and value.
+ mask = splib.make_mask_object_ndarray(arr, fill_value)
+ else:
+ mask = arr != fill_value
length = len(arr)
if length != mask.size:
diff --git a/pandas/tests/sparse/test_array.py b/pandas/tests/sparse/test_array.py
index b0a9182a265fe..f653ee50982ad 100644
--- a/pandas/tests/sparse/test_array.py
+++ b/pandas/tests/sparse/test_array.py
@@ -61,6 +61,15 @@ def test_constructor_object_dtype(self):
assert arr.dtype == np.object
assert arr.fill_value == 'A'
+ # GH 17574
+ data = [False, 0, 100.0, 0.0]
+ arr = SparseArray(data, dtype=np.object, fill_value=False)
+ assert arr.dtype == np.object
+ assert arr.fill_value is False
+ arr_expected = np.array(data, dtype=np.object)
+ it = (type(x) == type(y) and x == y for x, y in zip(arr, arr_expected))
+ assert np.fromiter(it, dtype=np.bool).all()
+
def test_constructor_spindex_dtype(self):
arr = SparseArray(data=[1, 2], sparse_index=IntIndex(4, [1, 2]))
tm.assert_sp_array_equal(arr, SparseArray([np.nan, 1, 2, np.nan]))
| - [x] closes #xxxx
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
This is the part of https://github.com/pandas-dev/pandas/pull/17386.
The mask generation sequence in `make_sparse` treated two data, which have same bits, as same if array is `dtype=object`.
This bug made `SparseArray([False, 0, 100.0, 0.0], fill_value=False, dtype=np.object)` is evaluated as `[False, False, 100.0, False]` | https://api.github.com/repos/pandas-dev/pandas/pulls/17574 | 2017-09-18T15:54:19Z | 2017-09-28T14:11:26Z | 2017-09-28T14:11:26Z | 2017-09-28T14:11:34Z |
BUG: Add SparseArray.all | diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index 50f11c38bae23..4a90e3b9073c1 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -633,6 +633,7 @@ Sparse
- Bug in :func:`SparseDataFrame.fillna` not filling all NaNs when frame was instantiated from SciPy sparse matrix (:issue:`16112`)
- Bug in :func:`SparseSeries.unstack` and :func:`SparseDataFrame.stack` (:issue:`16614`, :issue:`15045`)
- Bug in :func:`make_sparse` treating two numeric/boolean data, which have same bits, as same when array ``dtype`` is ``object`` (:issue:`17574`)
+- :func:`SparseArray.all` and :func:`SparseArray.any` are now implemented to handle ``SparseArray``, these were used but not implemented (:issue:`17570`)
Reshaping
^^^^^^^^^
diff --git a/pandas/compat/numpy/function.py b/pandas/compat/numpy/function.py
index ccbd3d9704e0c..d42be56963569 100644
--- a/pandas/compat/numpy/function.py
+++ b/pandas/compat/numpy/function.py
@@ -184,6 +184,14 @@ def validate_cum_func_with_skipna(skipna, args, kwargs, name):
return skipna
+ALLANY_DEFAULTS = OrderedDict()
+ALLANY_DEFAULTS['dtype'] = None
+ALLANY_DEFAULTS['out'] = None
+validate_all = CompatValidator(ALLANY_DEFAULTS, fname='all',
+ method='both', max_fname_arg_count=1)
+validate_any = CompatValidator(ALLANY_DEFAULTS, fname='any',
+ method='both', max_fname_arg_count=1)
+
LOGICAL_FUNC_DEFAULTS = dict(out=None)
validate_logical_func = CompatValidator(LOGICAL_FUNC_DEFAULTS, method='kwargs')
diff --git a/pandas/core/sparse/array.py b/pandas/core/sparse/array.py
index 3b45a013734c9..0424ac8703e25 100644
--- a/pandas/core/sparse/array.py
+++ b/pandas/core/sparse/array.py
@@ -615,6 +615,48 @@ def fillna(self, value, downcast=None):
return self._simple_new(new_values, self.sp_index,
fill_value=fill_value)
+ def all(self, axis=0, *args, **kwargs):
+ """
+ Tests whether all elements evaluate True
+
+ Returns
+ -------
+ all : bool
+
+ See Also
+ --------
+ numpy.all
+ """
+ nv.validate_all(args, kwargs)
+
+ values = self.sp_values
+
+ if len(values) != len(self) and not np.all(self.fill_value):
+ return False
+
+ return values.all()
+
+ def any(self, axis=0, *args, **kwargs):
+ """
+ Tests whether at least one of elements evaluate True
+
+ Returns
+ -------
+ any : bool
+
+ See Also
+ --------
+ numpy.any
+ """
+ nv.validate_any(args, kwargs)
+
+ values = self.sp_values
+
+ if len(values) != len(self) and np.any(self.fill_value):
+ return True
+
+ return values.any()
+
def sum(self, axis=0, *args, **kwargs):
"""
Sum of non-NA/null values
diff --git a/pandas/tests/sparse/test_array.py b/pandas/tests/sparse/test_array.py
index f653ee50982ad..8de93ff320961 100644
--- a/pandas/tests/sparse/test_array.py
+++ b/pandas/tests/sparse/test_array.py
@@ -664,6 +664,94 @@ def test_fillna_overlap(self):
class TestSparseArrayAnalytics(object):
+ @pytest.mark.parametrize('data,pos,neg', [
+ ([True, True, True], True, False),
+ ([1, 2, 1], 1, 0),
+ ([1.0, 2.0, 1.0], 1.0, 0.0)
+ ])
+ def test_all(self, data, pos, neg):
+ # GH 17570
+ out = SparseArray(data).all()
+ assert out
+
+ out = SparseArray(data, fill_value=pos).all()
+ assert out
+
+ data[1] = neg
+ out = SparseArray(data).all()
+ assert not out
+
+ out = SparseArray(data, fill_value=pos).all()
+ assert not out
+
+ @pytest.mark.parametrize('data,pos,neg', [
+ ([True, True, True], True, False),
+ ([1, 2, 1], 1, 0),
+ ([1.0, 2.0, 1.0], 1.0, 0.0)
+ ])
+ def test_numpy_all(self, data, pos, neg):
+ # GH 17570
+ out = np.all(SparseArray(data))
+ assert out
+
+ out = np.all(SparseArray(data, fill_value=pos))
+ assert out
+
+ data[1] = neg
+ out = np.all(SparseArray(data))
+ assert not out
+
+ out = np.all(SparseArray(data, fill_value=pos))
+ assert not out
+
+ msg = "the 'out' parameter is not supported"
+ tm.assert_raises_regex(ValueError, msg, np.all,
+ SparseArray(data), out=out)
+
+ @pytest.mark.parametrize('data,pos,neg', [
+ ([False, True, False], True, False),
+ ([0, 2, 0], 2, 0),
+ ([0.0, 2.0, 0.0], 2.0, 0.0)
+ ])
+ def test_any(self, data, pos, neg):
+ # GH 17570
+ out = SparseArray(data).any()
+ assert out
+
+ out = SparseArray(data, fill_value=pos).any()
+ assert out
+
+ data[1] = neg
+ out = SparseArray(data).any()
+ assert not out
+
+ out = SparseArray(data, fill_value=pos).any()
+ assert not out
+
+ @pytest.mark.parametrize('data,pos,neg', [
+ ([False, True, False], True, False),
+ ([0, 2, 0], 2, 0),
+ ([0.0, 2.0, 0.0], 2.0, 0.0)
+ ])
+ def test_numpy_any(self, data, pos, neg):
+ # GH 17570
+ out = np.any(SparseArray(data))
+ assert out
+
+ out = np.any(SparseArray(data, fill_value=pos))
+ assert out
+
+ data[1] = neg
+ out = np.any(SparseArray(data))
+ assert not out
+
+ out = np.any(SparseArray(data, fill_value=pos))
+ assert not out
+
+ msg = "the 'out' parameter is not supported"
+ tm.assert_raises_regex(ValueError, msg, np.any,
+ SparseArray(data), out=out)
+
def test_sum(self):
data = np.arange(10).astype(float)
out = SparseArray(data).sum()
| - [x] closes #xxxx
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
This is the part of https://github.com/pandas-dev/pandas/pull/17386.
`Block.where` uses `ndarray.all`, but there is no such method in `SparseArray`.
This makes that `all` evaluates `SparseArray([False, False, True])` as `True`.
https://github.com/pandas-dev/pandas/blob/master/pandas/core/internals.py#L1400 | https://api.github.com/repos/pandas-dev/pandas/pulls/17570 | 2017-09-18T11:44:50Z | 2017-09-28T23:44:30Z | 2017-09-28T23:44:30Z | 2017-09-28T23:44:34Z |
TST: Add tests for sparse quantile/where | diff --git a/pandas/tests/sparse/test_frame.py b/pandas/tests/sparse/test_frame.py
index ef94e2f78278d..e65059156c5b9 100644
--- a/pandas/tests/sparse/test_frame.py
+++ b/pandas/tests/sparse/test_frame.py
@@ -1398,3 +1398,139 @@ def test_numpy_func_call(self):
'std', 'min', 'max']
for func in funcs:
getattr(np, func)(self.frame)
+
+ @pytest.mark.parametrize('data', [
+ [[1, 1], [2, 2], [3, 3], [4, 4], [0, 0]],
+ [[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0], [nan, nan]],
+ [
+ [1.0, 1.0 + 1.0j],
+ [2.0 + 2.0j, 2.0],
+ [3.0, 3.0 + 3.0j],
+ [4.0 + 4.0j, 4.0],
+ [nan, nan]
+ ]
+ ])
+ @pytest.mark.xfail(reason='Wrong SparseBlock initialization '
+ '(GH 17386)')
+ def test_where_with_numeric_data(self, data):
+ # GH 17386
+ lower_bound = 1.5
+
+ sparse = SparseDataFrame(data)
+ result = sparse.where(sparse > lower_bound)
+
+ dense = DataFrame(data)
+ dense_expected = dense.where(dense > lower_bound)
+ sparse_expected = SparseDataFrame(dense_expected)
+
+ tm.assert_frame_equal(result, dense_expected)
+ tm.assert_sp_frame_equal(result, sparse_expected)
+
+ @pytest.mark.parametrize('data', [
+ [[1, 1], [2, 2], [3, 3], [4, 4], [0, 0]],
+ [[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0], [nan, nan]],
+ [
+ [1.0, 1.0 + 1.0j],
+ [2.0 + 2.0j, 2.0],
+ [3.0, 3.0 + 3.0j],
+ [4.0 + 4.0j, 4.0],
+ [nan, nan]
+ ]
+ ])
+ @pytest.mark.parametrize('other', [
+ True,
+ -100,
+ 0.1,
+ 100.0 + 100.0j
+ ])
+ @pytest.mark.xfail(reason='Wrong SparseBlock initialization '
+ '(GH 17386)')
+ def test_where_with_numeric_data_and_other(self, data, other):
+ # GH 17386
+ lower_bound = 1.5
+
+ sparse = SparseDataFrame(data)
+ result = sparse.where(sparse > lower_bound, other)
+
+ dense = DataFrame(data)
+ dense_expected = dense.where(dense > lower_bound, other)
+ sparse_expected = SparseDataFrame(dense_expected,
+ default_fill_value=other)
+
+ tm.assert_frame_equal(result, dense_expected)
+ tm.assert_sp_frame_equal(result, sparse_expected)
+
+ @pytest.mark.xfail(reason='Wrong SparseBlock initialization '
+ '(GH 17386)')
+ def test_where_with_bool_data(self):
+ # GH 17386
+ data = [[False, False], [True, True], [False, False]]
+ cond = True
+
+ sparse = SparseDataFrame(data)
+ result = sparse.where(sparse == cond)
+
+ dense = DataFrame(data)
+ dense_expected = dense.where(dense == cond)
+ sparse_expected = SparseDataFrame(dense_expected)
+
+ tm.assert_frame_equal(result, dense_expected)
+ tm.assert_sp_frame_equal(result, sparse_expected)
+
+ @pytest.mark.parametrize('other', [
+ True,
+ 0,
+ 0.1,
+ 100.0 + 100.0j
+ ])
+ @pytest.mark.xfail(reason='Wrong SparseBlock initialization '
+ '(GH 17386)')
+ def test_where_with_bool_data_and_other(self, other):
+ # GH 17386
+ data = [[False, False], [True, True], [False, False]]
+ cond = True
+
+ sparse = SparseDataFrame(data)
+ result = sparse.where(sparse == cond, other)
+
+ dense = DataFrame(data)
+ dense_expected = dense.where(dense == cond, other)
+ sparse_expected = SparseDataFrame(dense_expected,
+ default_fill_value=other)
+
+ tm.assert_frame_equal(result, dense_expected)
+ tm.assert_sp_frame_equal(result, sparse_expected)
+
+ @pytest.mark.xfail(reason='Wrong SparseBlock initialization '
+ '(GH 17386)')
+ def test_quantile(self):
+ # GH 17386
+ data = [[1, 1], [2, 10], [3, 100], [nan, nan]]
+ q = 0.1
+
+ sparse_df = SparseDataFrame(data)
+ result = sparse_df.quantile(q)
+
+ dense_df = DataFrame(data)
+ dense_expected = dense_df.quantile(q)
+ sparse_expected = SparseSeries(dense_expected)
+
+ tm.assert_series_equal(result, dense_expected)
+ tm.assert_sp_series_equal(result, sparse_expected)
+
+ @pytest.mark.xfail(reason='Wrong SparseBlock initialization '
+ '(GH 17386)')
+ def test_quantile_multi(self):
+ # GH 17386
+ data = [[1, 1], [2, 10], [3, 100], [nan, nan]]
+ q = [0.1, 0.5]
+
+ sparse_df = SparseDataFrame(data)
+ result = sparse_df.quantile(q)
+
+ dense_df = DataFrame(data)
+ dense_expected = dense_df.quantile(q)
+ sparse_expected = SparseDataFrame(dense_expected)
+
+ tm.assert_frame_equal(result, dense_expected)
+ tm.assert_sp_frame_equal(result, sparse_expected)
diff --git a/pandas/tests/sparse/test_series.py b/pandas/tests/sparse/test_series.py
index df1badb860d6d..1dc1c7f1575cc 100644
--- a/pandas/tests/sparse/test_series.py
+++ b/pandas/tests/sparse/test_series.py
@@ -1419,6 +1419,108 @@ def test_deprecated_reindex_axis(self):
self.bseries.reindex_axis([0, 1, 2])
assert 'reindex' in str(m[0].message)
+ @pytest.mark.parametrize('data', [
+ [1, 1, 2, 2, 3, 3, 4, 4, 0, 0],
+ [1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0, nan, nan],
+ [
+ 1.0, 1.0 + 1.0j,
+ 2.0 + 2.0j, 2.0,
+ 3.0, 3.0 + 3.0j,
+ 4.0 + 4.0j, 4.0,
+ nan, nan
+ ]
+ ])
+ @pytest.mark.xfail(reason='Wrong SparseBlock initialization '
+ '(GH 17386)')
+ def test_where_with_numeric_data(self, data):
+ # GH 17386
+ lower_bound = 1.5
+
+ sparse = SparseSeries(data)
+ result = sparse.where(sparse > lower_bound)
+
+ dense = Series(data)
+ dense_expected = dense.where(dense > lower_bound)
+ sparse_expected = SparseSeries(dense_expected)
+
+ tm.assert_series_equal(result, dense_expected)
+ tm.assert_sp_series_equal(result, sparse_expected)
+
+ @pytest.mark.parametrize('data', [
+ [1, 1, 2, 2, 3, 3, 4, 4, 0, 0],
+ [1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0, nan, nan],
+ [
+ 1.0, 1.0 + 1.0j,
+ 2.0 + 2.0j, 2.0,
+ 3.0, 3.0 + 3.0j,
+ 4.0 + 4.0j, 4.0,
+ nan, nan
+ ]
+ ])
+ @pytest.mark.parametrize('other', [
+ True,
+ -100,
+ 0.1,
+ 100.0 + 100.0j
+ ])
+ @pytest.mark.skip(reason='Wrong SparseBlock initialization '
+ '(Segfault) '
+ '(GH 17386)')
+ def test_where_with_numeric_data_and_other(self, data, other):
+ # GH 17386
+ lower_bound = 1.5
+
+ sparse = SparseSeries(data)
+ result = sparse.where(sparse > lower_bound, other)
+
+ dense = Series(data)
+ dense_expected = dense.where(dense > lower_bound, other)
+ sparse_expected = SparseSeries(dense_expected, fill_value=other)
+
+ tm.assert_series_equal(result, dense_expected)
+ tm.assert_sp_series_equal(result, sparse_expected)
+
+ @pytest.mark.xfail(reason='Wrong SparseBlock initialization '
+ '(GH 17386)')
+ def test_where_with_bool_data(self):
+ # GH 17386
+ data = [False, False, True, True, False, False]
+ cond = True
+
+ sparse = SparseSeries(data)
+ result = sparse.where(sparse == cond)
+
+ dense = Series(data)
+ dense_expected = dense.where(dense == cond)
+ sparse_expected = SparseSeries(dense_expected)
+
+ tm.assert_series_equal(result, dense_expected)
+ tm.assert_sp_series_equal(result, sparse_expected)
+
+ @pytest.mark.parametrize('other', [
+ True,
+ 0,
+ 0.1,
+ 100.0 + 100.0j
+ ])
+ @pytest.mark.skip(reason='Wrong SparseBlock initialization '
+ '(Segfault) '
+ '(GH 17386)')
+ def test_where_with_bool_data_and_other(self, other):
+ # GH 17386
+ data = [False, False, True, True, False, False]
+ cond = True
+
+ sparse = SparseSeries(data)
+ result = sparse.where(sparse == cond, other)
+
+ dense = Series(data)
+ dense_expected = dense.where(dense == cond, other)
+ sparse_expected = SparseSeries(dense_expected, fill_value=other)
+
+ tm.assert_series_equal(result, dense_expected)
+ tm.assert_sp_series_equal(result, sparse_expected)
+
@pytest.mark.parametrize(
'datetime_type', (np.datetime64,
| - [x] closes #xxxx
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
This is the part of https://github.com/pandas-dev/pandas/pull/17386. | https://api.github.com/repos/pandas-dev/pandas/pulls/17568 | 2017-09-18T10:34:15Z | 2017-10-31T01:29:59Z | 2017-10-31T01:29:59Z | 2017-10-31T01:30:10Z |
Revert "Remove pyx dependencies from setup (#17478)" | diff --git a/setup.py b/setup.py
index 664478cc35845..0e4e22b875e1d 100755
--- a/setup.py
+++ b/setup.py
@@ -348,6 +348,14 @@ class CheckSDist(sdist_class):
def initialize_options(self):
sdist_class.initialize_options(self)
+ '''
+ self._pyxfiles = []
+ for root, dirs, files in os.walk('pandas'):
+ for f in files:
+ if f.endswith('.pyx'):
+ self._pyxfiles.append(pjoin(root, f))
+ '''
+
def run(self):
if 'cython' in cmdclass:
self.run_command('cython')
@@ -471,10 +479,11 @@ def pxd(name):
'_libs.lib': {'pyxfile': '_libs/lib',
'depends': lib_depends + tseries_depends},
'_libs.hashtable': {'pyxfile': '_libs/hashtable',
+ 'pxdfiles': ['_libs/hashtable'],
'depends': (['pandas/_libs/src/klib/khash_python.h']
+ _pxi_dep['hashtable'])},
'_libs.tslib': {'pyxfile': '_libs/tslib',
- 'pxdfiles': ['_libs/src/util'],
+ 'pxdfiles': ['_libs/src/util', '_libs/lib'],
'depends': tseries_depends,
'sources': ['pandas/_libs/src/datetime/np_datetime.c',
'pandas/_libs/src/datetime/np_datetime_strings.c']},
@@ -490,20 +499,21 @@ def pxd(name):
'_libs.index': {'pyxfile': '_libs/index',
'sources': ['pandas/_libs/src/datetime/np_datetime.c',
'pandas/_libs/src/datetime/np_datetime_strings.c'],
- 'pxdfiles': ['_libs/src/util'],
+ 'pxdfiles': ['_libs/src/util', '_libs/hashtable'],
'depends': _pxi_dep['index']},
'_libs.algos': {'pyxfile': '_libs/algos',
- 'pxdfiles': ['_libs/src/util'],
+ 'pxdfiles': ['_libs/src/util', '_libs/algos', '_libs/hashtable'],
'depends': _pxi_dep['algos']},
'_libs.groupby': {'pyxfile': '_libs/groupby',
- 'pxdfiles': ['_libs/src/util'],
- 'depends': _pxi_dep['groupby']},
+ 'pxdfiles': ['_libs/src/util', '_libs/algos'],
+ 'depends': _pxi_dep['groupby']},
'_libs.join': {'pyxfile': '_libs/join',
- 'pxdfiles': ['_libs/src/util'],
+ 'pxdfiles': ['_libs/src/util', '_libs/hashtable'],
'depends': _pxi_dep['join']},
'_libs.reshape': {'pyxfile': '_libs/reshape',
'depends': _pxi_dep['reshape']},
'_libs.interval': {'pyxfile': '_libs/interval',
+ 'pxdfiles': ['_libs/hashtable'],
'depends': _pxi_dep['interval']},
'_libs.window': {'pyxfile': '_libs/window',
'pxdfiles': ['_libs/src/skiplist', '_libs/src/util'],
@@ -516,9 +526,12 @@ def pxd(name):
'sources': ['pandas/_libs/src/parser/tokenizer.c',
'pandas/_libs/src/parser/io.c']},
'_libs.sparse': {'pyxfile': '_libs/sparse',
- 'depends': _pxi_dep['sparse']},
- '_libs.testing': {'pyxfile': '_libs/testing'},
- '_libs.hashing': {'pyxfile': '_libs/hashing'},
+ 'depends': (['pandas/_libs/sparse.pyx'] +
+ _pxi_dep['sparse'])},
+ '_libs.testing': {'pyxfile': '_libs/testing',
+ 'depends': ['pandas/_libs/testing.pyx']},
+ '_libs.hashing': {'pyxfile': '_libs/hashing',
+ 'depends': ['pandas/_libs/hashing.pyx']},
'io.sas._sas': {'pyxfile': 'io/sas/sas'},
}
| This reverts commit e6aed2ebb7374ed2a6a7c284750d47728aec285e.
xref #17555 | https://api.github.com/repos/pandas-dev/pandas/pulls/17565 | 2017-09-17T21:45:03Z | 2017-09-17T22:14:16Z | 2017-09-17T22:14:16Z | 2017-09-18T16:19:19Z |
Dont check for NaTType, just NaT | diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py
index d7b7d56d74a3a..12b7936503ad7 100644
--- a/pandas/core/indexes/timedeltas.py
+++ b/pandas/core/indexes/timedeltas.py
@@ -847,7 +847,7 @@ def insert(self, loc, item):
pass
freq = None
- if isinstance(item, (Timedelta, libts.NaTType)):
+ if isinstance(item, Timedelta) or item is NaT:
# check freq can be preserved on edge cases
if self.freq is not None:
diff --git a/pandas/io/packers.py b/pandas/io/packers.py
index a2fc4db23700c..92270b39f56ef 100644
--- a/pandas/io/packers.py
+++ b/pandas/io/packers.py
@@ -56,7 +56,6 @@
Index, MultiIndex, Float64Index, Int64Index,
Panel, RangeIndex, PeriodIndex, DatetimeIndex, NaT,
Categorical, CategoricalIndex)
-from pandas._libs.tslib import NaTType
from pandas.core.sparse.api import SparseSeries, SparseDataFrame
from pandas.core.sparse.array import BlockIndex, IntIndex
from pandas.core.generic import NDFrame
@@ -470,7 +469,7 @@ def encode(obj):
}
elif isinstance(obj, (datetime, date, np.datetime64, timedelta,
- np.timedelta64, NaTType)):
+ np.timedelta64)) or obj is NaT:
if isinstance(obj, Timestamp):
tz = obj.tzinfo
if tz is not None:
@@ -482,7 +481,7 @@ def encode(obj):
u'value': obj.value,
u'freq': freq,
u'tz': tz}
- if isinstance(obj, NaTType):
+ if obj is NaT:
return {u'typ': u'nat'}
elif isinstance(obj, np.timedelta64):
return {u'typ': u'timedelta64',
diff --git a/pandas/tests/scalar/test_timedelta.py b/pandas/tests/scalar/test_timedelta.py
index bc9a0388df9d9..910aed6fc5d3e 100644
--- a/pandas/tests/scalar/test_timedelta.py
+++ b/pandas/tests/scalar/test_timedelta.py
@@ -9,7 +9,7 @@
from pandas.core.tools.timedeltas import _coerce_scalar_to_timedelta_type as ct
from pandas import (Timedelta, TimedeltaIndex, timedelta_range, Series,
to_timedelta, compat)
-from pandas._libs.tslib import iNaT, NaTType
+from pandas._libs.tslib import iNaT, NaT
class TestTimedeltas(object):
@@ -572,7 +572,7 @@ def test_implementation_limits(self):
assert max_td.value == np.iinfo(np.int64).max
# Beyond lower limit, a NAT before the Overflow
- assert isinstance(min_td - Timedelta(1, 'ns'), NaTType)
+ assert (min_td - Timedelta(1, 'ns')) is NaT
with pytest.raises(OverflowError):
min_td - Timedelta(2, 'ns')
@@ -582,7 +582,7 @@ def test_implementation_limits(self):
# Same tests using the internal nanosecond values
td = Timedelta(min_td.value - 1, 'ns')
- assert isinstance(td, NaTType)
+ assert td is NaT
with pytest.raises(OverflowError):
Timedelta(min_td.value - 2, 'ns')
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17564 | 2017-09-17T20:27:44Z | 2017-09-23T19:42:54Z | 2017-09-23T19:42:54Z | 2017-10-30T16:24:43Z |
DOC: Add examples to .get_loc methods | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 008828cf4f309..ca145eeaaa7b8 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -2421,7 +2421,7 @@ def _get_unique_index(self, dropna=False):
return self._shallow_copy(values)
_index_shared_docs['get_loc'] = """
- Get integer location for requested label.
+ Get integer location, slice or boolean mask for requested label.
Parameters
----------
@@ -2441,8 +2441,22 @@ def _get_unique_index(self, dropna=False):
Returns
-------
- loc : int if unique index, possibly slice or mask if not
- """
+ loc : int if unique index, slice if monotonic index, else mask
+
+ Examples
+ ---------
+ >>> unique_index = pd.Index(list('abc'))
+ >>> unique_index.get_loc('b')
+ 1
+
+ >>> monotonic_index = pd.Index(list('abbc'))
+ >>> monotonic_index.get_loc('b')
+ slice(1, 3, None)
+
+ >>> non_monotonic_index = pd.Index(list('abcb'))
+ >>> non_monotonic_index.get_loc('b')
+ array([False, True, False, True], dtype=bool)
+ """
@Appender(_index_shared_docs['get_loc'])
def get_loc(self, key, method=None, tolerance=None):
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index ef1dc4d971f37..447087d3c7563 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -354,7 +354,7 @@ def _to_safe_for_reshape(self):
def get_loc(self, key, method=None):
"""
- Get integer location for requested label
+ Get integer location, slice or boolean mask for requested label.
Parameters
----------
@@ -364,7 +364,21 @@ def get_loc(self, key, method=None):
Returns
-------
- loc : int if unique index, possibly slice or mask if not
+ loc : int if unique index, slice if monotonic index, else mask
+
+ Examples
+ ---------
+ >>> unique_index = pd.CategoricalIndex(list('abc'))
+ >>> unique_index.get_loc('b')
+ 1
+
+ >>> monotonic_index = pd.CategoricalIndex(list('abbc'))
+ >>> monotonic_index.get_loc('b')
+ slice(1, 3, None)
+
+ >>> non_monotonic_index = p.dCategoricalIndex(list('abcb'))
+ >>> non_monotonic_index.get_loc('b')
+ array([False, True, False, True], dtype=bool)
"""
codes = self.categories.get_loc(key)
if (codes == -1):
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index c0a9c139722f5..8120c93ad3364 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -689,6 +689,41 @@ def _find_non_overlapping_monotonic_bounds(self, key):
return start, stop
def get_loc(self, key, method=None):
+ """Get integer location, slice or boolean mask for requested label.
+
+ Parameters
+ ----------
+ key : label
+ method : {None}, optional
+ * default: matches where the label is within an interval only.
+
+ Returns
+ -------
+ loc : int if unique index, slice if monotonic index, else mask
+
+ Examples
+ ---------
+ >>> i1, i2 = pd.Interval(0, 1), pd.Interval(1, 2)
+ >>> index = pd.IntervalIndex.from_intervals([i1, i2])
+ >>> index.get_loc(1)
+ 0
+
+ You can also supply an interval or an location for a point inside an
+ interval.
+
+ >>> index.get_loc(pd.Interval(0, 2))
+ array([0, 1], dtype=int64)
+ >>> index.get_loc(1.5)
+ 1
+
+ If a label is in several intervals, you get the locations of all the
+ relevant intervals.
+
+ >>> i3 = pd.Interval(0, 2)
+ >>> overlapping_index = pd.IntervalIndex.from_intervals([i2, i3])
+ >>> overlapping_index.get_loc(1.5)
+ array([0, 1], dtype=int64)
+ """
self._check_method(method)
original_key = key
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index ea613a27b6521..66209ecd3a030 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -1967,6 +1967,21 @@ def get_loc(self, key, method=None):
Returns
-------
loc : int, slice object or boolean mask
+
+ Examples
+ ---------
+ >>> mi = pd.MultiIndex.from_arrays([list('abb'), list('def')])
+ >>> mi.get_loc('b')
+ slice(1, 3, None)
+ >>> mi.get_loc(('b', 'e'))
+ 1
+
+ See also
+ --------
+ Index.get_loc : get_loc method for (single-level) index.
+ get_locs : Given a tuple of slices/lists/labels/boolean indexer to a
+ level-wise spec, produce an indexer to extract those
+ locations.
"""
if method is not None:
raise NotImplementedError('only the default get_loc method is '
| - [ x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
This pull request adds some examples to ``.get_loc`` doc string of ``pd.Index``, ``pd.CategoricalIndex``, ``pd.MultiIndex`` & ``pd.IntervalIndex``. Also clarifies the return value in some cases.
I previously proposed pull request #17380, but the commit history there became a mess. I've deleted that pull request and added this instead. | https://api.github.com/repos/pandas-dev/pandas/pulls/17563 | 2017-09-17T16:26:41Z | 2017-09-20T21:23:58Z | 2017-09-20T21:23:58Z | 2017-10-09T21:00:13Z |
DOC: Fixes after #17482 | diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index 52e056103cbdc..35833a9d49e11 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -363,7 +363,7 @@ Additionally, DataFrames with datetime columns that were parsed by :func:`read_s
Consistency of Range Functions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-In previous versions, there were some inconsistencies between the various range functions: func:`date_range`, func:`bdate_range`, func:`cdate_range`, func:`period_range`, func:`timedelta_range`, and func:`interval_range`. (:issue:`17471`).
+In previous versions, there were some inconsistencies between the various range functions: :func:`date_range`, :func:`bdate_range`, :func:`cdate_range`, :func:`period_range`, :func:`timedelta_range`, and :func:`interval_range`. (:issue:`17471`).
One of the inconsistent behaviors occurred when the ``start``, ``end`` and ``period`` parameters were all specified, potentially leading to ambiguous ranges. When all three parameters were passed, ``interval_range`` ignored the ``period`` parameter, ``period_range`` ignored the ``end`` parameter, and the other range functions raised. To promote consistency among the range functions, and avoid potentially ambiguous ranges, ``interval_range`` and ``period_range`` will now raise when all three parameters are passed.
diff --git a/pandas/core/api.py b/pandas/core/api.py
index 086fedd7d7cf8..6a32d3763ffb1 100644
--- a/pandas/core/api.py
+++ b/pandas/core/api.py
@@ -16,7 +16,8 @@
PeriodIndex, NaT)
from pandas.core.indexes.period import Period, period_range, pnow
from pandas.core.indexes.timedeltas import Timedelta, timedelta_range
-from pandas.core.indexes.datetimes import Timestamp, date_range, bdate_range
+from pandas.core.indexes.datetimes import (Timestamp, date_range, bdate_range,
+ cdate_range)
from pandas.core.indexes.interval import Interval, interval_range
from pandas.core.series import Series
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index 1c8d0b334b91c..6b1b61c2798f4 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -2094,13 +2094,8 @@ def bdate_range(start=None, end=None, periods=None, freq='B', tz=None,
def cdate_range(start=None, end=None, periods=None, freq='C', tz=None,
normalize=True, name=None, closed=None, **kwargs):
"""
- **EXPERIMENTAL** Return a fixed frequency DatetimeIndex, with
- CustomBusinessDay as the default frequency
-
- .. warning:: EXPERIMENTAL
-
- The CustomBusinessDay class is not officially supported and the API is
- likely to change in future versions. Use this at your own risk.
+ Return a fixed frequency DatetimeIndex, with CustomBusinessDay as the
+ default frequency
Parameters
----------
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index d4df53d76398c..c0a9c139722f5 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -1094,7 +1094,8 @@ def interval_range(start=None, end=None, periods=None, freq=None,
Additionally, datetime-like input is also supported.
- >>> pd.interval_range(start='2017-01-01', end='2017-01-04')
+ >>> pd.interval_range(start=pd.Timestamp('2017-01-01'),
+ end=pd.Timestamp('2017-01-04'))
IntervalIndex([(2017-01-01, 2017-01-02], (2017-01-02, 2017-01-03],
(2017-01-03, 2017-01-04]]
closed='right', dtype='interval[datetime64[ns]]')
@@ -1110,7 +1111,8 @@ def interval_range(start=None, end=None, periods=None, freq=None,
Similarly, for datetime-like ``start`` and ``end``, the frequency must be
convertible to a DateOffset.
- >>> pd.interval_range(start='2017-01-01', periods=3, freq='MS')
+ >>> pd.interval_range(start=pd.Timestamp('2017-01-01'),
+ periods=3, freq='MS')
IntervalIndex([(2017-01-01, 2017-02-01], (2017-02-01, 2017-03-01],
(2017-03-01, 2017-04-01]]
closed='right', dtype='interval[datetime64[ns]]')
diff --git a/pandas/tests/api/test_api.py b/pandas/tests/api/test_api.py
index 09cccd54b74f8..cbc73615811a2 100644
--- a/pandas/tests/api/test_api.py
+++ b/pandas/tests/api/test_api.py
@@ -63,7 +63,7 @@ class TestPDApi(Base):
# top-level functions
funcs = ['bdate_range', 'concat', 'crosstab', 'cut',
'date_range', 'interval_range', 'eval',
- 'factorize', 'get_dummies',
+ 'factorize', 'get_dummies', 'cdate_range',
'infer_freq', 'isna', 'isnull', 'lreshape',
'melt', 'notna', 'notnull', 'offsets',
'merge', 'merge_ordered', 'merge_asof',
| - [X] tests added / passed
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
Some doc fixes related to #17482:
- `func:` -> `:func:`
- See: https://github.com/pandas-dev/pandas/pull/17482#discussion_r139148962
- Added `cdate_range` to the public api so that it works in the docs
- Ask for it to be added to docs: https://github.com/pandas-dev/pandas/pull/17482#discussion_r138609092
- Public api issue pointed out: https://github.com/pandas-dev/pandas/pull/17482#discussion_r139148705
- Added `cdate_range` to `tests\api\test_api.py` to ensure that adding it to the top-level api is tested
- Removed the "experimental" from `cdate_range` docstring
- See: https://github.com/pandas-dev/pandas/pull/17482#discussion_r138504193
- Fixed an error in the docstring for `interval_range` (strings aren't supported). | https://api.github.com/repos/pandas-dev/pandas/pulls/17554 | 2017-09-15T22:07:16Z | 2017-09-17T15:04:55Z | 2017-09-17T15:04:55Z | 2017-09-19T14:27:47Z |
Spelling and grammar | diff --git a/pandas/compat/chainmap_impl.py b/pandas/compat/chainmap_impl.py
index 05a0d5faa4c2a..c4aa8c8d6ab30 100644
--- a/pandas/compat/chainmap_impl.py
+++ b/pandas/compat/chainmap_impl.py
@@ -34,10 +34,10 @@ def wrapper(self):
class ChainMap(MutableMapping):
""" A ChainMap groups multiple dicts (or other mappings) together
- to create a single, updateable view.
+ to create a single, updatable view.
The underlying mappings are stored in a list. That list is public and can
- accessed or updated using the *maps* attribute. There is no other state.
+ be accessed / updated using the *maps* attribute. There is no other state.
Lookups search the underlying mappings successively until a key is found.
In contrast, writes, updates, and deletions only operate on the first
|

- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17548 | 2017-09-15T17:41:54Z | 2017-09-16T07:00:11Z | 2017-09-16T07:00:11Z | 2017-09-18T18:03:07Z |
de-privatize timezone functions | diff --git a/pandas/_libs/period.pyx b/pandas/_libs/period.pyx
index 49353f7b0491c..785bc945c264b 100644
--- a/pandas/_libs/period.pyx
+++ b/pandas/_libs/period.pyx
@@ -35,7 +35,7 @@ from pandas._libs import tslib, lib
from pandas._libs.tslib import (Timedelta, Timestamp, iNaT,
NaT)
from tslibs.timezones cimport (
- is_utc, is_tzlocal, get_utcoffset, _get_dst_info, maybe_get_tz)
+ is_utc, is_tzlocal, get_utcoffset, get_dst_info, maybe_get_tz)
from tslib cimport _nat_scalar_rules
from tslibs.frequencies cimport get_freq_code
@@ -557,7 +557,7 @@ cdef _reso_local(ndarray[int64_t] stamps, object tz):
reso = curr_reso
else:
# Adjust datetime64 timestamp, recompute datetimestruct
- trans, deltas, typ = _get_dst_info(tz)
+ trans, deltas, typ = get_dst_info(tz)
_pos = trans.searchsorted(stamps, side='right') - 1
if _pos.dtype != np.int64:
@@ -624,7 +624,7 @@ cdef ndarray[int64_t] localize_dt64arr_to_period(ndarray[int64_t] stamps,
dts.us, dts.ps, freq)
else:
# Adjust datetime64 timestamp, recompute datetimestruct
- trans, deltas, typ = _get_dst_info(tz)
+ trans, deltas, typ = get_dst_info(tz)
_pos = trans.searchsorted(stamps, side='right') - 1
if _pos.dtype != np.int64:
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx
index ec12611ae7f02..ee8a03bd0c37c 100644
--- a/pandas/_libs/tslib.pyx
+++ b/pandas/_libs/tslib.pyx
@@ -100,16 +100,10 @@ iNaT = NPY_NAT
from tslibs.timezones cimport (
- is_utc, is_tzlocal, _is_fixed_offset,
+ is_utc, is_tzlocal, is_fixed_offset,
treat_tz_as_dateutil, treat_tz_as_pytz,
get_timezone, get_utcoffset, maybe_get_tz,
- _get_dst_info
- )
-from tslibs.timezones import ( # noqa
- get_timezone, get_utcoffset, maybe_get_tz,
- _p_tz_cache_key, dst_cache,
- _unbox_utcoffsets,
- _dateutil_gettz
+ get_dst_info
)
@@ -167,7 +161,7 @@ def ints_to_pydatetime(ndarray[int64_t] arr, tz=None, freq=None, box=False):
pandas_datetime_to_datetimestruct(
value, PANDAS_FR_ns, &dts)
result[i] = func_create(value, dts, tz, freq)
- elif is_tzlocal(tz) or _is_fixed_offset(tz):
+ elif is_tzlocal(tz) or is_fixed_offset(tz):
for i in range(n):
value = arr[i]
if value == NPY_NAT:
@@ -181,7 +175,7 @@ def ints_to_pydatetime(ndarray[int64_t] arr, tz=None, freq=None, box=False):
dt = Timestamp(dt)
result[i] = dt
else:
- trans, deltas, typ = _get_dst_info(tz)
+ trans, deltas, typ = get_dst_info(tz)
for i in range(n):
@@ -1641,12 +1635,12 @@ cdef inline void _localize_tso(_TSObject obj, object tz):
obj.tzinfo = tz
else:
# Adjust datetime64 timestamp, recompute datetimestruct
- trans, deltas, typ = _get_dst_info(tz)
+ trans, deltas, typ = get_dst_info(tz)
pos = trans.searchsorted(obj.value, side='right') - 1
# static/pytz/dateutil specific code
- if _is_fixed_offset(tz):
+ if is_fixed_offset(tz):
# statictzinfo
if len(deltas) > 0 and obj.value != NPY_NAT:
pandas_datetime_to_datetimestruct(obj.value + deltas[0],
@@ -4066,7 +4060,7 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2):
* 1000000000)
utc_dates[i] = v - delta
else:
- trans, deltas, typ = _get_dst_info(tz1)
+ trans, deltas, typ = get_dst_info(tz1)
# all-NaT
tt = vals[vals!=NPY_NAT]
@@ -4108,7 +4102,7 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2):
return result
# Convert UTC to other timezone
- trans, deltas, typ = _get_dst_info(tz2)
+ trans, deltas, typ = get_dst_info(tz2)
# use first non-NaT element
# if all-NaT, return all-NaT
@@ -4172,7 +4166,7 @@ def tz_convert_single(int64_t val, object tz1, object tz2):
delta = int(get_utcoffset(tz1, dt).total_seconds()) * 1000000000
utc_date = val - delta
elif get_timezone(tz1) != 'UTC':
- trans, deltas, typ = _get_dst_info(tz1)
+ trans, deltas, typ = get_dst_info(tz1)
pos = trans.searchsorted(val, side='right') - 1
if pos < 0:
raise ValueError('First time before start of DST info')
@@ -4191,7 +4185,7 @@ def tz_convert_single(int64_t val, object tz1, object tz2):
return utc_date + delta
# Convert UTC to other timezone
- trans, deltas, typ = _get_dst_info(tz2)
+ trans, deltas, typ = get_dst_info(tz2)
pos = trans.searchsorted(utc_date, side='right') - 1
if pos < 0:
@@ -4261,7 +4255,7 @@ def tz_localize_to_utc(ndarray[int64_t] vals, object tz, object ambiguous=None,
"Length of ambiguous bool-array must be the same size as vals")
ambiguous_array = np.asarray(ambiguous)
- trans, deltas, typ = _get_dst_info(tz)
+ trans, deltas, typ = get_dst_info(tz)
tdata = <int64_t*> trans.data
ntrans = len(trans)
@@ -4967,7 +4961,7 @@ cdef _normalize_local(ndarray[int64_t] stamps, object tz):
result[i] = _normalized_stamp(&dts)
else:
# Adjust datetime64 timestamp, recompute datetimestruct
- trans, deltas, typ = _get_dst_info(tz)
+ trans, deltas, typ = get_dst_info(tz)
_pos = trans.searchsorted(stamps, side='right') - 1
if _pos.dtype != np.int64:
@@ -5022,7 +5016,7 @@ def dates_normalized(ndarray[int64_t] stamps, tz=None):
if (dt.hour + dt.minute + dt.second + dt.microsecond) > 0:
return False
else:
- trans, deltas, typ = _get_dst_info(tz)
+ trans, deltas, typ = get_dst_info(tz)
for i in range(n):
# Adjust datetime64 timestamp, recompute datetimestruct
diff --git a/pandas/_libs/tslibs/timezones.pxd b/pandas/_libs/tslibs/timezones.pxd
index fac0018a78bc2..e5d1343e1c984 100644
--- a/pandas/_libs/tslibs/timezones.pxd
+++ b/pandas/_libs/tslibs/timezones.pxd
@@ -13,6 +13,6 @@ cpdef object get_timezone(object tz)
cpdef object maybe_get_tz(object tz)
cpdef get_utcoffset(tzinfo, obj)
-cdef bint _is_fixed_offset(object tz)
+cdef bint is_fixed_offset(object tz)
-cdef object _get_dst_info(object tz)
+cdef object get_dst_info(object tz)
diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx
index 346da41e7073b..48d82996a0bd0 100644
--- a/pandas/_libs/tslibs/timezones.pyx
+++ b/pandas/_libs/tslibs/timezones.pyx
@@ -13,9 +13,9 @@ from dateutil.tz import (
import sys
if sys.platform == 'win32' or sys.platform == 'cygwin':
# equiv pd.compat.is_platform_windows()
- from dateutil.zoneinfo import gettz as _dateutil_gettz
+ from dateutil.zoneinfo import gettz as dateutil_gettz
else:
- from dateutil.tz import gettz as _dateutil_gettz
+ from dateutil.tz import gettz as dateutil_gettz
from pytz.tzinfo import BaseTzInfo as _pytz_BaseTzInfo
@@ -100,7 +100,7 @@ cpdef inline object maybe_get_tz(object tz):
tz = _dateutil_tzlocal()
elif tz.startswith('dateutil/'):
zone = tz[9:]
- tz = _dateutil_gettz(zone)
+ tz = dateutil_gettz(zone)
# On Python 3 on Windows, the filename is not always set correctly.
if isinstance(tz, _dateutil_tzfile) and '.tar.gz' in tz._filename:
tz._filename = zone
@@ -113,14 +113,14 @@ cpdef inline object maybe_get_tz(object tz):
def _p_tz_cache_key(tz):
""" Python interface for cache function to facilitate testing."""
- return _tz_cache_key(tz)
+ return tz_cache_key(tz)
# Timezone data caches, key is the pytz string or dateutil file name.
dst_cache = {}
-cdef inline object _tz_cache_key(object tz):
+cdef inline object tz_cache_key(object tz):
"""
Return the key in the cache for the timezone info object or None
if unknown.
@@ -163,7 +163,7 @@ cpdef get_utcoffset(tzinfo, obj):
return tzinfo.utcoffset(obj)
-cdef inline bint _is_fixed_offset(object tz):
+cdef inline bint is_fixed_offset(object tz):
if treat_tz_as_dateutil(tz):
if len(tz._trans_idx) == 0 and len(tz._trans_list) == 0:
return 1
@@ -178,7 +178,7 @@ cdef inline bint _is_fixed_offset(object tz):
return 1
-cdef object _get_utc_trans_times_from_dateutil_tz(object tz):
+cdef object get_utc_trans_times_from_dateutil_tz(object tz):
"""
Transition times in dateutil timezones are stored in local non-dst
time. This code converts them to UTC. It's the reverse of the code
@@ -193,7 +193,7 @@ cdef object _get_utc_trans_times_from_dateutil_tz(object tz):
return new_trans
-cpdef ndarray _unbox_utcoffsets(object transinfo):
+cpdef ndarray unbox_utcoffsets(object transinfo):
cdef:
Py_ssize_t i, sz
ndarray[int64_t] arr
@@ -211,7 +211,7 @@ cpdef ndarray _unbox_utcoffsets(object transinfo):
# Daylight Savings
-cdef object _get_dst_info(object tz):
+cdef object get_dst_info(object tz):
"""
return a tuple of :
(UTC times of DST transitions,
@@ -219,7 +219,7 @@ cdef object _get_dst_info(object tz):
string of type of transitions)
"""
- cache_key = _tz_cache_key(tz)
+ cache_key = tz_cache_key(tz)
if cache_key is None:
num = int(get_utcoffset(tz, None).total_seconds()) * 1000000000
return (np.array([NPY_NAT + 1], dtype=np.int64),
@@ -235,13 +235,13 @@ cdef object _get_dst_info(object tz):
trans[0] = NPY_NAT + 1
except Exception:
pass
- deltas = _unbox_utcoffsets(tz._transition_info)
+ deltas = unbox_utcoffsets(tz._transition_info)
typ = 'pytz'
elif treat_tz_as_dateutil(tz):
if len(tz._trans_list):
# get utc trans times
- trans_list = _get_utc_trans_times_from_dateutil_tz(tz)
+ trans_list = get_utc_trans_times_from_dateutil_tz(tz)
trans = np.hstack([
np.array([0], dtype='M8[s]'), # place holder for first item
np.array(trans_list, dtype='M8[s]')]).astype(
@@ -255,7 +255,7 @@ cdef object _get_dst_info(object tz):
deltas *= 1000000000
typ = 'dateutil'
- elif _is_fixed_offset(tz):
+ elif is_fixed_offset(tz):
trans = np.array([NPY_NAT + 1], dtype=np.int64)
deltas = np.array([tz._ttinfo_std.offset],
dtype='i8') * 1000000000
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index 1c8d0b334b91c..1260d9547d5bb 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -50,6 +50,7 @@
from pandas._libs import (lib, index as libindex, tslib as libts,
algos as libalgos, join as libjoin,
Timestamp, period as libperiod)
+from pandas._libs.tslibs import timezones
def _utc():
@@ -372,7 +373,7 @@ def __new__(cls, data=None,
tz = subarr.tz
else:
if tz is not None:
- tz = libts.maybe_get_tz(tz)
+ tz = timezones.maybe_get_tz(tz)
if (not isinstance(data, DatetimeIndex) or
getattr(data, 'tz', None) is None):
@@ -447,17 +448,18 @@ def _generate(cls, start, end, periods, name, offset,
raise TypeError('Start and end cannot both be tz-aware with '
'different timezones')
- inferred_tz = libts.maybe_get_tz(inferred_tz)
+ inferred_tz = timezones.maybe_get_tz(inferred_tz)
# these may need to be localized
- tz = libts.maybe_get_tz(tz)
+ tz = timezones.maybe_get_tz(tz)
if tz is not None:
date = start or end
if date.tzinfo is not None and hasattr(tz, 'localize'):
tz = tz.localize(date.replace(tzinfo=None)).tzinfo
if tz is not None and inferred_tz is not None:
- if not libts.get_timezone(inferred_tz) == libts.get_timezone(tz):
+ if not (timezones.get_timezone(inferred_tz) ==
+ timezones.get_timezone(tz)):
raise AssertionError("Inferred time zone not equal to passed "
"time zone")
@@ -593,7 +595,7 @@ def _simple_new(cls, values, name=None, freq=None, tz=None,
result._data = values
result.name = name
result.offset = freq
- result.tz = libts.maybe_get_tz(tz)
+ result.tz = timezones.maybe_get_tz(tz)
result._reset_identity()
return result
@@ -607,7 +609,7 @@ def tzinfo(self):
@cache_readonly
def _timezone(self):
""" Comparable timezone both for pytz / dateutil"""
- return libts.get_timezone(self.tzinfo)
+ return timezones.get_timezone(self.tzinfo)
def _has_same_tz(self, other):
zzone = self._timezone
@@ -616,7 +618,7 @@ def _has_same_tz(self, other):
if isinstance(other, np.datetime64):
# convert to Timestamp as np.datetime64 doesn't have tz attr
other = Timestamp(other)
- vzone = libts.get_timezone(getattr(other, 'tzinfo', '__no_tz__'))
+ vzone = timezones.get_timezone(getattr(other, 'tzinfo', '__no_tz__'))
return zzone == vzone
@classmethod
@@ -1779,7 +1781,7 @@ def tz_convert(self, tz):
TypeError
If DatetimeIndex is tz-naive.
"""
- tz = libts.maybe_get_tz(tz)
+ tz = timezones.maybe_get_tz(tz)
if self.tz is None:
# tz naive, use tz_localize
@@ -1839,7 +1841,7 @@ def tz_localize(self, tz, ambiguous='raise', errors='raise'):
else:
raise TypeError("Already tz-aware, use tz_convert to convert.")
else:
- tz = libts.maybe_get_tz(tz)
+ tz = timezones.maybe_get_tz(tz)
# Convert to UTC
new_dates = libts.tz_localize_to_utc(self.asi8, tz,
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py
index 9dde26f43ad33..95fe3ab83c2ab 100644
--- a/pandas/core/tools/datetimes.py
+++ b/pandas/core/tools/datetimes.py
@@ -3,6 +3,7 @@
from collections import MutableMapping
from pandas._libs import lib, tslib
+from pandas._libs.tslibs.timezones import get_timezone
from pandas.core.dtypes.common import (
_ensure_object,
@@ -44,7 +45,7 @@ def _infer_tzinfo(start, end):
def _infer(a, b):
tz = a.tzinfo
if b and b.tzinfo:
- if not (tslib.get_timezone(tz) == tslib.get_timezone(b.tzinfo)):
+ if not (get_timezone(tz) == get_timezone(b.tzinfo)):
raise AssertionError('Inputs must both have the same timezone,'
' {timezone1} != {timezone2}'
.format(timezone1=tz, timezone2=b.tzinfo))
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 9f819a4463bed..4d300b200971a 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -46,7 +46,8 @@
from pandas.core.config import get_option
from pandas.core.computation.pytables import Expr, maybe_expression
-from pandas._libs import tslib, algos, lib
+from pandas._libs import algos, lib
+from pandas._libs.tslibs import timezones
from distutils.version import LooseVersion
@@ -4379,7 +4380,7 @@ def _get_info(info, name):
def _get_tz(tz):
""" for a tz-aware type, return an encoded zone """
- zone = tslib.get_timezone(tz)
+ zone = timezones.get_timezone(tz)
if zone is None:
zone = tz.utcoffset().total_seconds()
return zone
@@ -4401,7 +4402,7 @@ def _set_tz(values, tz, preserve_UTC=False, coerce=False):
if tz is not None:
name = getattr(values, 'name', None)
values = values.ravel()
- tz = tslib.get_timezone(_ensure_decoded(tz))
+ tz = timezones.get_timezone(_ensure_decoded(tz))
values = DatetimeIndex(values, name=name)
if values.tz is None:
values = values.tz_localize('UTC').tz_convert(tz)
diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py
index 8d86bebdd4d5e..c373942cb4c63 100644
--- a/pandas/tests/indexes/datetimes/test_date_range.py
+++ b/pandas/tests/indexes/datetimes/test_date_range.py
@@ -394,7 +394,7 @@ def test_range_tz_dateutil(self):
# see gh-2906
# Use maybe_get_tz to fix filename in tz under dateutil.
- from pandas._libs.tslib import maybe_get_tz
+ from pandas._libs.tslibs.timezones import maybe_get_tz
tz = lambda x: maybe_get_tz('dateutil/' + x)
start = datetime(2011, 1, 1, tzinfo=tz('US/Eastern'))
diff --git a/pandas/tests/indexes/datetimes/test_setops.py b/pandas/tests/indexes/datetimes/test_setops.py
index f43c010f59b9e..4ffd2e1cd1e61 100644
--- a/pandas/tests/indexes/datetimes/test_setops.py
+++ b/pandas/tests/indexes/datetimes/test_setops.py
@@ -325,8 +325,8 @@ def test_month_range_union_tz_pytz(self):
def test_month_range_union_tz_dateutil(self):
tm._skip_if_windows_python_3()
- from pandas._libs.tslib import _dateutil_gettz as timezone
- tz = timezone('US/Eastern')
+ from pandas._libs.tslibs.timezones import dateutil_gettz
+ tz = dateutil_gettz('US/Eastern')
early_start = datetime(2011, 1, 1)
early_end = datetime(2011, 3, 1)
diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py
index f331378b654be..a05553d80c133 100644
--- a/pandas/tests/io/test_pytables.py
+++ b/pandas/tests/io/test_pytables.py
@@ -5421,7 +5421,7 @@ def test_append_with_timezones_dateutil(self):
# use maybe_get_tz instead of dateutil.tz.gettz to handle the windows
# filename issues.
- from pandas._libs.tslib import maybe_get_tz
+ from pandas._libs.tslibs.timezones import maybe_get_tz
gettz = lambda x: maybe_get_tz('dateutil/' + x)
# as columns
diff --git a/pandas/tests/scalar/test_period.py b/pandas/tests/scalar/test_period.py
index a167c9c738b0b..c17a216df44cb 100644
--- a/pandas/tests/scalar/test_period.py
+++ b/pandas/tests/scalar/test_period.py
@@ -245,29 +245,29 @@ def test_timestamp_tz_arg(self):
assert p.tz == exp.tz
def test_timestamp_tz_arg_dateutil(self):
- from pandas._libs.tslib import _dateutil_gettz as gettz
- from pandas._libs.tslib import maybe_get_tz
+ from pandas._libs.tslibs.timezones import dateutil_gettz
+ from pandas._libs.tslibs.timezones import maybe_get_tz
for case in ['dateutil/Europe/Brussels', 'dateutil/Asia/Tokyo',
'dateutil/US/Pacific']:
p = Period('1/1/2005', freq='M').to_timestamp(
tz=maybe_get_tz(case))
exp = Timestamp('1/1/2005', tz='UTC').tz_convert(case)
assert p == exp
- assert p.tz == gettz(case.split('/', 1)[1])
+ assert p.tz == dateutil_gettz(case.split('/', 1)[1])
assert p.tz == exp.tz
p = Period('1/1/2005',
freq='M').to_timestamp(freq='3H', tz=maybe_get_tz(case))
exp = Timestamp('1/1/2005', tz='UTC').tz_convert(case)
assert p == exp
- assert p.tz == gettz(case.split('/', 1)[1])
+ assert p.tz == dateutil_gettz(case.split('/', 1)[1])
assert p.tz == exp.tz
def test_timestamp_tz_arg_dateutil_from_string(self):
- from pandas._libs.tslib import _dateutil_gettz as gettz
+ from pandas._libs.tslibs.timezones import dateutil_gettz
p = Period('1/1/2005',
freq='M').to_timestamp(tz='dateutil/Europe/Brussels')
- assert p.tz == gettz('Europe/Brussels')
+ assert p.tz == dateutil_gettz('Europe/Brussels')
def test_timestamp_mult(self):
p = pd.Period('2011-01', freq='M')
diff --git a/pandas/tests/scalar/test_timestamp.py b/pandas/tests/scalar/test_timestamp.py
index 8d47ce4802ac6..c1b9f858a08de 100644
--- a/pandas/tests/scalar/test_timestamp.py
+++ b/pandas/tests/scalar/test_timestamp.py
@@ -17,7 +17,7 @@
import pandas.util.testing as tm
from pandas.tseries import offsets, frequencies
from pandas._libs import tslib, period
-from pandas._libs.tslib import get_timezone
+from pandas._libs.tslibs.timezones import get_timezone
from pandas.compat import lrange, long
from pandas.util.testing import assert_series_equal
@@ -1295,7 +1295,7 @@ def test_timestamp_to_datetime_explicit_pytz(self):
def test_timestamp_to_datetime_explicit_dateutil(self):
tm._skip_if_windows_python_3()
- from pandas._libs.tslib import _dateutil_gettz as gettz
+ from pandas._libs.tslibs.timezones import dateutil_gettz as gettz
rng = date_range('20090415', '20090519', tz=gettz('US/Eastern'))
stamp = rng[0]
diff --git a/pandas/tests/series/test_indexing.py b/pandas/tests/series/test_indexing.py
index 45a92f6d6f50b..91187b709463a 100644
--- a/pandas/tests/series/test_indexing.py
+++ b/pandas/tests/series/test_indexing.py
@@ -387,7 +387,7 @@ def test_getitem_setitem_datetime_tz_pytz(self):
def test_getitem_setitem_datetime_tz_dateutil(self):
from dateutil.tz import tzutc
- from pandas._libs.tslib import _dateutil_gettz as gettz
+ from pandas._libs.tslibs.timezones import dateutil_gettz as gettz
tz = lambda x: tzutc() if x == 'UTC' else gettz(
x) # handle special case for utc in dateutil
diff --git a/pandas/tests/tseries/test_offsets.py b/pandas/tests/tseries/test_offsets.py
index cd2c29ffe3ac6..543d21e162f04 100644
--- a/pandas/tests/tseries/test_offsets.py
+++ b/pandas/tests/tseries/test_offsets.py
@@ -33,6 +33,7 @@
to_datetime, DateParseError)
import pandas.tseries.offsets as offsets
from pandas.io.pickle import read_pickle
+from pandas._libs.tslibs import timezones
from pandas._libs.tslib import normalize_date, NaT, Timestamp, Timedelta
import pandas._libs.tslib as tslib
import pandas.util.testing as tm
@@ -288,7 +289,7 @@ def _check_offsetfunc_works(self, offset, funcname, dt, expected,
for tz in self.timezones:
expected_localize = expected.tz_localize(tz)
- tz_obj = tslib.maybe_get_tz(tz)
+ tz_obj = timezones.maybe_get_tz(tz)
dt_tz = tslib._localize_pydatetime(dt, tz_obj)
result = func(dt_tz)
diff --git a/pandas/tests/tseries/test_timezones.py b/pandas/tests/tseries/test_timezones.py
index a9ecfd797a32b..ab0bb899d01e7 100644
--- a/pandas/tests/tseries/test_timezones.py
+++ b/pandas/tests/tseries/test_timezones.py
@@ -18,6 +18,7 @@
from pandas.core.indexes.datetimes import bdate_range, date_range
from pandas.core.dtypes.dtypes import DatetimeTZDtype
from pandas._libs import tslib
+from pandas._libs.tslibs import timezones
from pandas import (Index, Series, DataFrame, isna, Timestamp, NaT,
DatetimeIndex, to_datetime)
from pandas.util.testing import (assert_frame_equal, assert_series_equal,
@@ -943,7 +944,7 @@ def tz(self, tz):
Use tslib.maybe_get_tz so that we get the filename on the tz right
on windows. See #7337.
"""
- return tslib.maybe_get_tz('dateutil/' + tz)
+ return timezones.maybe_get_tz('dateutil/' + tz)
def tzstr(self, tz):
""" Construct a timezone string from a string. Overridden in subclass
@@ -962,7 +963,7 @@ def test_utc_with_system_utc(self):
# Skipped on win32 due to dateutil bug
tm._skip_if_windows()
- from pandas._libs.tslib import maybe_get_tz
+ from pandas._libs.tslibs.timezones import maybe_get_tz
# from system utc to real utc
ts = Timestamp('2001-01-05 11:56', tz=maybe_get_tz('dateutil/UTC'))
@@ -1133,7 +1134,7 @@ def test_tzlocal(self):
assert ts.tz == dateutil.tz.tzlocal()
assert "tz='tzlocal()')" in repr(ts)
- tz = tslib.maybe_get_tz('tzlocal()')
+ tz = timezones.maybe_get_tz('tzlocal()')
assert tz == dateutil.tz.tzlocal()
# get offset using normal datetime for test
@@ -1176,12 +1177,13 @@ def test_cache_keys_are_distinct_for_pytz_vs_dateutil(self):
if tz_name == 'UTC':
# skip utc as it's a special case in dateutil
continue
- tz_p = tslib.maybe_get_tz(tz_name)
- tz_d = tslib.maybe_get_tz('dateutil/' + tz_name)
+ tz_p = timezones.maybe_get_tz(tz_name)
+ tz_d = timezones.maybe_get_tz('dateutil/' + tz_name)
if tz_d is None:
# skip timezones that dateutil doesn't know about.
continue
- assert tslib._p_tz_cache_key(tz_p) != tslib._p_tz_cache_key(tz_d)
+ assert (timezones._p_tz_cache_key(tz_p) !=
+ timezones._p_tz_cache_key(tz_d))
class TestTimeZones(object):
@@ -1743,13 +1745,13 @@ def compare_local_to_utc(tz_didx, utc_didx):
# Check empty array
result = tslib.tz_convert(np.array([], dtype=np.int64),
- tslib.maybe_get_tz('US/Eastern'),
- tslib.maybe_get_tz('Asia/Tokyo'))
+ timezones.maybe_get_tz('US/Eastern'),
+ timezones.maybe_get_tz('Asia/Tokyo'))
tm.assert_numpy_array_equal(result, np.array([], dtype=np.int64))
# Check all-NaT array
result = tslib.tz_convert(np.array([tslib.iNaT], dtype=np.int64),
- tslib.maybe_get_tz('US/Eastern'),
- tslib.maybe_get_tz('Asia/Tokyo'))
+ timezones.maybe_get_tz('US/Eastern'),
+ timezones.maybe_get_tz('Asia/Tokyo'))
tm.assert_numpy_array_equal(result, np.array(
[tslib.iNaT], dtype=np.int64))
| Follow-up to #17526
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17543 | 2017-09-15T15:29:45Z | 2017-09-23T19:46:06Z | 2017-09-23T19:46:06Z | 2017-10-30T16:24:46Z |
DOC: fixes after #17503 and #17491 | diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index 52e056103cbdc..d87db023f919c 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -215,7 +215,7 @@ New Behaviour:
Furthermore this will now correctly box the results of iteration for :func:`DataFrame.to_dict` as well.
-.. ipython:: ipython
+.. ipython:: python
d = {'a':[1], 'b':['b']}
df = pd.DataFrame(d)
diff --git a/pandas/core/base.py b/pandas/core/base.py
index f0e8d8a16661b..be021f3621c73 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -900,7 +900,7 @@ def tolist(self):
See Also
--------
- numpy.tolist
+ numpy.ndarray.tolist
"""
if is_datetimelike(self):
| There was still a doc build error (`df` was not defined due to a missing 'i' in 'ipython') | https://api.github.com/repos/pandas-dev/pandas/pulls/17541 | 2017-09-15T13:10:37Z | 2017-09-17T14:12:42Z | 2017-09-17T14:12:42Z | 2017-09-17T14:38:06Z |
TST: sql flaky test: check less decimals (#17510) | diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py
index a7c42391effe6..e482a0ec460bb 100644
--- a/pandas/tests/io/test_sql.py
+++ b/pandas/tests/io/test_sql.py
@@ -2124,7 +2124,7 @@ def test_write_row_by_row(self):
result = sql.read_sql("select * from test", con=self.conn)
result.index = frame.index
- tm.assert_frame_equal(result, frame)
+ tm.assert_frame_equal(result, frame, check_less_precise=True)
def test_execute(self):
frame = tm.makeTimeDataFrame()
@@ -2409,7 +2409,7 @@ def test_write_row_by_row(self):
result = sql.read_sql("select * from test", con=self.conn)
result.index = frame.index
- tm.assert_frame_equal(result, frame)
+ tm.assert_frame_equal(result, frame, check_less_precise=True)
def test_chunksize_read_type(self):
_skip_if_no_pymysql()
| - [ ] closes #17510 | https://api.github.com/repos/pandas-dev/pandas/pulls/17538 | 2017-09-15T08:28:57Z | 2017-09-17T14:13:22Z | 2017-09-17T14:13:22Z | 2017-09-17T14:13:24Z |
CLN: Fix Spelling Errors | diff --git a/doc/source/advanced.rst b/doc/source/advanced.rst
index 3f145cf955664..3bda8c7eacb61 100644
--- a/doc/source/advanced.rst
+++ b/doc/source/advanced.rst
@@ -625,7 +625,7 @@ Index Types
We have discussed ``MultiIndex`` in the previous sections pretty extensively. ``DatetimeIndex`` and ``PeriodIndex``
are shown :ref:`here <timeseries.overview>`. ``TimedeltaIndex`` are :ref:`here <timedeltas.timedeltas>`.
-In the following sub-sections we will highlite some other index types.
+In the following sub-sections we will highlight some other index types.
.. _indexing.categoricalindex:
@@ -645,7 +645,7 @@ and allows efficient indexing and storage of an index with a large number of dup
df.dtypes
df.B.cat.categories
-Setting the index, will create create a ``CategoricalIndex``
+Setting the index, will create a ``CategoricalIndex``
.. ipython:: python
@@ -681,7 +681,7 @@ Groupby operations on the index will preserve the index nature as well
Reindexing operations, will return a resulting index based on the type of the passed
indexer, meaning that passing a list will return a plain-old-``Index``; indexing with
a ``Categorical`` will return a ``CategoricalIndex``, indexed according to the categories
-of the PASSED ``Categorical`` dtype. This allows one to arbitrarly index these even with
+of the PASSED ``Categorical`` dtype. This allows one to arbitrarily index these even with
values NOT in the categories, similarly to how you can reindex ANY pandas index.
.. ipython :: python
@@ -722,7 +722,7 @@ Int64Index and RangeIndex
Prior to 0.18.0, the ``Int64Index`` would provide the default index for all ``NDFrame`` objects.
``RangeIndex`` is a sub-class of ``Int64Index`` added in version 0.18.0, now providing the default index for all ``NDFrame`` objects.
-``RangeIndex`` is an optimized version of ``Int64Index`` that can represent a monotonic ordered set. These are analagous to python `range types <https://docs.python.org/3/library/stdtypes.html#typesseq-range>`__.
+``RangeIndex`` is an optimized version of ``Int64Index`` that can represent a monotonic ordered set. These are analogous to python `range types <https://docs.python.org/3/library/stdtypes.html#typesseq-range>`__.
.. _indexing.float64index:
@@ -963,7 +963,7 @@ index can be somewhat complicated. For example, the following does not work:
s.loc['c':'e'+1]
A very common use case is to limit a time series to start and end at two
-specific dates. To enable this, we made the design design to make label-based
+specific dates. To enable this, we made the design to make label-based
slicing include both endpoints:
.. ipython:: python
diff --git a/doc/source/api.rst b/doc/source/api.rst
index 1541bbccefe21..4e02f7b11f466 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -1291,7 +1291,7 @@ Index
-----
**Many of these methods or variants thereof are available on the objects
-that contain an index (Series/Dataframe) and those should most likely be
+that contain an index (Series/DataFrame) and those should most likely be
used before calling these methods directly.**
.. autosummary::
diff --git a/doc/source/basics.rst b/doc/source/basics.rst
index 42c28df3a6030..0990d2bd15ee6 100644
--- a/doc/source/basics.rst
+++ b/doc/source/basics.rst
@@ -923,7 +923,7 @@ Passing a named function will yield that name for the row:
Aggregating with a dict
+++++++++++++++++++++++
-Passing a dictionary of column names to a scalar or a list of scalars, to ``DataFame.agg``
+Passing a dictionary of column names to a scalar or a list of scalars, to ``DataFrame.agg``
allows you to customize which functions are applied to which columns. Note that the results
are not in any particular order, you can use an ``OrderedDict`` instead to guarantee ordering.
diff --git a/doc/source/computation.rst b/doc/source/computation.rst
index 23699393958cf..14cfdbc364837 100644
--- a/doc/source/computation.rst
+++ b/doc/source/computation.rst
@@ -654,7 +654,7 @@ aggregation with, outputting a DataFrame:
r['A'].agg([np.sum, np.mean, np.std])
-On a widowed DataFrame, you can pass a list of functions to apply to each
+On a windowed DataFrame, you can pass a list of functions to apply to each
column, which produces an aggregated result with a hierarchical index:
.. ipython:: python
diff --git a/doc/source/groupby.rst b/doc/source/groupby.rst
index e1231b9a4a200..e9a7d8dd0a46e 100644
--- a/doc/source/groupby.rst
+++ b/doc/source/groupby.rst
@@ -561,7 +561,7 @@ must be either implemented on GroupBy or available via :ref:`dispatching
.. note::
- If you pass a dict to ``aggregate``, the ordering of the output colums is
+ If you pass a dict to ``aggregate``, the ordering of the output columns is
non-deterministic. If you want to be sure the output columns will be in a specific
order, you can use an ``OrderedDict``. Compare the output of the following two commands:
@@ -1211,7 +1211,7 @@ Groupby by Indexer to 'resample' data
Resampling produces new hypothetical samples (resamples) from already existing observed data or from a model that generates data. These new samples are similar to the pre-existing samples.
-In order to resample to work on indices that are non-datetimelike , the following procedure can be utilized.
+In order to resample to work on indices that are non-datetimelike, the following procedure can be utilized.
In the following examples, **df.index // 5** returns a binary array which is used to determine what gets selected for the groupby operation.
diff --git a/doc/source/indexing.rst b/doc/source/indexing.rst
index 8474116c38082..edbc4e6d7fd22 100644
--- a/doc/source/indexing.rst
+++ b/doc/source/indexing.rst
@@ -714,7 +714,7 @@ Finally, one can also set a seed for ``sample``'s random number generator using
Setting With Enlargement
------------------------
-The ``.loc/[]`` operations can perform enlargement when setting a non-existant key for that axis.
+The ``.loc/[]`` operations can perform enlargement when setting a non-existent key for that axis.
In the ``Series`` case this is effectively an appending operation
diff --git a/doc/source/io.rst b/doc/source/io.rst
index 8fbb23769492e..fcf7f6029197b 100644
--- a/doc/source/io.rst
+++ b/doc/source/io.rst
@@ -3077,7 +3077,7 @@ Compressed pickle files
.. versionadded:: 0.20.0
-:func:`read_pickle`, :meth:`DataFame.to_pickle` and :meth:`Series.to_pickle` can read
+:func:`read_pickle`, :meth:`DataFrame.to_pickle` and :meth:`Series.to_pickle` can read
and write compressed pickle files. The compression types of ``gzip``, ``bz2``, ``xz`` are supported for reading and writing.
`zip`` file supports read only and must contain only one data file
to be read in.
diff --git a/doc/source/merging.rst b/doc/source/merging.rst
index a5ee1b1a9384c..72787ea97a782 100644
--- a/doc/source/merging.rst
+++ b/doc/source/merging.rst
@@ -1329,7 +1329,7 @@ By default we are taking the asof of the quotes.
on='time',
by='ticker')
-We only asof within ``2ms`` betwen the quote time and the trade time.
+We only asof within ``2ms`` between the quote time and the trade time.
.. ipython:: python
@@ -1338,8 +1338,8 @@ We only asof within ``2ms`` betwen the quote time and the trade time.
by='ticker',
tolerance=pd.Timedelta('2ms'))
-We only asof within ``10ms`` betwen the quote time and the trade time and we exclude exact matches on time.
-Note that though we exclude the exact matches (of the quotes), prior quotes DO propogate to that point
+We only asof within ``10ms`` between the quote time and the trade time and we exclude exact matches on time.
+Note that though we exclude the exact matches (of the quotes), prior quotes DO propagate to that point
in time.
.. ipython:: python
diff --git a/doc/source/missing_data.rst b/doc/source/missing_data.rst
index 65b411ccd4af2..b33b5c304853a 100644
--- a/doc/source/missing_data.rst
+++ b/doc/source/missing_data.rst
@@ -320,7 +320,7 @@ Interpolation
The ``limit_direction`` keyword argument was added.
-Both Series and Dataframe objects have an ``interpolate`` method that, by default,
+Both Series and DataFrame objects have an ``interpolate`` method that, by default,
performs linear interpolation at missing datapoints.
.. ipython:: python
diff --git a/doc/source/options.rst b/doc/source/options.rst
index 1592caf90546c..f042e4d3f5120 100644
--- a/doc/source/options.rst
+++ b/doc/source/options.rst
@@ -313,9 +313,9 @@ display.large_repr truncate For DataFrames exceeding max_ro
display.latex.repr False Whether to produce a latex DataFrame
representation for jupyter frontends
that support it.
-display.latex.escape True Escapes special caracters in Dataframes, when
+display.latex.escape True Escapes special characters in DataFrames, when
using the to_latex method.
-display.latex.longtable False Specifies if the to_latex method of a Dataframe
+display.latex.longtable False Specifies if the to_latex method of a DataFrame
uses the longtable format.
display.latex.multicolumn True Combines columns when using a MultiIndex
display.latex.multicolumn_format 'l' Alignment of multicolumn labels
diff --git a/doc/source/reshaping.rst b/doc/source/reshaping.rst
index fab83222b313f..1209c4a8d6be8 100644
--- a/doc/source/reshaping.rst
+++ b/doc/source/reshaping.rst
@@ -156,7 +156,7 @@ the level numbers:
stacked.unstack('second')
Notice that the ``stack`` and ``unstack`` methods implicitly sort the index
-levels involved. Hence a call to ``stack`` and then ``unstack``, or viceversa,
+levels involved. Hence a call to ``stack`` and then ``unstack``, or vice versa,
will result in a **sorted** copy of the original DataFrame or Series:
.. ipython:: python
diff --git a/doc/source/sparse.rst b/doc/source/sparse.rst
index cf16cee501a3e..89efa7b4be3ee 100644
--- a/doc/source/sparse.rst
+++ b/doc/source/sparse.rst
@@ -132,7 +132,7 @@ dtype, ``fill_value`` default changes:
s.to_sparse()
You can change the dtype using ``.astype()``, the result is also sparse. Note that
-``.astype()`` also affects to the ``fill_value`` to keep its dense represantation.
+``.astype()`` also affects to the ``fill_value`` to keep its dense representation.
.. ipython:: python
diff --git a/doc/source/style.ipynb b/doc/source/style.ipynb
index c250787785e14..1d6ce163cf977 100644
--- a/doc/source/style.ipynb
+++ b/doc/source/style.ipynb
@@ -169,7 +169,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Notice the similarity with the standard `df.applymap`, which operates on DataFrames elementwise. We want you to be able to resuse your existing knowledge of how to interact with DataFrames.\n",
+ "Notice the similarity with the standard `df.applymap`, which operates on DataFrames elementwise. We want you to be able to reuse your existing knowledge of how to interact with DataFrames.\n",
"\n",
"Notice also that our function returned a string containing the CSS attribute and value, separated by a colon just like in a `<style>` tag. This will be a common theme.\n",
"\n",
diff --git a/doc/source/timeseries.rst b/doc/source/timeseries.rst
index 5422d5c53043d..3b8f105bb1b47 100644
--- a/doc/source/timeseries.rst
+++ b/doc/source/timeseries.rst
@@ -1054,7 +1054,7 @@ as ``BusinessHour`` except that it skips specified custom holidays.
# Tuesday after MLK Day (Monday is skipped because it's a holiday)
dt + bhour_us * 2
-You can use keyword arguments suported by either ``BusinessHour`` and ``CustomBusinessDay``.
+You can use keyword arguments supported by either ``BusinessHour`` and ``CustomBusinessDay``.
.. ipython:: python
@@ -1088,7 +1088,7 @@ frequencies. We will refer to these aliases as *offset aliases*.
"BMS", "business month start frequency"
"CBMS", "custom business month start frequency"
"Q", "quarter end frequency"
- "BQ", "business quarter endfrequency"
+ "BQ", "business quarter end frequency"
"QS", "quarter start frequency"
"BQS", "business quarter start frequency"
"A, Y", "year end frequency"
@@ -1132,13 +1132,13 @@ For some frequencies you can specify an anchoring suffix:
:header: "Alias", "Description"
:widths: 15, 100
- "W\-SUN", "weekly frequency (sundays). Same as 'W'"
- "W\-MON", "weekly frequency (mondays)"
- "W\-TUE", "weekly frequency (tuesdays)"
- "W\-WED", "weekly frequency (wednesdays)"
- "W\-THU", "weekly frequency (thursdays)"
- "W\-FRI", "weekly frequency (fridays)"
- "W\-SAT", "weekly frequency (saturdays)"
+ "W\-SUN", "weekly frequency (Sundays). Same as 'W'"
+ "W\-MON", "weekly frequency (Mondays)"
+ "W\-TUE", "weekly frequency (Tuesdays)"
+ "W\-WED", "weekly frequency (Wednesdays)"
+ "W\-THU", "weekly frequency (Thursdays)"
+ "W\-FRI", "weekly frequency (Fridays)"
+ "W\-SAT", "weekly frequency (Saturdays)"
"(B)Q(S)\-DEC", "quarterly frequency, year ends in December. Same as 'Q'"
"(B)Q(S)\-JAN", "quarterly frequency, year ends in January"
"(B)Q(S)\-FEB", "quarterly frequency, year ends in February"
diff --git a/doc/source/visualization.rst b/doc/source/visualization.rst
index b5a261e3acac5..82ad8de93514e 100644
--- a/doc/source/visualization.rst
+++ b/doc/source/visualization.rst
@@ -261,7 +261,7 @@ Histogram can be stacked by ``stacked=True``. Bin size can be changed by ``bins`
plt.close('all')
-You can pass other keywords supported by matplotlib ``hist``. For example, horizontal and cumulative histgram can be drawn by ``orientation='horizontal'`` and ``cumulative='True'``.
+You can pass other keywords supported by matplotlib ``hist``. For example, horizontal and cumulative histogram can be drawn by ``orientation='horizontal'`` and ``cumulative=True``.
.. ipython:: python
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index cccb094eaae7b..9f712a1cf039b 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -1475,7 +1475,7 @@ def func(arr, indexer, out, fill_value=np.nan):
def diff(arr, n, axis=0):
"""
difference of n between self,
- analagoust to s-s.shift(n)
+ analogous to s-s.shift(n)
Parameters
----------
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index 6e80f6c900386..d4df53d76398c 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -918,7 +918,7 @@ def take(self, indices, axis=0, allow_fill=True,
except ValueError:
# we need to coerce; migth have NA's in an
- # interger dtype
+ # integer dtype
new_left = taker(left.astype(float))
new_right = taker(right.astype(float))
diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py
index 9e180c624963c..4040c65136617 100644
--- a/pandas/core/reshape/concat.py
+++ b/pandas/core/reshape/concat.py
@@ -72,7 +72,7 @@ def concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,
The keys, levels, and names arguments are all optional.
A walkthrough of how this method fits in with other tools for combining
- panda objects can be found `here
+ pandas objects can be found `here
<http://pandas.pydata.org/pandas-docs/stable/merging.html>`__.
See Also
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 947300a28e510..6bb6988a7442a 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -447,7 +447,7 @@ def merge_asof(left, right, on=None,
3 2016-05-25 13:30:00.048 GOOG 720.92 100 720.50 720.93
4 2016-05-25 13:30:00.048 AAPL 98.00 100 NaN NaN
- We only asof within 2ms betwen the quote time and the trade time
+ We only asof within 2ms between the quote time and the trade time
>>> pd.merge_asof(trades, quotes,
... on='time',
@@ -460,9 +460,9 @@ def merge_asof(left, right, on=None,
3 2016-05-25 13:30:00.048 GOOG 720.92 100 720.50 720.93
4 2016-05-25 13:30:00.048 AAPL 98.00 100 NaN NaN
- We only asof within 10ms betwen the quote time and the trade time
+ We only asof within 10ms between the quote time and the trade time
and we exclude exact matches on time. However *prior* data will
- propogate forward
+ propagate forward
>>> pd.merge_asof(trades, quotes,
... on='time',
diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py
index 2f5538556fa6d..fda339aa30461 100644
--- a/pandas/core/reshape/tile.py
+++ b/pandas/core/reshape/tile.py
@@ -359,7 +359,7 @@ def _preprocess_for_cut(x):
"""
handles preprocessing for cut where we convert passed
input to array, strip the index information and store it
- seperately
+ separately
"""
x_is_series = isinstance(x, Series)
series_index = None
diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py
index ab689d196f4b6..51668bb6b0895 100644
--- a/pandas/io/formats/excel.py
+++ b/pandas/io/formats/excel.py
@@ -263,7 +263,7 @@ def build_font(self, props):
else None),
'strike': ('line-through' in decoration) or None,
'color': self.color_to_excel(props.get('color')),
- # shadow if nonzero digit before shadow colour
+ # shadow if nonzero digit before shadow color
'shadow': (bool(re.search('^[^#(]*[1-9]',
props['text-shadow']))
if 'text-shadow' in props else None),
@@ -304,7 +304,7 @@ def color_to_excel(self, val):
try:
return self.NAMED_COLORS[val]
except KeyError:
- warnings.warn('Unhandled colour format: {val!r}'.format(val=val),
+ warnings.warn('Unhandled color format: {val!r}'.format(val=val),
CSSWarning)
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index 712e9e9903f0a..9f819a4463bed 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -605,7 +605,7 @@ def open(self, mode='a', **kwargs):
except (Exception) as e:
- # trying to read from a non-existant file causes an error which
+ # trying to read from a non-existent file causes an error which
# is not part of IOError, make it one
if self._mode == 'r' and 'Unable to open/create file' in str(e):
raise IOError(str(e))
@@ -1621,7 +1621,7 @@ def __iter__(self):
def maybe_set_size(self, min_itemsize=None, **kwargs):
""" maybe set a string col itemsize:
- min_itemsize can be an interger or a dict with this columns name
+ min_itemsize can be an integer or a dict with this columns name
with an integer size """
if _ensure_decoded(self.kind) == u('string'):
@@ -1712,11 +1712,11 @@ def set_info(self, info):
self.__dict__.update(idx)
def get_attr(self):
- """ set the kind for this colummn """
+ """ set the kind for this column """
self.kind = getattr(self.attrs, self.kind_attr, None)
def set_attr(self):
- """ set the kind for this colummn """
+ """ set the kind for this column """
setattr(self.attrs, self.kind_attr, self.kind)
def read_metadata(self, handler):
@@ -2160,14 +2160,14 @@ def convert(self, values, nan_rep, encoding):
return self
def get_attr(self):
- """ get the data for this colummn """
+ """ get the data for this column """
self.values = getattr(self.attrs, self.kind_attr, None)
self.dtype = getattr(self.attrs, self.dtype_attr, None)
self.meta = getattr(self.attrs, self.meta_attr, None)
self.set_kind()
def set_attr(self):
- """ set the data for this colummn """
+ """ set the data for this column """
setattr(self.attrs, self.kind_attr, self.values)
setattr(self.attrs, self.meta_attr, self.meta)
if self.dtype is not None:
diff --git a/pandas/io/stata.py b/pandas/io/stata.py
index 92f180506a8b7..81862f9cd293e 100644
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -511,8 +511,8 @@ def _cast_to_stata_types(data):
this range. If the int64 values are outside of the range of those
perfectly representable as float64 values, a warning is raised.
- bool columns are cast to int8. uint colums are converted to int of the
- same size if there is no loss in precision, other wise are upcast to a
+ bool columns are cast to int8. uint columns are converted to int of the
+ same size if there is no loss in precision, otherwise are upcast to a
larger type. uint64 is currently not supported since it is concerted to
object in a DataFrame.
"""
diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py
index db2211fb55135..54f87febdc214 100644
--- a/pandas/plotting/_misc.py
+++ b/pandas/plotting/_misc.py
@@ -413,7 +413,7 @@ def parallel_coordinates(frame, class_column, cols=None, ax=None, color=None,
axvlines_kwds: keywords, optional
Options to be passed to axvline method for vertical lines
sort_labels: bool, False
- Sort class_column labels, useful when assigning colours
+ Sort class_column labels, useful when assigning colors
.. versionadded:: 0.20.0
diff --git a/pandas/plotting/_tools.py b/pandas/plotting/_tools.py
index 6deddc97915f1..c734855bdc09a 100644
--- a/pandas/plotting/_tools.py
+++ b/pandas/plotting/_tools.py
@@ -329,7 +329,7 @@ def _handle_shared_axes(axarr, nplots, naxes, nrows, ncols, sharex, sharey):
if ncols > 1:
for ax in axarr:
# only the first column should get y labels -> set all other to
- # off as we only have labels in teh first column and we always
+ # off as we only have labels in the first column and we always
# have a subplot there, we can skip the layout test
if ax.is_first_col():
continue
diff --git a/pandas/tests/frame/test_convert_to.py b/pandas/tests/frame/test_convert_to.py
index 99e5630ce6a43..5bdb76494f4c8 100644
--- a/pandas/tests/frame/test_convert_to.py
+++ b/pandas/tests/frame/test_convert_to.py
@@ -136,11 +136,11 @@ def test_to_records_with_unicode_index(self):
def test_to_records_with_unicode_column_names(self):
# xref issue: https://github.com/numpy/numpy/issues/2407
# Issue #11879. to_records used to raise an exception when used
- # with column names containing non ascii caracters in Python 2
+ # with column names containing non-ascii characters in Python 2
result = DataFrame(data={u"accented_name_é": [1.0]}).to_records()
# Note that numpy allows for unicode field names but dtypes need
- # to be specified using dictionnary intsead of list of tuples.
+ # to be specified using dictionary instead of list of tuples.
expected = np.rec.array(
[(0, 1.0)],
dtype={"names": ["index", u"accented_name_é"],
diff --git a/pandas/tests/groupby/test_transform.py b/pandas/tests/groupby/test_transform.py
index 98839a17d6e0c..267b67972c640 100644
--- a/pandas/tests/groupby/test_transform.py
+++ b/pandas/tests/groupby/test_transform.py
@@ -533,7 +533,7 @@ def test_cython_transform(self):
for (op, args), targop in ops:
if op != 'shift' and 'int' not in gb_target:
# numeric apply fastpath promotes dtype so have
- # to apply seperately and concat
+ # to apply separately and concat
i = gb[['int']].apply(targop)
f = gb[['float', 'float_missing']].apply(targop)
expected = pd.concat([f, i], axis=1)
diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py
index 5152c1019d8de..be27334384f6b 100644
--- a/pandas/tests/indexes/datetimes/test_tools.py
+++ b/pandas/tests/indexes/datetimes/test_tools.py
@@ -1144,7 +1144,7 @@ def test_parsers(self):
exp = DatetimeIndex([pd.Timestamp(expected)])
tm.assert_index_equal(res, exp)
- # these really need to have yearfist, but we don't support
+ # these really need to have yearfirst, but we don't support
if not yearfirst:
result5 = Timestamp(date_str)
assert result5 == expected
diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py
index e447a74b2b462..e097194674cf6 100644
--- a/pandas/tests/io/json/test_json_table_schema.py
+++ b/pandas/tests/io/json/test_json_table_schema.py
@@ -52,7 +52,7 @@ def test_series(self):
result = build_table_schema(s)
assert 'pandas_version' in result
- def tets_series_unnamed(self):
+ def test_series_unnamed(self):
result = build_table_schema(pd.Series([1, 2, 3]), version=False)
expected = {'fields': [{'name': 'index', 'type': 'integer'},
{'name': 'values', 'type': 'integer'}],
diff --git a/pandas/tests/io/parser/test_read_fwf.py b/pandas/tests/io/parser/test_read_fwf.py
index ec1d1a2a51cdc..a60f2b5a4c946 100644
--- a/pandas/tests/io/parser/test_read_fwf.py
+++ b/pandas/tests/io/parser/test_read_fwf.py
@@ -291,7 +291,7 @@ def test_full_file_with_spaces(self):
tm.assert_frame_equal(expected, read_fwf(StringIO(test)))
def test_full_file_with_spaces_and_missing(self):
- # File with spaces and missing values in columsn
+ # File with spaces and missing values in columns
test = """
Account Name Balance CreditLimit AccountCreated
101 10000.00 1/17/1998
diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py
index 9c488cb2389be..f331378b654be 100644
--- a/pandas/tests/io/test_pytables.py
+++ b/pandas/tests/io/test_pytables.py
@@ -1370,7 +1370,7 @@ def check_indexers(key, indexers):
labels=['l1'], items=['ItemA'], minor_axis=['B'])
assert_panel4d_equal(result, expected)
- # non-existant partial selection
+ # non-existent partial selection
result = store.select(
'p4d', "labels='l1' and items='Item1' and minor_axis='B'")
expected = p4d.reindex(labels=['l1'], items=[],
@@ -1980,11 +1980,11 @@ def test_append_misc(self):
with catch_warnings(record=True):
- # unsuported data types for non-tables
+ # unsupported data types for non-tables
p4d = tm.makePanel4D()
pytest.raises(TypeError, store.put, 'p4d', p4d)
- # unsuported data types
+ # unsupported data types
pytest.raises(TypeError, store.put, 'abc', None)
pytest.raises(TypeError, store.put, 'abc', '123')
pytest.raises(TypeError, store.put, 'abc', 123)
@@ -4965,7 +4965,7 @@ def test_preserve_timedeltaindex_type(self):
store['df'] = df
assert_frame_equal(store['df'], df)
- def test_colums_multiindex_modified(self):
+ def test_columns_multiindex_modified(self):
# BUG: 7212
# read_hdf store.select modified the passed columns parameters
# when multi-indexed.
diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py
index cff0c1c0b424e..eb10e70f4189b 100644
--- a/pandas/tests/plotting/test_datetimelike.py
+++ b/pandas/tests/plotting/test_datetimelike.py
@@ -347,7 +347,7 @@ def _test(ax):
assert int(result[0]) == expected[0].ordinal
assert int(result[1]) == expected[1].ordinal
- # datetim
+ # datetime
expected = (Period('1/1/2000', ax.freq),
Period('4/1/2000', ax.freq))
ax.set_xlim(datetime(2000, 1, 1), datetime(2000, 4, 1))
diff --git a/pandas/tests/series/test_dtypes.py b/pandas/tests/series/test_dtypes.py
index c214280ee8386..fa9feb016726e 100644
--- a/pandas/tests/series/test_dtypes.py
+++ b/pandas/tests/series/test_dtypes.py
@@ -279,7 +279,7 @@ def test_infer_objects_series(self):
expected = Series([1., 2., 3., np.nan])
tm.assert_series_equal(actual, expected)
- # only soft conversions, uncovertable pass thru unchanged
+ # only soft conversions, unconvertable pass thru unchanged
actual = (Series(np.array([1, 2, 3, None, 'a'], dtype='O'))
.infer_objects())
expected = Series([1, 2, 3, None, 'a'])
diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py
index 8a5f6bf110be3..1fa3c84dc0260 100644
--- a/pandas/tests/test_categorical.py
+++ b/pandas/tests/test_categorical.py
@@ -4064,7 +4064,7 @@ def test_merge(self):
expected = df.copy()
# object-cat
- # note that we propogate the category
+ # note that we propagate the category
# because we don't have any matching rows
cright = right.copy()
cright['d'] = cright['d'].astype('category')
diff --git a/pandas/tests/test_sorting.py b/pandas/tests/test_sorting.py
index e58042961129d..a5b12bbf9608a 100644
--- a/pandas/tests/test_sorting.py
+++ b/pandas/tests/test_sorting.py
@@ -408,7 +408,7 @@ def test_mixed_integer(self):
tm.assert_numpy_array_equal(result, expected)
tm.assert_numpy_array_equal(result_labels, expected_labels)
- def test_mixed_interger_from_list(self):
+ def test_mixed_integer_from_list(self):
values = ['b', 1, 0, 'a', 0, 'b']
result = safe_sort(values)
expected = np.array([0, 0, 1, 'a', 'b', 'b'], dtype=object)
diff --git a/pandas/tseries/util.py b/pandas/tseries/util.py
index 5934f5843736c..dc8a41215139d 100644
--- a/pandas/tseries/util.py
+++ b/pandas/tseries/util.py
@@ -16,7 +16,7 @@ def pivot_annual(series, freq=None):
The output has as many rows as distinct years in the original series,
and as many columns as the length of a leap year in the units corresponding
to the original frequency (366 for daily frequency, 366*24 for hourly...).
- The fist column of the output corresponds to Jan. 1st, 00:00:00,
+ The first column of the output corresponds to Jan. 1st, 00:00:00,
while the last column corresponds to Dec, 31st, 23:59:59.
Entries corresponding to Feb. 29th are masked for non-leap years.
| - [X] tests added / passed
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
Fixed some miscellaneous spelling errors. One test has been re-enabled after not running due to the prefix `tets_` being misspelled. Not technically a spelling error, but I changed colour -> color in a few places; seems reasonable since the 'u' is omitted in most cases when color is a parameter. Some changes were just to code comments, so not terribly useful, but makes reading comments a bit nicer.
| https://api.github.com/repos/pandas-dev/pandas/pulls/17535 | 2017-09-15T04:17:49Z | 2017-09-15T08:18:24Z | 2017-09-15T08:18:24Z | 2017-09-15T22:14:21Z |
remove period_helper from non-period reqs | diff --git a/setup.py b/setup.py
index 434ca64473916..664478cc35845 100755
--- a/setup.py
+++ b/setup.py
@@ -461,7 +461,6 @@ def pxd(name):
tseries_depends = ['pandas/_libs/src/datetime/np_datetime.h',
'pandas/_libs/src/datetime/np_datetime_strings.h',
- 'pandas/_libs/src/period_helper.h',
'pandas/_libs/src/datetime.pxd']
@@ -478,11 +477,11 @@ def pxd(name):
'pxdfiles': ['_libs/src/util'],
'depends': tseries_depends,
'sources': ['pandas/_libs/src/datetime/np_datetime.c',
- 'pandas/_libs/src/datetime/np_datetime_strings.c',
- 'pandas/_libs/src/period_helper.c']},
+ 'pandas/_libs/src/datetime/np_datetime_strings.c']},
'_libs.tslibs.timezones': {'pyxfile': '_libs/tslibs/timezones'},
'_libs.period': {'pyxfile': '_libs/period',
- 'depends': tseries_depends,
+ 'depends': (tseries_depends +
+ ['pandas/_libs/src/period_helper.h']),
'sources': ['pandas/_libs/src/datetime/np_datetime.c',
'pandas/_libs/src/datetime/np_datetime_strings.c',
'pandas/_libs/src/period_helper.c']},
| There are a bunch of other reqs that _could_ be removed (e.g. every direct reference to src/util, all of `lib_depends`), but at least `period_helper` it's obvious _why_ it belongs where it does.
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17531 | 2017-09-14T16:05:49Z | 2017-09-14T22:49:00Z | 2017-09-14T22:49:00Z | 2017-10-30T16:24:52Z |
BLD: fix inline warnings | diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx
index 3e8b5c4bd3feb..5bf9f4ce83cbf 100644
--- a/pandas/_libs/parsers.pyx
+++ b/pandas/_libs/parsers.pyx
@@ -255,7 +255,7 @@ cdef extern from "parser/tokenizer.h":
# inline int to_complex(char *item, double *p_real,
# double *p_imag, char sci, char decimal)
- inline int to_longlong(char *item, long long *p_value) nogil
+ int to_longlong(char *item, long long *p_value) nogil
# inline int to_longlong_thousands(char *item, long long *p_value,
# char tsep)
int to_boolean(const char *item, uint8_t *val) nogil
diff --git a/pandas/_libs/src/inference.pyx b/pandas/_libs/src/inference.pyx
index 2bb362eab4097..a2764e87eec55 100644
--- a/pandas/_libs/src/inference.pyx
+++ b/pandas/_libs/src/inference.pyx
@@ -1015,7 +1015,7 @@ cpdef bint is_interval_array(ndarray[object] values):
cdef extern from "parse_helper.h":
- inline int floatify(object, double *result, int *maybe_int) except -1
+ int floatify(object, double *result, int *maybe_int) except -1
# constants that will be compared to potentially arbitrarily large
# python int
diff --git a/pandas/_libs/src/khash.pxd b/pandas/_libs/src/khash.pxd
index adb0fe285dbb8..ba9a3c70097b2 100644
--- a/pandas/_libs/src/khash.pxd
+++ b/pandas/_libs/src/khash.pxd
@@ -11,13 +11,13 @@ cdef extern from "khash_python.h":
PyObject **keys
size_t *vals
- inline kh_pymap_t* kh_init_pymap()
- inline void kh_destroy_pymap(kh_pymap_t*)
- inline void kh_clear_pymap(kh_pymap_t*)
- inline khint_t kh_get_pymap(kh_pymap_t*, PyObject*)
- inline void kh_resize_pymap(kh_pymap_t*, khint_t)
- inline khint_t kh_put_pymap(kh_pymap_t*, PyObject*, int*)
- inline void kh_del_pymap(kh_pymap_t*, khint_t)
+ kh_pymap_t* kh_init_pymap()
+ void kh_destroy_pymap(kh_pymap_t*)
+ void kh_clear_pymap(kh_pymap_t*)
+ khint_t kh_get_pymap(kh_pymap_t*, PyObject*)
+ void kh_resize_pymap(kh_pymap_t*, khint_t)
+ khint_t kh_put_pymap(kh_pymap_t*, PyObject*, int*)
+ void kh_del_pymap(kh_pymap_t*, khint_t)
bint kh_exist_pymap(kh_pymap_t*, khiter_t)
@@ -27,13 +27,13 @@ cdef extern from "khash_python.h":
PyObject **keys
size_t *vals
- inline kh_pyset_t* kh_init_pyset()
- inline void kh_destroy_pyset(kh_pyset_t*)
- inline void kh_clear_pyset(kh_pyset_t*)
- inline khint_t kh_get_pyset(kh_pyset_t*, PyObject*)
- inline void kh_resize_pyset(kh_pyset_t*, khint_t)
- inline khint_t kh_put_pyset(kh_pyset_t*, PyObject*, int*)
- inline void kh_del_pyset(kh_pyset_t*, khint_t)
+ kh_pyset_t* kh_init_pyset()
+ void kh_destroy_pyset(kh_pyset_t*)
+ void kh_clear_pyset(kh_pyset_t*)
+ khint_t kh_get_pyset(kh_pyset_t*, PyObject*)
+ void kh_resize_pyset(kh_pyset_t*, khint_t)
+ khint_t kh_put_pyset(kh_pyset_t*, PyObject*, int*)
+ void kh_del_pyset(kh_pyset_t*, khint_t)
bint kh_exist_pyset(kh_pyset_t*, khiter_t)
@@ -45,13 +45,13 @@ cdef extern from "khash_python.h":
kh_cstr_t *keys
size_t *vals
- inline kh_str_t* kh_init_str() nogil
- inline void kh_destroy_str(kh_str_t*) nogil
- inline void kh_clear_str(kh_str_t*) nogil
- inline khint_t kh_get_str(kh_str_t*, kh_cstr_t) nogil
- inline void kh_resize_str(kh_str_t*, khint_t) nogil
- inline khint_t kh_put_str(kh_str_t*, kh_cstr_t, int*) nogil
- inline void kh_del_str(kh_str_t*, khint_t) nogil
+ kh_str_t* kh_init_str() nogil
+ void kh_destroy_str(kh_str_t*) nogil
+ void kh_clear_str(kh_str_t*) nogil
+ khint_t kh_get_str(kh_str_t*, kh_cstr_t) nogil
+ void kh_resize_str(kh_str_t*, khint_t) nogil
+ khint_t kh_put_str(kh_str_t*, kh_cstr_t, int*) nogil
+ void kh_del_str(kh_str_t*, khint_t) nogil
bint kh_exist_str(kh_str_t*, khiter_t) nogil
@@ -61,13 +61,13 @@ cdef extern from "khash_python.h":
int64_t *keys
size_t *vals
- inline kh_int64_t* kh_init_int64() nogil
- inline void kh_destroy_int64(kh_int64_t*) nogil
- inline void kh_clear_int64(kh_int64_t*) nogil
- inline khint_t kh_get_int64(kh_int64_t*, int64_t) nogil
- inline void kh_resize_int64(kh_int64_t*, khint_t) nogil
- inline khint_t kh_put_int64(kh_int64_t*, int64_t, int*) nogil
- inline void kh_del_int64(kh_int64_t*, khint_t) nogil
+ kh_int64_t* kh_init_int64() nogil
+ void kh_destroy_int64(kh_int64_t*) nogil
+ void kh_clear_int64(kh_int64_t*) nogil
+ khint_t kh_get_int64(kh_int64_t*, int64_t) nogil
+ void kh_resize_int64(kh_int64_t*, khint_t) nogil
+ khint_t kh_put_int64(kh_int64_t*, int64_t, int*) nogil
+ void kh_del_int64(kh_int64_t*, khint_t) nogil
bint kh_exist_int64(kh_int64_t*, khiter_t) nogil
@@ -79,13 +79,13 @@ cdef extern from "khash_python.h":
khuint64_t *keys
size_t *vals
- inline kh_uint64_t* kh_init_uint64() nogil
- inline void kh_destroy_uint64(kh_uint64_t*) nogil
- inline void kh_clear_uint64(kh_uint64_t*) nogil
- inline khint_t kh_get_uint64(kh_uint64_t*, int64_t) nogil
- inline void kh_resize_uint64(kh_uint64_t*, khint_t) nogil
- inline khint_t kh_put_uint64(kh_uint64_t*, int64_t, int*) nogil
- inline void kh_del_uint64(kh_uint64_t*, khint_t) nogil
+ kh_uint64_t* kh_init_uint64() nogil
+ void kh_destroy_uint64(kh_uint64_t*) nogil
+ void kh_clear_uint64(kh_uint64_t*) nogil
+ khint_t kh_get_uint64(kh_uint64_t*, int64_t) nogil
+ void kh_resize_uint64(kh_uint64_t*, khint_t) nogil
+ khint_t kh_put_uint64(kh_uint64_t*, int64_t, int*) nogil
+ void kh_del_uint64(kh_uint64_t*, khint_t) nogil
bint kh_exist_uint64(kh_uint64_t*, khiter_t) nogil
@@ -95,13 +95,13 @@ cdef extern from "khash_python.h":
float64_t *keys
size_t *vals
- inline kh_float64_t* kh_init_float64() nogil
- inline void kh_destroy_float64(kh_float64_t*) nogil
- inline void kh_clear_float64(kh_float64_t*) nogil
- inline khint_t kh_get_float64(kh_float64_t*, float64_t) nogil
- inline void kh_resize_float64(kh_float64_t*, khint_t) nogil
- inline khint_t kh_put_float64(kh_float64_t*, float64_t, int*) nogil
- inline void kh_del_float64(kh_float64_t*, khint_t) nogil
+ kh_float64_t* kh_init_float64() nogil
+ void kh_destroy_float64(kh_float64_t*) nogil
+ void kh_clear_float64(kh_float64_t*) nogil
+ khint_t kh_get_float64(kh_float64_t*, float64_t) nogil
+ void kh_resize_float64(kh_float64_t*, khint_t) nogil
+ khint_t kh_put_float64(kh_float64_t*, float64_t, int*) nogil
+ void kh_del_float64(kh_float64_t*, khint_t) nogil
bint kh_exist_float64(kh_float64_t*, khiter_t) nogil
@@ -111,13 +111,13 @@ cdef extern from "khash_python.h":
int32_t *keys
size_t *vals
- inline kh_int32_t* kh_init_int32() nogil
- inline void kh_destroy_int32(kh_int32_t*) nogil
- inline void kh_clear_int32(kh_int32_t*) nogil
- inline khint_t kh_get_int32(kh_int32_t*, int32_t) nogil
- inline void kh_resize_int32(kh_int32_t*, khint_t) nogil
- inline khint_t kh_put_int32(kh_int32_t*, int32_t, int*) nogil
- inline void kh_del_int32(kh_int32_t*, khint_t) nogil
+ kh_int32_t* kh_init_int32() nogil
+ void kh_destroy_int32(kh_int32_t*) nogil
+ void kh_clear_int32(kh_int32_t*) nogil
+ khint_t kh_get_int32(kh_int32_t*, int32_t) nogil
+ void kh_resize_int32(kh_int32_t*, khint_t) nogil
+ khint_t kh_put_int32(kh_int32_t*, int32_t, int*) nogil
+ void kh_del_int32(kh_int32_t*, khint_t) nogil
bint kh_exist_int32(kh_int32_t*, khiter_t) nogil
@@ -129,12 +129,12 @@ cdef extern from "khash_python.h":
kh_cstr_t *keys
PyObject **vals
- inline kh_strbox_t* kh_init_strbox() nogil
- inline void kh_destroy_strbox(kh_strbox_t*) nogil
- inline void kh_clear_strbox(kh_strbox_t*) nogil
- inline khint_t kh_get_strbox(kh_strbox_t*, kh_cstr_t) nogil
- inline void kh_resize_strbox(kh_strbox_t*, khint_t) nogil
- inline khint_t kh_put_strbox(kh_strbox_t*, kh_cstr_t, int*) nogil
- inline void kh_del_strbox(kh_strbox_t*, khint_t) nogil
+ kh_strbox_t* kh_init_strbox() nogil
+ void kh_destroy_strbox(kh_strbox_t*) nogil
+ void kh_clear_strbox(kh_strbox_t*) nogil
+ khint_t kh_get_strbox(kh_strbox_t*, kh_cstr_t) nogil
+ void kh_resize_strbox(kh_strbox_t*, khint_t) nogil
+ khint_t kh_put_strbox(kh_strbox_t*, kh_cstr_t, int*) nogil
+ void kh_del_strbox(kh_strbox_t*, khint_t) nogil
bint kh_exist_strbox(kh_strbox_t*, khiter_t) nogil
diff --git a/pandas/_libs/src/skiplist.pxd b/pandas/_libs/src/skiplist.pxd
index 69e9df5b542aa..214aa1c7aeaf0 100644
--- a/pandas/_libs/src/skiplist.pxd
+++ b/pandas/_libs/src/skiplist.pxd
@@ -14,9 +14,9 @@ cdef extern from "skiplist.h":
int size
int maxlevels
- inline skiplist_t* skiplist_init(int) nogil
- inline void skiplist_destroy(skiplist_t*) nogil
- inline double skiplist_get(skiplist_t*, int, int*) nogil
- inline int skiplist_insert(skiplist_t*, double) nogil
- inline int skiplist_remove(skiplist_t*, double) nogil
+ skiplist_t* skiplist_init(int) nogil
+ void skiplist_destroy(skiplist_t*) nogil
+ double skiplist_get(skiplist_t*, int, int*) nogil
+ int skiplist_insert(skiplist_t*, double) nogil
+ int skiplist_remove(skiplist_t*, double) nogil
diff --git a/pandas/_libs/src/util.pxd b/pandas/_libs/src/util.pxd
index 076bc1cd56003..f7a68c4ade71b 100644
--- a/pandas/_libs/src/util.pxd
+++ b/pandas/_libs/src/util.pxd
@@ -3,26 +3,26 @@ cimport numpy as cnp
cimport cpython
cdef extern from "numpy_helper.h":
- inline void set_array_owndata(ndarray ao)
- inline void set_array_not_contiguous(ndarray ao)
-
- inline int is_integer_object(object)
- inline int is_float_object(object)
- inline int is_complex_object(object)
- inline int is_bool_object(object)
- inline int is_string_object(object)
- inline int is_datetime64_object(object)
- inline int is_timedelta64_object(object)
- inline int assign_value_1d(ndarray, Py_ssize_t, object) except -1
- inline cnp.int64_t get_nat()
- inline object get_value_1d(ndarray, Py_ssize_t)
- inline int floatify(object, double*) except -1
- inline char *get_c_string(object) except NULL
- inline object char_to_string(char*)
- inline void transfer_object_column(char *dst, char *src, size_t stride,
+ void set_array_owndata(ndarray ao)
+ void set_array_not_contiguous(ndarray ao)
+
+ int is_integer_object(object)
+ int is_float_object(object)
+ int is_complex_object(object)
+ int is_bool_object(object)
+ int is_string_object(object)
+ int is_datetime64_object(object)
+ int is_timedelta64_object(object)
+ int assign_value_1d(ndarray, Py_ssize_t, object) except -1
+ cnp.int64_t get_nat()
+ object get_value_1d(ndarray, Py_ssize_t)
+ int floatify(object, double*) except -1
+ char *get_c_string(object) except NULL
+ object char_to_string(char*)
+ void transfer_object_column(char *dst, char *src, size_t stride,
size_t length)
object sarr_from_data(cnp.dtype, int length, void* data)
- inline object unbox_if_zerodim(object arr)
+ object unbox_if_zerodim(object arr)
ctypedef fused numeric:
cnp.int8_t
| Previous PR: https://github.com/pandas-dev/pandas/pull/17277 | https://api.github.com/repos/pandas-dev/pandas/pulls/17528 | 2017-09-14T02:46:30Z | 2017-09-23T02:52:56Z | 2017-09-23T02:52:56Z | 2017-10-30T16:23:27Z |
Cut/paste (most) remaining tz funcs to tslibs/timezones | diff --git a/pandas/_libs/period.pyx b/pandas/_libs/period.pyx
index 9e473a7f362b4..eef3c571ef37a 100644
--- a/pandas/_libs/period.pyx
+++ b/pandas/_libs/period.pyx
@@ -34,11 +34,9 @@ from lib cimport is_null_datetimelike, is_period
from pandas._libs import tslib, lib
from pandas._libs.tslib import (Timedelta, Timestamp, iNaT,
NaT)
-from tslibs.timezones cimport is_utc, is_tzlocal, get_utcoffset
-from tslib cimport (
- maybe_get_tz,
- _get_dst_info,
- _nat_scalar_rules)
+from tslibs.timezones cimport (
+ is_utc, is_tzlocal, get_utcoffset, _get_dst_info, maybe_get_tz)
+from tslib cimport _nat_scalar_rules
from tslibs.frequencies cimport get_freq_code
diff --git a/pandas/_libs/tslib.pxd b/pandas/_libs/tslib.pxd
index c1b25963a6257..ee8adfe67bb5e 100644
--- a/pandas/_libs/tslib.pxd
+++ b/pandas/_libs/tslib.pxd
@@ -2,7 +2,5 @@ from numpy cimport ndarray, int64_t
cdef convert_to_tsobject(object, object, object, bint, bint)
cpdef convert_to_timedelta64(object, object)
-cpdef object maybe_get_tz(object)
-cdef object _get_dst_info(object)
cdef bint _nat_scalar_rules[6]
cdef bint _check_all_nulls(obj)
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx
index 629325c28ea9c..ec12611ae7f02 100644
--- a/pandas/_libs/tslib.pyx
+++ b/pandas/_libs/tslib.pyx
@@ -21,8 +21,7 @@ from cpython cimport (
PyObject_RichCompare,
Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE,
PyUnicode_Check,
- PyUnicode_AsUTF8String,
-)
+ PyUnicode_AsUTF8String)
cdef extern from "Python.h":
cdef PyTypeObject *Py_TYPE(object)
@@ -73,19 +72,12 @@ import re
# dateutil compat
from dateutil.tz import (tzoffset, tzlocal as _dateutil_tzlocal,
- tzfile as _dateutil_tzfile,
tzutc as _dateutil_tzutc,
tzstr as _dateutil_tzstr)
-from pandas.compat import is_platform_windows
-if is_platform_windows():
- from dateutil.zoneinfo import gettz as _dateutil_gettz
-else:
- from dateutil.tz import gettz as _dateutil_gettz
from dateutil.relativedelta import relativedelta
from dateutil.parser import DEFAULTPARSER
-from pytz.tzinfo import BaseTzInfo as _pytz_BaseTzInfo
from pandas.compat import (parse_date, string_types, iteritems,
StringIO, callable)
@@ -108,11 +100,17 @@ iNaT = NPY_NAT
from tslibs.timezones cimport (
- is_utc, is_tzlocal,
+ is_utc, is_tzlocal, _is_fixed_offset,
treat_tz_as_dateutil, treat_tz_as_pytz,
- get_timezone,
- get_utcoffset)
-from tslibs.timezones import get_timezone, get_utcoffset # noqa
+ get_timezone, get_utcoffset, maybe_get_tz,
+ _get_dst_info
+ )
+from tslibs.timezones import ( # noqa
+ get_timezone, get_utcoffset, maybe_get_tz,
+ _p_tz_cache_key, dst_cache,
+ _unbox_utcoffsets,
+ _dateutil_gettz
+ )
cdef inline object create_timestamp_from_ts(
@@ -241,20 +239,6 @@ def ints_to_pytimedelta(ndarray[int64_t] arr, box=False):
return result
-cdef inline bint _is_fixed_offset(object tz):
- if treat_tz_as_dateutil(tz):
- if len(tz._trans_idx) == 0 and len(tz._trans_list) == 0:
- return 1
- else:
- return 0
- elif treat_tz_as_pytz(tz):
- if (len(tz._transition_info) == 0
- and len(tz._utc_transition_times) == 0):
- return 1
- else:
- return 0
- return 1
-
_zero_time = datetime_time(0, 0)
_no_input = object()
@@ -1709,27 +1693,6 @@ def _localize_pydatetime(object dt, object tz):
return dt.replace(tzinfo=tz)
-cpdef inline object maybe_get_tz(object tz):
- """
- (Maybe) Construct a timezone object from a string. If tz is a string, use
- it to construct a timezone object. Otherwise, just return tz.
- """
- if isinstance(tz, string_types):
- if tz == 'tzlocal()':
- tz = _dateutil_tzlocal()
- elif tz.startswith('dateutil/'):
- zone = tz[9:]
- tz = _dateutil_gettz(zone)
- # On Python 3 on Windows, the filename is not always set correctly.
- if isinstance(tz, _dateutil_tzfile) and '.tar.gz' in tz._filename:
- tz._filename = zone
- else:
- tz = pytz.timezone(tz)
- elif is_integer_object(tz):
- tz = pytz.FixedOffset(tz / 60)
- return tz
-
-
class OutOfBoundsDatetime(ValueError):
pass
@@ -4237,141 +4200,6 @@ def tz_convert_single(int64_t val, object tz1, object tz2):
offset = deltas[pos]
return utc_date + offset
-# Timezone data caches, key is the pytz string or dateutil file name.
-dst_cache = {}
-
-
-def _p_tz_cache_key(tz):
- """ Python interface for cache function to facilitate testing."""
- return _tz_cache_key(tz)
-
-
-cdef inline object _tz_cache_key(object tz):
- """
- Return the key in the cache for the timezone info object or None
- if unknown.
-
- The key is currently the tz string for pytz timezones, the filename for
- dateutil timezones.
-
- Notes
- =====
- This cannot just be the hash of a timezone object. Unfortunately, the
- hashes of two dateutil tz objects which represent the same timezone are
- not equal (even though the tz objects will compare equal and represent
- the same tz file). Also, pytz objects are not always hashable so we use
- str(tz) instead.
- """
- if isinstance(tz, _pytz_BaseTzInfo):
- return tz.zone
- elif isinstance(tz, _dateutil_tzfile):
- if '.tar.gz' in tz._filename:
- raise ValueError('Bad tz filename. Dateutil on python 3 on '
- 'windows has a bug which causes tzfile._filename '
- 'to be the same for all timezone files. Please '
- 'construct dateutil timezones implicitly by '
- 'passing a string like "dateutil/Europe/London" '
- 'when you construct your pandas objects instead '
- 'of passing a timezone object. See '
- 'https://github.com/pandas-dev/pandas/pull/7362')
- return 'dateutil' + tz._filename
- else:
- return None
-
-
-cdef object _get_dst_info(object tz):
- """
- return a tuple of :
- (UTC times of DST transitions,
- UTC offsets in microseconds corresponding to DST transitions,
- string of type of transitions)
-
- """
- cache_key = _tz_cache_key(tz)
- if cache_key is None:
- num = int(get_utcoffset(tz, None).total_seconds()) * 1000000000
- return (np.array([NPY_NAT + 1], dtype=np.int64),
- np.array([num], dtype=np.int64),
- None)
-
- if cache_key not in dst_cache:
- if treat_tz_as_pytz(tz):
- trans = np.array(tz._utc_transition_times, dtype='M8[ns]')
- trans = trans.view('i8')
- try:
- if tz._utc_transition_times[0].year == 1:
- trans[0] = NPY_NAT + 1
- except Exception:
- pass
- deltas = _unbox_utcoffsets(tz._transition_info)
- typ = 'pytz'
-
- elif treat_tz_as_dateutil(tz):
- if len(tz._trans_list):
- # get utc trans times
- trans_list = _get_utc_trans_times_from_dateutil_tz(tz)
- trans = np.hstack([
- np.array([0], dtype='M8[s]'), # place holder for first item
- np.array(trans_list, dtype='M8[s]')]).astype(
- 'M8[ns]') # all trans listed
- trans = trans.view('i8')
- trans[0] = NPY_NAT + 1
-
- # deltas
- deltas = np.array([v.offset for v in (
- tz._ttinfo_before,) + tz._trans_idx], dtype='i8')
- deltas *= 1000000000
- typ = 'dateutil'
-
- elif _is_fixed_offset(tz):
- trans = np.array([NPY_NAT + 1], dtype=np.int64)
- deltas = np.array([tz._ttinfo_std.offset],
- dtype='i8') * 1000000000
- typ = 'fixed'
- else:
- trans = np.array([], dtype='M8[ns]')
- deltas = np.array([], dtype='i8')
- typ = None
-
- else:
- # static tzinfo
- trans = np.array([NPY_NAT + 1], dtype=np.int64)
- num = int(get_utcoffset(tz, None).total_seconds()) * 1000000000
- deltas = np.array([num], dtype=np.int64)
- typ = 'static'
-
- dst_cache[cache_key] = (trans, deltas, typ)
-
- return dst_cache[cache_key]
-
-cdef object _get_utc_trans_times_from_dateutil_tz(object tz):
- """
- Transition times in dateutil timezones are stored in local non-dst
- time. This code converts them to UTC. It's the reverse of the code
- in dateutil.tz.tzfile.__init__.
- """
- new_trans = list(tz._trans_list)
- last_std_offset = 0
- for i, (trans, tti) in enumerate(zip(tz._trans_list, tz._trans_idx)):
- if not tti.isdst:
- last_std_offset = tti.offset
- new_trans[i] = trans - last_std_offset
- return new_trans
-
-
-cpdef ndarray _unbox_utcoffsets(object transinfo):
- cdef:
- Py_ssize_t i, sz
- ndarray[int64_t] arr
-
- sz = len(transinfo)
- arr = np.empty(sz, dtype='i8')
-
- for i in range(sz):
- arr[i] = int(transinfo[i][0].total_seconds()) * 1000000000
-
- return arr
-
@cython.boundscheck(False)
@cython.wraparound(False)
diff --git a/pandas/_libs/tslibs/timezones.pxd b/pandas/_libs/tslibs/timezones.pxd
index ead5566440ca0..fac0018a78bc2 100644
--- a/pandas/_libs/tslibs/timezones.pxd
+++ b/pandas/_libs/tslibs/timezones.pxd
@@ -1,6 +1,8 @@
# -*- coding: utf-8 -*-
# cython: profile=False
+from numpy cimport ndarray
+
cdef bint is_utc(object tz)
cdef bint is_tzlocal(object tz)
@@ -8,5 +10,9 @@ cdef bint treat_tz_as_pytz(object tz)
cdef bint treat_tz_as_dateutil(object tz)
cpdef object get_timezone(object tz)
+cpdef object maybe_get_tz(object tz)
cpdef get_utcoffset(tzinfo, obj)
+cdef bint _is_fixed_offset(object tz)
+
+cdef object _get_dst_info(object tz)
diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx
index 3db369a09ba2d..346da41e7073b 100644
--- a/pandas/_libs/tslibs/timezones.pyx
+++ b/pandas/_libs/tslibs/timezones.pyx
@@ -1,15 +1,40 @@
# -*- coding: utf-8 -*-
# cython: profile=False
+cimport cython
+from cython cimport Py_ssize_t
+
# dateutil compat
from dateutil.tz import (
- tzutc as _dateutil_tzutc,
- tzlocal as _dateutil_tzlocal)
+ tzutc as _dateutil_tzutc,
+ tzlocal as _dateutil_tzlocal,
+ tzfile as _dateutil_tzfile)
+
+import sys
+if sys.platform == 'win32' or sys.platform == 'cygwin':
+ # equiv pd.compat.is_platform_windows()
+ from dateutil.zoneinfo import gettz as _dateutil_gettz
+else:
+ from dateutil.tz import gettz as _dateutil_gettz
+
+from pytz.tzinfo import BaseTzInfo as _pytz_BaseTzInfo
import pytz
UTC = pytz.utc
+import numpy as np
+cimport numpy as np
+from numpy cimport ndarray, int64_t
+np.import_array()
+
+# ----------------------------------------------------------------------
+from util cimport is_string_object, is_integer_object, get_nat
+
+cdef int64_t NPY_NAT = get_nat()
+
+# ----------------------------------------------------------------------
+
cdef inline bint is_utc(object tz):
return tz is UTC or isinstance(tz, _dateutil_tzutc)
@@ -64,6 +89,70 @@ cpdef inline object get_timezone(object tz):
except AttributeError:
return tz
+
+cpdef inline object maybe_get_tz(object tz):
+ """
+ (Maybe) Construct a timezone object from a string. If tz is a string, use
+ it to construct a timezone object. Otherwise, just return tz.
+ """
+ if is_string_object(tz):
+ if tz == 'tzlocal()':
+ tz = _dateutil_tzlocal()
+ elif tz.startswith('dateutil/'):
+ zone = tz[9:]
+ tz = _dateutil_gettz(zone)
+ # On Python 3 on Windows, the filename is not always set correctly.
+ if isinstance(tz, _dateutil_tzfile) and '.tar.gz' in tz._filename:
+ tz._filename = zone
+ else:
+ tz = pytz.timezone(tz)
+ elif is_integer_object(tz):
+ tz = pytz.FixedOffset(tz / 60)
+ return tz
+
+
+def _p_tz_cache_key(tz):
+ """ Python interface for cache function to facilitate testing."""
+ return _tz_cache_key(tz)
+
+
+# Timezone data caches, key is the pytz string or dateutil file name.
+dst_cache = {}
+
+
+cdef inline object _tz_cache_key(object tz):
+ """
+ Return the key in the cache for the timezone info object or None
+ if unknown.
+
+ The key is currently the tz string for pytz timezones, the filename for
+ dateutil timezones.
+
+ Notes
+ =====
+ This cannot just be the hash of a timezone object. Unfortunately, the
+ hashes of two dateutil tz objects which represent the same timezone are
+ not equal (even though the tz objects will compare equal and represent
+ the same tz file). Also, pytz objects are not always hashable so we use
+ str(tz) instead.
+ """
+ if isinstance(tz, _pytz_BaseTzInfo):
+ return tz.zone
+ elif isinstance(tz, _dateutil_tzfile):
+ if '.tar.gz' in tz._filename:
+ raise ValueError('Bad tz filename. Dateutil on python 3 on '
+ 'windows has a bug which causes tzfile._filename '
+ 'to be the same for all timezone files. Please '
+ 'construct dateutil timezones implicitly by '
+ 'passing a string like "dateutil/Europe/London" '
+ 'when you construct your pandas objects instead '
+ 'of passing a timezone object. See '
+ 'https://github.com/pandas-dev/pandas/pull/7362')
+ return 'dateutil' + tz._filename
+ else:
+ return None
+
+
#----------------------------------------------------------------------
# UTC Offsets
@@ -72,3 +161,117 @@ cpdef get_utcoffset(tzinfo, obj):
return tzinfo._utcoffset
except AttributeError:
return tzinfo.utcoffset(obj)
+
+
+cdef inline bint _is_fixed_offset(object tz):
+ if treat_tz_as_dateutil(tz):
+ if len(tz._trans_idx) == 0 and len(tz._trans_list) == 0:
+ return 1
+ else:
+ return 0
+ elif treat_tz_as_pytz(tz):
+ if (len(tz._transition_info) == 0
+ and len(tz._utc_transition_times) == 0):
+ return 1
+ else:
+ return 0
+ return 1
+
+
+cdef object _get_utc_trans_times_from_dateutil_tz(object tz):
+ """
+ Transition times in dateutil timezones are stored in local non-dst
+ time. This code converts them to UTC. It's the reverse of the code
+ in dateutil.tz.tzfile.__init__.
+ """
+ new_trans = list(tz._trans_list)
+ last_std_offset = 0
+ for i, (trans, tti) in enumerate(zip(tz._trans_list, tz._trans_idx)):
+ if not tti.isdst:
+ last_std_offset = tti.offset
+ new_trans[i] = trans - last_std_offset
+ return new_trans
+
+
+cpdef ndarray _unbox_utcoffsets(object transinfo):
+ cdef:
+ Py_ssize_t i, sz
+ ndarray[int64_t] arr
+
+ sz = len(transinfo)
+ arr = np.empty(sz, dtype='i8')
+
+ for i in range(sz):
+ arr[i] = int(transinfo[i][0].total_seconds()) * 1000000000
+
+ return arr
+
+
+# ----------------------------------------------------------------------
+# Daylight Savings
+
+
+cdef object _get_dst_info(object tz):
+ """
+ return a tuple of :
+ (UTC times of DST transitions,
+ UTC offsets in microseconds corresponding to DST transitions,
+ string of type of transitions)
+
+ """
+ cache_key = _tz_cache_key(tz)
+ if cache_key is None:
+ num = int(get_utcoffset(tz, None).total_seconds()) * 1000000000
+ return (np.array([NPY_NAT + 1], dtype=np.int64),
+ np.array([num], dtype=np.int64),
+ None)
+
+ if cache_key not in dst_cache:
+ if treat_tz_as_pytz(tz):
+ trans = np.array(tz._utc_transition_times, dtype='M8[ns]')
+ trans = trans.view('i8')
+ try:
+ if tz._utc_transition_times[0].year == 1:
+ trans[0] = NPY_NAT + 1
+ except Exception:
+ pass
+ deltas = _unbox_utcoffsets(tz._transition_info)
+ typ = 'pytz'
+
+ elif treat_tz_as_dateutil(tz):
+ if len(tz._trans_list):
+ # get utc trans times
+ trans_list = _get_utc_trans_times_from_dateutil_tz(tz)
+ trans = np.hstack([
+ np.array([0], dtype='M8[s]'), # place holder for first item
+ np.array(trans_list, dtype='M8[s]')]).astype(
+ 'M8[ns]') # all trans listed
+ trans = trans.view('i8')
+ trans[0] = NPY_NAT + 1
+
+ # deltas
+ deltas = np.array([v.offset for v in (
+ tz._ttinfo_before,) + tz._trans_idx], dtype='i8')
+ deltas *= 1000000000
+ typ = 'dateutil'
+
+ elif _is_fixed_offset(tz):
+ trans = np.array([NPY_NAT + 1], dtype=np.int64)
+ deltas = np.array([tz._ttinfo_std.offset],
+ dtype='i8') * 1000000000
+ typ = 'fixed'
+ else:
+ trans = np.array([], dtype='M8[ns]')
+ deltas = np.array([], dtype='i8')
+ typ = None
+
+ else:
+ # static tzinfo
+ trans = np.array([NPY_NAT + 1], dtype=np.int64)
+ num = int(get_utcoffset(tz, None).total_seconds()) * 1000000000
+ deltas = np.array([num], dtype=np.int64)
+ typ = 'static'
+
+ dst_cache[cache_key] = (trans, deltas, typ)
+
+ return dst_cache[cache_key]
| We're very nearly done with `tslibs.timezones`. I had hoped to bring over the remaining functions in smaller chunks, but this turns out to be the smallest independent subset that contains `_get_dst_info` and `maybe_get_tz`.
Getting `_get_dst_info` and `maybe_get_tz` separated is a milestone because it allows us to move `tseries.frequencies.Resolution` and related functions into cython without having a dependency on `tslib`. This in turn gets the dependency on `khash` out of `tslib`. A few more nice things become feasible.
This is _almost_ pure cut/paste. The only change I made was replacing `isinstance(tz, string_types)` with `is_string_object(tz)`. If requested, I'll do a follow-up to de-privatize the names.
`timezones` is within spitting distance of being valid python. Getting it over that hump would allow linting and coverage that is tough as it is.
Note that if/when #17363 is merged, a bunch of residual imports in `tslib` can be cleaned up.
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17526 | 2017-09-14T01:41:21Z | 2017-09-15T09:51:47Z | 2017-09-15T09:51:47Z | 2017-09-15T15:30:31Z |
Remove from numpy cimport * | diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx
index 897a60e0c2f21..8cbc65633c786 100644
--- a/pandas/_libs/algos.pyx
+++ b/pandas/_libs/algos.pyx
@@ -1,12 +1,12 @@
# cython: profile=False
-from numpy cimport *
cimport numpy as np
import numpy as np
cimport cython
+from cython cimport Py_ssize_t
-import_array()
+np.import_array()
cdef float64_t FP_ERR = 1e-13
@@ -15,31 +15,19 @@ cimport util
from libc.stdlib cimport malloc, free
from libc.string cimport memmove
-from numpy cimport NPY_INT8 as NPY_int8
-from numpy cimport NPY_INT16 as NPY_int16
-from numpy cimport NPY_INT32 as NPY_int32
-from numpy cimport NPY_INT64 as NPY_int64
-from numpy cimport NPY_FLOAT16 as NPY_float16
-from numpy cimport NPY_FLOAT32 as NPY_float32
-from numpy cimport NPY_FLOAT64 as NPY_float64
-
-from numpy cimport (int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t,
- uint32_t, uint64_t, float16_t, float32_t, float64_t)
-
-int8 = np.dtype(np.int8)
-int16 = np.dtype(np.int16)
-int32 = np.dtype(np.int32)
-int64 = np.dtype(np.int64)
-float16 = np.dtype(np.float16)
-float32 = np.dtype(np.float32)
-float64 = np.dtype(np.float64)
+from numpy cimport (ndarray,
+ NPY_INT64, NPY_UINT64, NPY_INT32, NPY_INT16, NPY_INT8,
+ NPY_FLOAT32, NPY_FLOAT64,
+ NPY_OBJECT,
+ int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t,
+ uint32_t, uint64_t, float16_t, float32_t, float64_t,
+ double_t)
+
cdef double NaN = <double> np.NaN
cdef double nan = NaN
-cdef extern from "../src/headers/math.h":
- double sqrt(double x) nogil
- double fabs(double) nogil
+from libc.math cimport sqrt, fabs
# this is our util.pxd
from util cimport numeric, get_nat
diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx
index c6ff602cfef1c..9500e685367c8 100644
--- a/pandas/_libs/groupby.pyx
+++ b/pandas/_libs/groupby.pyx
@@ -1,16 +1,17 @@
# cython: profile=False
-from numpy cimport *
-cimport numpy as np
+cimport numpy as cnp
import numpy as np
cimport cython
-import_array()
+cnp.import_array()
cimport util
-from numpy cimport (int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t,
+from numpy cimport (ndarray,
+ double_t,
+ int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t,
uint32_t, uint64_t, float16_t, float32_t, float64_t)
from libc.stdlib cimport malloc, free
diff --git a/pandas/_libs/hashtable.pyx b/pandas/_libs/hashtable.pyx
index 2462b7af7b0fe..9aeb700dd5923 100644
--- a/pandas/_libs/hashtable.pyx
+++ b/pandas/_libs/hashtable.pyx
@@ -23,7 +23,7 @@ from khash cimport (
kh_put_pymap, kh_resize_pymap)
-from numpy cimport *
+from numpy cimport ndarray, uint8_t, uint32_t
from libc.stdlib cimport malloc, free
from cpython cimport (PyMem_Malloc, PyMem_Realloc, PyMem_Free,
@@ -56,8 +56,6 @@ cdef extern from "datetime.h":
PyDateTime_IMPORT
-cdef extern from "Python.h":
- int PySlice_Check(object)
cdef size_t _INIT_VEC_CAP = 128
diff --git a/pandas/_libs/interval.pyx b/pandas/_libs/interval.pyx
index e287e1fc8bdaf..bfbda9696ff2b 100644
--- a/pandas/_libs/interval.pyx
+++ b/pandas/_libs/interval.pyx
@@ -1,11 +1,10 @@
cimport numpy as np
import numpy as np
-import pandas as pd
cimport util
cimport cython
import cython
-from numpy cimport *
+from numpy cimport ndarray
from tslib import Timestamp
from cpython.object cimport (Py_EQ, Py_NE, Py_GT, Py_LT, Py_GE, Py_LE,
diff --git a/pandas/_libs/intervaltree.pxi.in b/pandas/_libs/intervaltree.pxi.in
index 4fa0d6d156fa2..b22e694c9fcca 100644
--- a/pandas/_libs/intervaltree.pxi.in
+++ b/pandas/_libs/intervaltree.pxi.in
@@ -4,11 +4,15 @@ Template for intervaltree
WARNING: DO NOT edit .pxi FILE directly, .pxi is generated from .pxi.in
"""
-from numpy cimport int64_t, float64_t
-from numpy cimport ndarray, PyArray_ArgSort, NPY_QUICKSORT, PyArray_Take
+from numpy cimport (
+ int64_t, int32_t, float64_t, float32_t,
+ ndarray,
+ PyArray_ArgSort, NPY_QUICKSORT, PyArray_Take)
import numpy as np
cimport cython
+from cython cimport Py_ssize_t
+
cimport numpy as cnp
cnp.import_array()
diff --git a/pandas/_libs/join.pyx b/pandas/_libs/join.pyx
index 385a9762ed90d..503bdda75875f 100644
--- a/pandas/_libs/join.pyx
+++ b/pandas/_libs/join.pyx
@@ -1,34 +1,19 @@
# cython: profile=False
-from numpy cimport *
cimport numpy as np
import numpy as np
cimport cython
+from cython cimport Py_ssize_t
-import_array()
+np.import_array()
cimport util
-from numpy cimport NPY_INT8 as NPY_int8
-from numpy cimport NPY_INT16 as NPY_int16
-from numpy cimport NPY_INT32 as NPY_int32
-from numpy cimport NPY_INT64 as NPY_int64
-from numpy cimport NPY_FLOAT16 as NPY_float16
-from numpy cimport NPY_FLOAT32 as NPY_float32
-from numpy cimport NPY_FLOAT64 as NPY_float64
-
-from numpy cimport (int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t,
+from numpy cimport (ndarray,
+ int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t,
uint32_t, uint64_t, float16_t, float32_t, float64_t)
-int8 = np.dtype(np.int8)
-int16 = np.dtype(np.int16)
-int32 = np.dtype(np.int32)
-int64 = np.dtype(np.int64)
-float16 = np.dtype(np.float16)
-float32 = np.dtype(np.float32)
-float64 = np.dtype(np.float64)
-
cdef double NaN = <double> np.NaN
cdef double nan = NaN
diff --git a/pandas/_libs/reshape.pyx b/pandas/_libs/reshape.pyx
index 82851b7e80994..d6996add374a9 100644
--- a/pandas/_libs/reshape.pyx
+++ b/pandas/_libs/reshape.pyx
@@ -1,34 +1,19 @@
# cython: profile=False
-from numpy cimport *
cimport numpy as np
import numpy as np
cimport cython
+from cython cimport Py_ssize_t
-import_array()
+np.import_array()
cimport util
-from numpy cimport NPY_INT8 as NPY_int8
-from numpy cimport NPY_INT16 as NPY_int16
-from numpy cimport NPY_INT32 as NPY_int32
-from numpy cimport NPY_INT64 as NPY_int64
-from numpy cimport NPY_FLOAT16 as NPY_float16
-from numpy cimport NPY_FLOAT32 as NPY_float32
-from numpy cimport NPY_FLOAT64 as NPY_float64
-
-from numpy cimport (int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t,
+from numpy cimport (ndarray,
+ int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t,
uint32_t, uint64_t, float16_t, float32_t, float64_t)
-int8 = np.dtype(np.int8)
-int16 = np.dtype(np.int16)
-int32 = np.dtype(np.int32)
-int64 = np.dtype(np.int64)
-float16 = np.dtype(np.float16)
-float32 = np.dtype(np.float32)
-float64 = np.dtype(np.float64)
-
cdef double NaN = <double> np.NaN
cdef double nan = NaN
diff --git a/pandas/_libs/src/reduce.pyx b/pandas/_libs/src/reduce.pyx
index 3ce94022e586b..f578eb2f4a346 100644
--- a/pandas/_libs/src/reduce.pyx
+++ b/pandas/_libs/src/reduce.pyx
@@ -1,5 +1,4 @@
#cython=False
-from numpy cimport *
import numpy as np
from distutils.version import LooseVersion
| Replace these imports with explicit imports.
There are a couple of other similar things coming up, splitting them apart for easier review.
There are a couple of places with `cdef extern from "../src/headers/math.h":` but I don't think the path here makes sense. The fact that it works anyway bothers me. This PR changes one such occurrence as a demonstration, leaves the others for the next PR.
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17521 | 2017-09-13T20:33:53Z | 2017-09-17T15:05:44Z | 2017-09-17T15:05:44Z | 2017-10-30T16:24:48Z |
BUG: preserve name in set_categories (#17509) | diff --git a/doc/source/categorical.rst b/doc/source/categorical.rst
index 8835c4a1533d0..65361886436d6 100644
--- a/doc/source/categorical.rst
+++ b/doc/source/categorical.rst
@@ -146,6 +146,8 @@ Using ``.describe()`` on categorical data will produce similar output to a `Seri
df.describe()
df["cat"].describe()
+.. _categorical.cat:
+
Working with categories
-----------------------
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index 52e056103cbdc..d192166f620f2 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -566,6 +566,7 @@ Categorical
- Bug in the categorical constructor with empty values and categories causing
the ``.categories`` to be an empty ``Float64Index`` rather than an empty
``Index`` with object dtype (:issue:`17248`)
+- Bug in categorical operations with :ref:`Series.cat <categorical.cat>' not preserving the original Series' name (:issue:`17509`)
PyPy
^^^^
diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py
index e67ce2936819f..ddca93f07ad5e 100644
--- a/pandas/core/categorical.py
+++ b/pandas/core/categorical.py
@@ -2054,9 +2054,10 @@ class CategoricalAccessor(PandasDelegate, NoNewAttributesMixin):
"""
- def __init__(self, values, index):
+ def __init__(self, values, index, name):
self.categorical = values
self.index = index
+ self.name = name
self._freeze()
def _delegate_property_get(self, name):
@@ -2075,14 +2076,15 @@ def _delegate_method(self, name, *args, **kwargs):
method = getattr(self.categorical, name)
res = method(*args, **kwargs)
if res is not None:
- return Series(res, index=self.index)
+ return Series(res, index=self.index, name=self.name)
@classmethod
def _make_accessor(cls, data):
if not is_categorical_dtype(data.dtype):
raise AttributeError("Can only use .cat accessor with a "
"'category' dtype")
- return CategoricalAccessor(data.values, data.index)
+ return CategoricalAccessor(data.values, data.index,
+ getattr(data, 'name', None),)
CategoricalAccessor._add_delegate_accessors(delegate=Categorical,
diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py
index 1fa3c84dc0260..c361b430cfd8a 100644
--- a/pandas/tests/test_categorical.py
+++ b/pandas/tests/test_categorical.py
@@ -57,6 +57,25 @@ def test_getitem_listlike(self):
expected = c[np.array([100000]).astype(np.int64)].codes
tm.assert_numpy_array_equal(result, expected)
+ @pytest.mark.parametrize(
+ "method",
+ [
+ lambda x: x.cat.set_categories([1, 2, 3]),
+ lambda x: x.cat.reorder_categories([2, 3, 1], ordered=True),
+ lambda x: x.cat.rename_categories([1, 2, 3]),
+ lambda x: x.cat.remove_unused_categories(),
+ lambda x: x.cat.remove_categories([2]),
+ lambda x: x.cat.add_categories([4]),
+ lambda x: x.cat.as_ordered(),
+ lambda x: x.cat.as_unordered(),
+ ])
+ def test_getname_categorical_accessor(self, method):
+ # GH 17509
+ s = pd.Series([1, 2, 3], name='A').astype('category')
+ expected = 'A'
+ result = method(s).name
+ assert result == expected
+
def test_getitem_category_type(self):
# GH 14580
# test iloc() on Series with Categorical data
| - [x] closes #17509
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17517 | 2017-09-13T19:12:53Z | 2017-09-18T12:30:07Z | 2017-09-18T12:30:06Z | 2017-09-18T18:01:55Z |
PERF: Avoid materializing values in Categorical.set_categories | diff --git a/asv_bench/benchmarks/categoricals.py b/asv_bench/benchmarks/categoricals.py
index 6432ccfb19efe..d90c994b3d194 100644
--- a/asv_bench/benchmarks/categoricals.py
+++ b/asv_bench/benchmarks/categoricals.py
@@ -67,6 +67,9 @@ def time_value_counts_dropna(self):
def time_rendering(self):
str(self.sel)
+ def time_set_categories(self):
+ self.ts.cat.set_categories(self.ts.cat.categories[::2])
+
class Categoricals3(object):
goal_time = 0.2
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index 939199d3f6fa6..6495ad3e7f6ad 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -467,6 +467,7 @@ Performance Improvements
- Improved performance of instantiating :class:`SparseDataFrame` (:issue:`16773`)
- :attr:`Series.dt` no longer performs frequency inference, yielding a large speedup when accessing the attribute (:issue:`17210`)
+- Improved performance of :meth:`Categorical.set_categories` by not materializing the values (:issue:`17508`)
- :attr:`Timestamp.microsecond` no longer re-computes on attribute access (:issue:`17331`)
.. _whatsnew_0210.bug_fixes:
diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py
index 97df72900428c..e67ce2936819f 100644
--- a/pandas/core/categorical.py
+++ b/pandas/core/categorical.py
@@ -777,8 +777,9 @@ def set_categories(self, new_categories, ordered=None, rename=False,
# remove all _codes which are larger and set to -1/NaN
self._codes[self._codes >= len(new_categories)] = -1
else:
- values = cat.__array__()
- cat._codes = _get_codes_for_values(values, new_categories)
+ codes = _recode_for_categories(self.codes, self.categories,
+ new_categories)
+ cat._codes = codes
cat._categories = new_categories
if ordered is None:
@@ -2113,6 +2114,38 @@ def _get_codes_for_values(values, categories):
return coerce_indexer_dtype(t.lookup(vals), cats)
+def _recode_for_categories(codes, old_categories, new_categories):
+ """
+ Convert a set of codes for to a new set of categories
+
+ Parameters
+ ----------
+ codes : array
+ old_categories, new_categories : Index
+
+ Returns
+ -------
+ new_codes : array
+
+ Examples
+ --------
+ >>> old_cat = pd.Index(['b', 'a', 'c'])
+ >>> new_cat = pd.Index(['a', 'b'])
+ >>> codes = np.array([0, 1, 1, 2])
+ >>> _recode_for_categories(codes, old_cat, new_cat)
+ array([ 1, 0, 0, -1])
+ """
+ from pandas.core.algorithms import take_1d
+
+ if len(old_categories) == 0:
+ # All null anyway, so just retain the nulls
+ return codes
+ indexer = coerce_indexer_dtype(new_categories.get_indexer(old_categories),
+ new_categories)
+ new_codes = take_1d(indexer, codes.copy(), fill_value=-1)
+ return new_codes
+
+
def _convert_to_list_like(list_like):
if hasattr(list_like, "dtype"):
return list_like
diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py
index 0ce45eea119ed..f6f956832eebe 100644
--- a/pandas/core/dtypes/concat.py
+++ b/pandas/core/dtypes/concat.py
@@ -314,6 +314,7 @@ def union_categoricals(to_union, sort_categories=False, ignore_order=False):
Categories (3, object): [b, c, a]
"""
from pandas import Index, Categorical, CategoricalIndex, Series
+ from pandas.core.categorical import _recode_for_categories
if len(to_union) == 0:
raise ValueError('No Categoricals to union')
@@ -359,14 +360,8 @@ def _maybe_unwrap(x):
new_codes = []
for c in to_union:
- if len(c.categories) > 0:
- indexer = categories.get_indexer(c.categories)
-
- from pandas.core.algorithms import take_1d
- new_codes.append(take_1d(indexer, c.codes, fill_value=-1))
- else:
- # must be all NaN
- new_codes.append(c.codes)
+ new_codes.append(_recode_for_categories(c.codes, c.categories,
+ categories))
new_codes = np.concatenate(new_codes)
else:
# ordered - to show a proper error message
diff --git a/pandas/tests/test_categorical.py b/pandas/tests/test_categorical.py
index 7bbe220378993..8a5f6bf110be3 100644
--- a/pandas/tests/test_categorical.py
+++ b/pandas/tests/test_categorical.py
@@ -26,6 +26,7 @@
Interval, IntervalIndex)
from pandas.compat import range, lrange, u, PY3, PYPY
from pandas.core.config import option_context
+from pandas.core.categorical import _recode_for_categories
class TestCategorical(object):
@@ -963,6 +964,67 @@ def test_rename_categories(self):
with pytest.raises(ValueError):
cat.rename_categories([1, 2])
+ @pytest.mark.parametrize('codes, old, new, expected', [
+ ([0, 1], ['a', 'b'], ['a', 'b'], [0, 1]),
+ ([0, 1], ['b', 'a'], ['b', 'a'], [0, 1]),
+ ([0, 1], ['a', 'b'], ['b', 'a'], [1, 0]),
+ ([0, 1], ['b', 'a'], ['a', 'b'], [1, 0]),
+ ([0, 1, 0, 1], ['a', 'b'], ['a', 'b', 'c'], [0, 1, 0, 1]),
+ ([0, 1, 2, 2], ['a', 'b', 'c'], ['a', 'b'], [0, 1, -1, -1]),
+ ([0, 1, -1], ['a', 'b', 'c'], ['a', 'b', 'c'], [0, 1, -1]),
+ ([0, 1, -1], ['a', 'b', 'c'], ['b'], [-1, 0, -1]),
+ ([0, 1, -1], ['a', 'b', 'c'], ['d'], [-1, -1, -1]),
+ ([0, 1, -1], ['a', 'b', 'c'], [], [-1, -1, -1]),
+ ([-1, -1], [], ['a', 'b'], [-1, -1]),
+ ([1, 0], ['b', 'a'], ['a', 'b'], [0, 1]),
+ ])
+ def test_recode_to_categories(self, codes, old, new, expected):
+ codes = np.asanyarray(codes, dtype=np.int8)
+ expected = np.asanyarray(expected, dtype=np.int8)
+ old = Index(old)
+ new = Index(new)
+ result = _recode_for_categories(codes, old, new)
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_recode_to_categories_large(self):
+ N = 1000
+ codes = np.arange(N)
+ old = Index(codes)
+ expected = np.arange(N - 1, -1, -1, dtype=np.int16)
+ new = Index(expected)
+ result = _recode_for_categories(codes, old, new)
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize('values, categories, new_categories', [
+ # No NaNs, same cats, same order
+ (['a', 'b', 'a'], ['a', 'b'], ['a', 'b'],),
+ # No NaNs, same cats, different order
+ (['a', 'b', 'a'], ['a', 'b'], ['b', 'a'],),
+ # Same, unsorted
+ (['b', 'a', 'a'], ['a', 'b'], ['a', 'b'],),
+ # No NaNs, same cats, different order
+ (['b', 'a', 'a'], ['a', 'b'], ['b', 'a'],),
+ # NaNs
+ (['a', 'b', 'c'], ['a', 'b'], ['a', 'b']),
+ (['a', 'b', 'c'], ['a', 'b'], ['b', 'a']),
+ (['b', 'a', 'c'], ['a', 'b'], ['a', 'b']),
+ (['b', 'a', 'c'], ['a', 'b'], ['a', 'b']),
+ # Introduce NaNs
+ (['a', 'b', 'c'], ['a', 'b'], ['a']),
+ (['a', 'b', 'c'], ['a', 'b'], ['b']),
+ (['b', 'a', 'c'], ['a', 'b'], ['a']),
+ (['b', 'a', 'c'], ['a', 'b'], ['a']),
+ # No overlap
+ (['a', 'b', 'c'], ['a', 'b'], ['d', 'e']),
+ ])
+ @pytest.mark.parametrize('ordered', [True, False])
+ def test_set_categories_many(self, values, categories, new_categories,
+ ordered):
+ c = Categorical(values, categories)
+ expected = Categorical(values, new_categories, ordered)
+ result = c.set_categories(new_categories, ordered=ordered)
+ tm.assert_categorical_equal(result, expected)
+
def test_reorder_categories(self):
cat = Categorical(["a", "b", "c", "a"], ordered=True)
old = cat.copy()
| Mater:
```python
In [1]: import pandas as pd; import numpy as np
In [2]: arr = ['s%04d' % i for i in np.random.randint(0, 500000 // 10,
size=500000)];
s = pd.Series(arr).astype('category')
In [3]: %timeit s.cat.set_categories(s.cat.categories)
68.5 ms ± 846 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
```
HEAD:
```python
In [1]: import pandas as pd; import numpy as np
In [2]: arr = ['s%04d' % i for i in np.random.randint(0, 500000 // 10,
size=500000)]
s = pd.Series(arr).astype('category')
In [3]: %timeit s.cat.set_categories(s.cat.categories)
7.43 ms ± 110 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
```
Closes https://github.com/pandas-dev/pandas/issues/17508
I'll rebase #16015 on top of this. Running an ASV now. | https://api.github.com/repos/pandas-dev/pandas/pulls/17515 | 2017-09-13T18:42:48Z | 2017-09-14T16:09:30Z | 2017-09-14T16:09:30Z | 2017-09-14T23:30:23Z |
PERF: Faster CategoricalIndex from categorical | diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index 6495ad3e7f6ad..52e056103cbdc 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -469,6 +469,7 @@ Performance Improvements
- :attr:`Series.dt` no longer performs frequency inference, yielding a large speedup when accessing the attribute (:issue:`17210`)
- Improved performance of :meth:`Categorical.set_categories` by not materializing the values (:issue:`17508`)
- :attr:`Timestamp.microsecond` no longer re-computes on attribute access (:issue:`17331`)
+- Improved performance of the :class:`CategoricalIndex` for data that is already categorical dtype (:issue:`17513`)
.. _whatsnew_0210.bug_fixes:
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index 71cd4790ac364..ef1dc4d971f37 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -130,6 +130,10 @@ def _create_categorical(self, data, categories=None, ordered=None):
-------
Categorical
"""
+ if (isinstance(data, (ABCSeries, type(self))) and
+ is_categorical_dtype(data)):
+ data = data.values
+
if not isinstance(data, ABCCategorical):
ordered = False if ordered is None else ordered
from pandas.core.categorical import Categorical
diff --git a/pandas/tests/indexes/test_category.py b/pandas/tests/indexes/test_category.py
index aac68ebd6abed..cf365465763fa 100644
--- a/pandas/tests/indexes/test_category.py
+++ b/pandas/tests/indexes/test_category.py
@@ -125,6 +125,16 @@ def test_construction_with_dtype(self):
result = CategoricalIndex(idx, categories=idx, ordered=True)
tm.assert_index_equal(result, expected, exact=True)
+ def test_create_categorical(self):
+ # https://github.com/pandas-dev/pandas/pull/17513
+ # The public CI constructor doesn't hit this code path with
+ # instances of CategoricalIndex, but we still want to test the code
+ ci = CategoricalIndex(['a', 'b', 'c'])
+ # First ci is self, second ci is data.
+ result = CategoricalIndex._create_categorical(ci, ci)
+ expected = Categorical(['a', 'b', 'c'])
+ tm.assert_categorical_equal(result, expected)
+
def test_disallow_set_ops(self):
# GH 10039
| Master:
```
In [1]: import pandas as pd; import numpy as np
In [2]: arr = ['s%04d' % i for i in np.random.randint(0, 500000 // 10, size=500000)]; s = pd.Series(arr).astype('category')
In [3]: %timeit pd.CategoricalIndex(s)
69.4 ms ± 946 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
```
HEAD
```python
In [1]: import pandas as pd; import numpy as np
In [2]: arr = ['s%04d' % i for i in np.random.randint(0, 500000 // 10, size=500000)]; s = pd.Series(arr).astype('category')
In [3]: %timeit pd.CategoricalIndex(s)
9.06 µs ± 182 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
```
Is that a 7000x speedup, or did I mess up the math? | https://api.github.com/repos/pandas-dev/pandas/pulls/17513 | 2017-09-13T16:55:24Z | 2017-09-14T23:29:40Z | 2017-09-14T23:29:40Z | 2017-09-14T23:29:43Z |
DOC: grammatical mistakes | diff --git a/pandas/io/stata.py b/pandas/io/stata.py
index 253ed03c25db9..92f180506a8b7 100644
--- a/pandas/io/stata.py
+++ b/pandas/io/stata.py
@@ -57,7 +57,7 @@
identifier of column that should be used as index of the DataFrame
convert_missing : boolean, defaults to False
Flag indicating whether to convert missing values to their Stata
- representations. If False, missing values are replaced with nans.
+ representations. If False, missing values are replaced with nan.
If True, columns containing missing values are returned with
object data types and missing values are represented by
StataMissingValue objects.
@@ -248,8 +248,9 @@ def _stata_elapsed_date_to_datetime_vec(dates, fmt):
def convert_year_month_safe(year, month):
"""
Convert year and month to datetimes, using pandas vectorized versions
- when the date range falls within the range supported by pandas. Other
- wise it falls back to a slower but more robust method using datetime.
+ when the date range falls within the range supported by pandas.
+ Otherwise it falls back to a slower but more robust method
+ using datetime.
"""
if year.max() < MAX_YEAR and year.min() > MIN_YEAR:
return to_datetime(100 * year + month, format='%Y%m')
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17512 | 2017-09-13T10:22:23Z | 2017-09-13T12:24:58Z | 2017-09-13T12:24:57Z | 2017-09-18T18:00:46Z |
DOC: grammatical mistake | diff --git a/pandas/plotting/_tools.py b/pandas/plotting/_tools.py
index 389e238ccb96e..6deddc97915f1 100644
--- a/pandas/plotting/_tools.py
+++ b/pandas/plotting/_tools.py
@@ -141,7 +141,7 @@ def _subplots(naxes=None, sharex=False, sharey=False, squeeze=True,
array of Axis objects are returned as numpy 1-d arrays.
- for NxM subplots with N>1 and M>1 are returned as a 2d array.
- If False, no squeezing at all is done: the returned axis object is always
+ If False, no squeezing is done: the returned axis object is always
a 2-d array containing Axis instances, even if it ends up being 1x1.
subplot_kw : dict
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17511 | 2017-09-13T09:53:37Z | 2017-09-13T10:03:31Z | 2017-09-13T10:03:31Z | 2017-09-18T18:00:54Z |
BUG: in Timestamp.replace when replacing tzinfo around DST changes | diff --git a/asv_bench/benchmarks/timestamp.py b/asv_bench/benchmarks/timestamp.py
index 066479b22739a..e4f3023037580 100644
--- a/asv_bench/benchmarks/timestamp.py
+++ b/asv_bench/benchmarks/timestamp.py
@@ -1,5 +1,7 @@
from .pandas_vb_common import *
from pandas import to_timedelta, Timestamp
+import pytz
+import datetime
class TimestampProperties(object):
@@ -58,3 +60,24 @@ def time_is_leap_year(self):
def time_microsecond(self):
self.ts.microsecond
+
+
+class TimestampOps(object):
+ goal_time = 0.2
+
+ def setup(self):
+ self.ts = Timestamp('2017-08-25 08:16:14')
+ self.ts_tz = Timestamp('2017-08-25 08:16:14', tz='US/Eastern')
+
+ dt = datetime.datetime(2016, 3, 27, 1)
+ self.tzinfo = pytz.timezone('CET').localize(dt, is_dst=False).tzinfo
+ self.ts2 = Timestamp(dt)
+
+ def time_replace_tz(self):
+ self.ts.replace(tzinfo=pytz.timezone('US/Eastern'))
+
+ def time_replace_across_dst(self):
+ self.ts2.replace(tzinfo=self.tzinfo)
+
+ def time_replace_None(self):
+ self.ts_tz.replace(tzinfo=None)
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index 5a353544a4283..8ed3a26a0ee8f 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -487,6 +487,7 @@ Conversion
- Bug in ``IntervalIndex.is_non_overlapping_monotonic`` when intervals are closed on both sides and overlap at a point (:issue:`16560`)
- Bug in :func:`Series.fillna` returns frame when ``inplace=True`` and ``value`` is dict (:issue:`16156`)
- Bug in :attr:`Timestamp.weekday_name` returning a UTC-based weekday name when localized to a timezone (:issue:`17354`)
+- Bug in ``Timestamp.replace`` when replacing ``tzinfo`` around DST changes (:issue:`15683`)
Indexing
^^^^^^^^
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx
index ec12611ae7f02..8238552b44e03 100644
--- a/pandas/_libs/tslib.pyx
+++ b/pandas/_libs/tslib.pyx
@@ -142,6 +142,7 @@ def ints_to_pydatetime(ndarray[int64_t] arr, tz=None, freq=None, box=False):
cdef:
Py_ssize_t i, n = len(arr)
+ ndarray[int64_t] trans, deltas
pandas_datetimestruct dts
object dt
int64_t value
@@ -417,8 +418,9 @@ class Timestamp(_Timestamp):
def _round(self, freq, rounder):
- cdef int64_t unit
- cdef object result, value
+ cdef:
+ int64_t unit, r, value, buff = 1000000
+ object result
from pandas.tseries.frequencies import to_offset
unit = to_offset(freq).nanos
@@ -429,16 +431,15 @@ class Timestamp(_Timestamp):
if unit < 1000 and unit % 1000 != 0:
# for nano rounding, work with the last 6 digits separately
# due to float precision
- buff = 1000000
- result = (buff * (value // buff) + unit *
- (rounder((value % buff) / float(unit))).astype('i8'))
+ r = (buff * (value // buff) + unit *
+ (rounder((value % buff) / float(unit))).astype('i8'))
elif unit >= 1000 and unit % 1000 != 0:
msg = 'Precision will be lost using frequency: {}'
warnings.warn(msg.format(freq))
- result = (unit * rounder(value / float(unit)).astype('i8'))
+ r = (unit * rounder(value / float(unit)).astype('i8'))
else:
- result = (unit * rounder(value / float(unit)).astype('i8'))
- result = Timestamp(result, unit='ns')
+ r = (unit * rounder(value / float(unit)).astype('i8'))
+ result = Timestamp(r, unit='ns')
if self.tz is not None:
result = result.tz_localize(self.tz)
return result
@@ -683,14 +684,16 @@ class Timestamp(_Timestamp):
cdef:
pandas_datetimestruct dts
- int64_t value
+ int64_t value, value_tz, offset
object _tzinfo, result, k, v
+ datetime ts_input
# set to naive if needed
_tzinfo = self.tzinfo
value = self.value
if _tzinfo is not None:
- value = tz_convert_single(value, 'UTC', _tzinfo)
+ value_tz = tz_convert_single(value, _tzinfo, 'UTC')
+ value += value - value_tz
# setup components
pandas_datetime_to_datetimestruct(value, PANDAS_FR_ns, &dts)
@@ -724,16 +727,14 @@ class Timestamp(_Timestamp):
_tzinfo = tzinfo
# reconstruct & check bounds
- value = pandas_datetimestruct_to_datetime(PANDAS_FR_ns, &dts)
+ ts_input = datetime(dts.year, dts.month, dts.day, dts.hour, dts.min,
+ dts.sec, dts.us, tzinfo=_tzinfo)
+ ts = convert_to_tsobject(ts_input, _tzinfo, None, 0, 0)
+ value = ts.value + (dts.ps // 1000)
if value != NPY_NAT:
_check_dts_bounds(&dts)
- # set tz if needed
- if _tzinfo is not None:
- value = tz_convert_single(value, _tzinfo, 'UTC')
-
- result = create_timestamp_from_ts(value, dts, _tzinfo, self.freq)
- return result
+ return create_timestamp_from_ts(value, dts, _tzinfo, self.freq)
def isoformat(self, sep='T'):
base = super(_Timestamp, self).isoformat(sep=sep)
@@ -1175,7 +1176,7 @@ cdef class _Timestamp(datetime):
return np.datetime64(self.value, 'ns')
def __add__(self, other):
- cdef int64_t other_int
+ cdef int64_t other_int, nanos
if is_timedelta64_object(other):
other_int = other.astype('timedelta64[ns]').view('i8')
@@ -1625,6 +1626,10 @@ cdef inline void _localize_tso(_TSObject obj, object tz):
"""
Take a TSObject in UTC and localizes to timezone tz.
"""
+ cdef:
+ ndarray[int64_t] trans, deltas
+ Py_ssize_t delta, posn
+
if is_utc(tz):
obj.tzinfo = tz
elif is_tzlocal(tz):
@@ -1676,7 +1681,7 @@ cdef inline void _localize_tso(_TSObject obj, object tz):
obj.tzinfo = tz
-def _localize_pydatetime(object dt, object tz):
+cpdef inline object _localize_pydatetime(object dt, object tz):
"""
Take a datetime/Timestamp in UTC and localizes to timezone tz.
"""
@@ -3892,7 +3897,7 @@ for _maybe_method_name in dir(NaTType):
# Conversion routines
-def _delta_to_nanoseconds(delta):
+cpdef int64_t _delta_to_nanoseconds(delta):
if isinstance(delta, np.ndarray):
return delta.astype('m8[ns]').astype('int64')
if hasattr(delta, 'nanos'):
@@ -4137,7 +4142,7 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2):
return result
-def tz_convert_single(int64_t val, object tz1, object tz2):
+cpdef int64_t tz_convert_single(int64_t val, object tz1, object tz2):
"""
Convert the val (in i8) from timezone1 to timezone2
@@ -5006,6 +5011,7 @@ cdef inline int64_t _normalized_stamp(pandas_datetimestruct *dts) nogil:
def dates_normalized(ndarray[int64_t] stamps, tz=None):
cdef:
Py_ssize_t i, n = len(stamps)
+ ndarray[int64_t] trans, deltas
pandas_datetimestruct dts
if tz is None or is_utc(tz):
diff --git a/pandas/tests/tseries/test_timezones.py b/pandas/tests/tseries/test_timezones.py
index a9ecfd797a32b..ac1a338d2844d 100644
--- a/pandas/tests/tseries/test_timezones.py
+++ b/pandas/tests/tseries/test_timezones.py
@@ -1269,6 +1269,27 @@ def test_ambiguous_compat(self):
assert (result_pytz.to_pydatetime().tzname() ==
result_dateutil.to_pydatetime().tzname())
+ def test_replace_tzinfo(self):
+ # GH 15683
+ dt = datetime(2016, 3, 27, 1)
+ tzinfo = pytz.timezone('CET').localize(dt, is_dst=False).tzinfo
+
+ result_dt = dt.replace(tzinfo=tzinfo)
+ result_pd = Timestamp(dt).replace(tzinfo=tzinfo)
+
+ if hasattr(result_dt, 'timestamp'): # New method in Py 3.3
+ assert result_dt.timestamp() == result_pd.timestamp()
+ assert result_dt == result_pd
+ assert result_dt == result_pd.to_pydatetime()
+
+ result_dt = dt.replace(tzinfo=tzinfo).replace(tzinfo=None)
+ result_pd = Timestamp(dt).replace(tzinfo=tzinfo).replace(tzinfo=None)
+
+ if hasattr(result_dt, 'timestamp'): # New method in Py 3.3
+ assert result_dt.timestamp() == result_pd.timestamp()
+ assert result_dt == result_pd
+ assert result_dt == result_pd.to_pydatetime()
+
def test_index_equals_with_tz(self):
left = date_range('1/1/2011', periods=100, freq='H', tz='utc')
right = date_range('1/1/2011', periods=100, freq='H', tz='US/Eastern')
| replaces #17356
closes #15683 | https://api.github.com/repos/pandas-dev/pandas/pulls/17507 | 2017-09-13T02:46:55Z | 2017-09-20T13:09:16Z | 2017-09-20T13:09:15Z | 2017-09-20T14:37:34Z |
DOC: removed versionadded <0.17 in doc strings | diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index 89da897f6c529..6ffa903c74150 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -526,4 +526,4 @@ Other
^^^^^
- Bug in :func:`eval` where the ``inplace`` parameter was being incorrectly handled (:issue:`16732`)
- Several ``NaT`` method docstrings (e.g. :func:`NaT.ctime`) were incorrect (:issue:`17327`)
-- The documentation has had references to versions < v0.16 removed and cleaned up (:issue:`17442`, :issue:`17442` & :issue:`#17404`)
+- The documentation has had references to versions < v0.17 removed and cleaned up (:issue:`17442`, :issue:`17442`, :issue:`17404` & :issue:`17504`)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 5991ec825c841..dd5d490ea66a8 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1479,8 +1479,6 @@ def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None,
Character recognized as decimal separator. E.g. use ',' for
European data
- .. versionadded:: 0.16.0
-
"""
formatter = fmt.CSVFormatter(self, path_or_buf,
line_terminator=line_terminator, sep=sep,
@@ -2165,8 +2163,6 @@ def _getitem_frame(self, key):
def query(self, expr, inplace=False, **kwargs):
"""Query the columns of a frame with a boolean expression.
- .. versionadded:: 0.13
-
Parameters
----------
expr : string
@@ -2561,8 +2557,6 @@ def assign(self, **kwargs):
Assign new columns to a DataFrame, returning a new object
(a copy) with all the original columns in addition to the new ones.
- .. versionadded:: 0.16.0
-
Parameters
----------
kwargs : keyword, value pairs
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 8d16b079ba2c8..a71bf7be1bc75 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2348,8 +2348,6 @@ def drop(self, labels, axis=0, level=None, inplace=False, errors='raise'):
errors : {'ignore', 'raise'}, default 'raise'
If 'ignore', suppress error and existing labels are dropped.
- .. versionadded:: 0.16.1
-
Returns
-------
dropped : type of caller
@@ -3070,8 +3068,6 @@ def sample(self, n=None, frac=None, replace=False, weights=None,
"""
Returns a random sample of items from an axis of object.
- .. versionadded:: 0.16.1
-
Parameters
----------
n : int, optional
@@ -3228,8 +3224,6 @@ def sample(self, n=None, frac=None, replace=False, weights=None,
_shared_docs['pipe'] = ("""
Apply func(self, \*args, \*\*kwargs)
- .. versionadded:: 0.16.2
-
Parameters
----------
func : function
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index c8044b14e4e57..baa3ebce6abbc 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -33,8 +33,6 @@ class CategoricalIndex(Index, base.PandasDelegate):
Immutable Index implementing an ordered, sliceable set. CategoricalIndex
represents a sparsely populated Index with an underlying Categorical.
- .. versionadded:: 0.16.1
-
Parameters
----------
data : array-like or Categorical, (1-dimensional)
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index 5a04c550f4502..4cfb7547e7d0a 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -1577,7 +1577,7 @@ def _set_freq(self, value):
days_in_month = _field_accessor(
'days_in_month',
'dim',
- "The number of days in the month\n\n.. versionadded:: 0.16.0")
+ "The number of days in the month")
daysinmonth = days_in_month
is_month_start = _field_accessor(
'is_month_start',
diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py
index b4abba8026b35..7260bc9a8b7a1 100644
--- a/pandas/core/reshape/reshape.py
+++ b/pandas/core/reshape/reshape.py
@@ -1110,8 +1110,6 @@ def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False,
Whether the dummy columns should be sparse or not. Returns
SparseDataFrame if `data` is a Series or if all columns are included.
Otherwise returns a DataFrame with some SparseBlocks.
-
- .. versionadded:: 0.16.1
drop_first : bool, default False
Whether to get k-1 dummies out of k categorical levels by removing the
first level.
diff --git a/pandas/core/sparse/series.py b/pandas/core/sparse/series.py
index 99aec2dd11569..2aecb9d7c4ffb 100644
--- a/pandas/core/sparse/series.py
+++ b/pandas/core/sparse/series.py
@@ -732,8 +732,6 @@ def to_coo(self, row_levels=(0, ), column_levels=(1, ), sort_labels=False):
(labels) or numbers of the levels. {row_levels, column_levels} must be
a partition of the MultiIndex level names (or numbers).
- .. versionadded:: 0.16.0
-
Parameters
----------
row_levels : tuple/list
@@ -784,8 +782,6 @@ def from_coo(cls, A, dense_index=False):
"""
Create a SparseSeries from a scipy.sparse.coo_matrix.
- .. versionadded:: 0.16.0
-
Parameters
----------
A : scipy.sparse.coo_matrix
diff --git a/pandas/core/strings.py b/pandas/core/strings.py
index 48bc2ee05dd68..021f88d1aec00 100644
--- a/pandas/core/strings.py
+++ b/pandas/core/strings.py
@@ -602,8 +602,6 @@ def str_extract(arr, pat, flags=0, expand=None):
For each subject string in the Series, extract groups from the
first match of regular expression pat.
- .. versionadded:: 0.13.0
-
Parameters
----------
pat : string
@@ -1016,7 +1014,6 @@ def str_split(arr, pat=None, n=None):
* If True, return DataFrame/MultiIndex expanding dimensionality.
* If False, return Series/Index.
- .. versionadded:: 0.16.1
return_type : deprecated, use `expand`
Returns
@@ -1047,8 +1044,6 @@ def str_rsplit(arr, pat=None, n=None):
string, starting at the end of the string and working to the front.
Equivalent to :meth:`str.rsplit`.
- .. versionadded:: 0.16.2
-
Parameters
----------
pat : string, default None
| Cleaned up old references to when functionality was added.
See also #17442, #17442, #17404. | https://api.github.com/repos/pandas-dev/pandas/pulls/17504 | 2017-09-13T00:27:07Z | 2017-09-13T10:04:32Z | 2017-09-13T10:04:32Z | 2017-09-28T11:07:57Z |
COMPAT: followup to #17491 | diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index 89da897f6c529..472663733e3b6 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -190,19 +190,19 @@ the target. Now, a ``ValueError`` will be raised when such an input is passed in
.. _whatsnew_0210.api_breaking.iteration_scalars:
-Iteration of Series/Index will now return python scalars
+Iteration of Series/Index will now return Python scalars
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-Previously, when using certain iteration methods for a ``Series`` with dtype ``int`` or ``float``, you would receive a ``numpy`` scalar, e.g. a ``np.int64``, rather than a python ``int``. Issue (:issue:`10904`) corrected this for ``Series.tolist()`` and ``list(Series)``. This change makes all iteration methods consistent, in particular, for ``__iter__()`` and ``.map()``; note that this only affect int/float dtypes. (:issue:`13236`, :issue:`13258`, :issue:`14216`).
+Previously, when using certain iteration methods for a ``Series`` with dtype ``int`` or ``float``, you would receive a ``numpy`` scalar, e.g. a ``np.int64``, rather than a Python ``int``. Issue (:issue:`10904`) corrected this for ``Series.tolist()`` and ``list(Series)``. This change makes all iteration methods consistent, in particular, for ``__iter__()`` and ``.map()``; note that this only affects int/float dtypes. (:issue:`13236`, :issue:`13258`, :issue:`14216`).
.. ipython:: python
- s = Series([1, 2, 3])
+ s = pd.Series([1, 2, 3])
s
Previously:
-.. code-block:: python
+.. code-block:: ipython
In [2]: type(list(s)[0])
Out[2]: numpy.int64
@@ -215,14 +215,14 @@ New Behaviour:
Furthermore this will now correctly box the results of iteration for :func:`DataFrame.to_dict` as well.
-.. ipython:: python
+.. ipython:: ipython
d = {'a':[1], 'b':['b']}
- df = DataFrame(d)
+ df = pd,DataFrame(d)
Previously:
-.. code-block:: python
+.. code-block:: ipython
In [8]: type(df.to_dict()['a'][0])
Out[8]: numpy.int64
diff --git a/pandas/core/base.py b/pandas/core/base.py
index 62d89eac4b354..f0e8d8a16661b 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -892,18 +892,31 @@ def argmin(self, axis=None):
def tolist(self):
"""
- return a list of the values; box to scalars
+ Return a list of the values.
+
+ These are each a scalar type, which is a Python scalar
+ (for str, int, float) or a pandas scalar
+ (for Timestamp/Timedelta/Interval/Period)
+
+ See Also
+ --------
+ numpy.tolist
"""
- return list(self.__iter__())
+
+ if is_datetimelike(self):
+ return [_maybe_box_datetimelike(x) for x in self._values]
+ else:
+ return self._values.tolist()
def __iter__(self):
"""
- provide iteration over the values; box to scalars
+ Return an iterator of the values.
+
+ These are each a scalar type, which is a Python scalar
+ (for str, int, float) or a pandas scalar
+ (for Timestamp/Timedelta/Interval/Period)
"""
- if is_datetimelike(self):
- return (_maybe_box_datetimelike(x) for x in self._values)
- else:
- return iter(self._values.tolist())
+ return iter(self.tolist())
@cache_readonly
def hasnans(self):
diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py
index dbd2a79b7e46d..97df72900428c 100644
--- a/pandas/core/categorical.py
+++ b/pandas/core/categorical.py
@@ -26,7 +26,7 @@
is_integer_dtype, is_bool,
is_list_like, is_sequence,
is_scalar)
-from pandas.core.common import is_null_slice
+from pandas.core.common import is_null_slice, _maybe_box_datetimelike
from pandas.core.algorithms import factorize, take_1d, unique1d
from pandas.core.base import (PandasObject, PandasDelegate,
@@ -401,8 +401,14 @@ def itemsize(self):
def tolist(self):
"""
- return a list of my values
+ Return a list of the values.
+
+ These are each a scalar type, which is a Python scalar
+ (for str, int, float) or a pandas scalar
+ (for Timestamp/Timedelta/Interval/Period)
"""
+ if is_datetimelike(self.categories):
+ return [_maybe_box_datetimelike(x) for x in self]
return np.array(self).tolist()
def reshape(self, new_shape, *args, **kwargs):
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index c8044b14e4e57..e952f4f4da1cb 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -253,9 +253,8 @@ def get_values(self):
""" return the underlying data as an ndarray """
return self._data.get_values()
- def __iter__(self):
- """ iterate like Categorical """
- return self._data.__iter__()
+ def tolist(self):
+ return self._data.tolist()
@property
def codes(self):
diff --git a/pandas/tests/indexes/test_category.py b/pandas/tests/indexes/test_category.py
index 05d31af57b36c..aac68ebd6abed 100644
--- a/pandas/tests/indexes/test_category.py
+++ b/pandas/tests/indexes/test_category.py
@@ -576,12 +576,13 @@ def test_isin(self):
ci.isin(['c', 'a', 'b', np.nan]), np.array([True] * 6))
# mismatched categorical -> coerced to ndarray so doesn't matter
- tm.assert_numpy_array_equal(
- ci.isin(ci.set_categories(list('abcdefghi'))), np.array([True] *
- 6))
- tm.assert_numpy_array_equal(
- ci.isin(ci.set_categories(list('defghi'))),
- np.array([False] * 5 + [True]))
+ result = ci.isin(ci.set_categories(list('abcdefghi')))
+ expected = np.array([True] * 6)
+ tm.assert_numpy_array_equal(result, expected)
+
+ result = ci.isin(ci.set_categories(list('defghi')))
+ expected = np.array([False] * 5 + [True])
+ tm.assert_numpy_array_equal(result, expected)
def test_identical(self):
diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py
index b7fbe803f8d3b..d0805e2bb54d2 100644
--- a/pandas/tests/series/test_api.py
+++ b/pandas/tests/series/test_api.py
@@ -245,43 +245,6 @@ def test_iter(self):
for i, val in enumerate(self.ts):
assert val == self.ts[i]
- def test_iter_box(self):
- vals = [pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02')]
- s = pd.Series(vals)
- assert s.dtype == 'datetime64[ns]'
- for res, exp in zip(s, vals):
- assert isinstance(res, pd.Timestamp)
- assert res.tz is None
- assert res == exp
-
- vals = [pd.Timestamp('2011-01-01', tz='US/Eastern'),
- pd.Timestamp('2011-01-02', tz='US/Eastern')]
- s = pd.Series(vals)
-
- assert s.dtype == 'datetime64[ns, US/Eastern]'
- for res, exp in zip(s, vals):
- assert isinstance(res, pd.Timestamp)
- assert res.tz == exp.tz
- assert res == exp
-
- # timedelta
- vals = [pd.Timedelta('1 days'), pd.Timedelta('2 days')]
- s = pd.Series(vals)
- assert s.dtype == 'timedelta64[ns]'
- for res, exp in zip(s, vals):
- assert isinstance(res, pd.Timedelta)
- assert res == exp
-
- # period (object dtype, not boxed)
- vals = [pd.Period('2011-01-01', freq='M'),
- pd.Period('2011-01-02', freq='M')]
- s = pd.Series(vals)
- assert s.dtype == 'object'
- for res, exp in zip(s, vals):
- assert isinstance(res, pd.Period)
- assert res.freq == 'M'
- assert res == exp
-
def test_keys(self):
# HACK: By doing this in two stages, we avoid 2to3 wrapping the call
# to .keys() in a list()
diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py
index 210d0260b8d95..38d78b12b31aa 100644
--- a/pandas/tests/test_base.py
+++ b/pandas/tests/test_base.py
@@ -1054,10 +1054,7 @@ class TestToIterable(object):
('timedelta64[ns]', Timedelta)]
@pytest.mark.parametrize(
- 'dtype, rdtype',
- dtypes + [
- ('object', object),
- ('category', object)])
+ 'dtype, rdtype', dtypes)
@pytest.mark.parametrize(
'method',
[
@@ -1074,6 +1071,43 @@ def test_iterable(self, typ, method, dtype, rdtype):
result = method(s)[0]
assert isinstance(result, rdtype)
+ @pytest.mark.parametrize(
+ 'dtype, rdtype, obj',
+ [
+ ('object', object, 'a'),
+ ('object', (int, long), 1),
+ ('category', object, 'a'),
+ ('category', (int, long), 1)])
+ @pytest.mark.parametrize(
+ 'method',
+ [
+ lambda x: x.tolist(),
+ lambda x: list(x),
+ lambda x: list(x.__iter__()),
+ ], ids=['tolist', 'list', 'iter'])
+ @pytest.mark.parametrize('typ', [Series, Index])
+ def test_iterable_object_and_category(self, typ, method,
+ dtype, rdtype, obj):
+ # gh-10904
+ # gh-13258
+ # coerce iteration to underlying python / pandas types
+ s = typ([obj], dtype=dtype)
+ result = method(s)[0]
+ assert isinstance(result, rdtype)
+
+ @pytest.mark.parametrize(
+ 'dtype, rdtype', dtypes)
+ def test_iterable_items(self, dtype, rdtype):
+ # gh-13258
+ # test items / iteritems yields the correct boxed scalars
+ # this only applies to series
+ s = Series([1], dtype=dtype)
+ _, result = list(s.items())[0]
+ assert isinstance(result, rdtype)
+
+ _, result = list(s.iteritems())[0]
+ assert isinstance(result, rdtype)
+
@pytest.mark.parametrize(
'dtype, rdtype',
dtypes + [
@@ -1102,3 +1136,40 @@ def test_categorial_datetimelike(self, method):
result = method(i)[0]
assert isinstance(result, Timestamp)
+
+ def test_iter_box(self):
+ vals = [pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02')]
+ s = pd.Series(vals)
+ assert s.dtype == 'datetime64[ns]'
+ for res, exp in zip(s, vals):
+ assert isinstance(res, pd.Timestamp)
+ assert res.tz is None
+ assert res == exp
+
+ vals = [pd.Timestamp('2011-01-01', tz='US/Eastern'),
+ pd.Timestamp('2011-01-02', tz='US/Eastern')]
+ s = pd.Series(vals)
+
+ assert s.dtype == 'datetime64[ns, US/Eastern]'
+ for res, exp in zip(s, vals):
+ assert isinstance(res, pd.Timestamp)
+ assert res.tz == exp.tz
+ assert res == exp
+
+ # timedelta
+ vals = [pd.Timedelta('1 days'), pd.Timedelta('2 days')]
+ s = pd.Series(vals)
+ assert s.dtype == 'timedelta64[ns]'
+ for res, exp in zip(s, vals):
+ assert isinstance(res, pd.Timedelta)
+ assert res == exp
+
+ # period (object dtype, not boxed)
+ vals = [pd.Period('2011-01-01', freq='M'),
+ pd.Period('2011-01-02', freq='M')]
+ s = pd.Series(vals)
+ assert s.dtype == 'object'
+ for res, exp in zip(s, vals):
+ assert isinstance(res, pd.Period)
+ assert res.freq == 'M'
+ assert res == exp
| https://api.github.com/repos/pandas-dev/pandas/pulls/17503 | 2017-09-12T23:24:17Z | 2017-09-13T23:18:57Z | 2017-09-13T23:18:57Z | 2017-09-15T13:01:05Z | |
De-privatize timezone funcs | diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx
index bf4d53683c9b7..884117799ec5b 100644
--- a/pandas/_libs/index.pyx
+++ b/pandas/_libs/index.pyx
@@ -17,7 +17,7 @@ cimport tslib
from hashtable cimport HashTable
-from tslibs.timezones cimport _is_utc
+from tslibs.timezones cimport is_utc, get_utcoffset
from pandas._libs import tslib, algos, hashtable as _hash
from pandas._libs.tslib import Timestamp, Timedelta
from datetime import datetime, timedelta
@@ -551,8 +551,8 @@ cdef inline _to_i8(object val):
tzinfo = getattr(val, 'tzinfo', None)
# Save the original date value so we can get the utcoffset from it.
ival = _pydatetime_to_dts(val, &dts)
- if tzinfo is not None and not _is_utc(tzinfo):
- offset = tslib._get_utcoffset(tzinfo, val)
+ if tzinfo is not None and not is_utc(tzinfo):
+ offset = get_utcoffset(tzinfo, val)
ival -= tslib._delta_to_nanoseconds(offset)
return ival
return val
diff --git a/pandas/_libs/period.pyx b/pandas/_libs/period.pyx
index 2b0734f5cf2e7..9e473a7f362b4 100644
--- a/pandas/_libs/period.pyx
+++ b/pandas/_libs/period.pyx
@@ -34,7 +34,7 @@ from lib cimport is_null_datetimelike, is_period
from pandas._libs import tslib, lib
from pandas._libs.tslib import (Timedelta, Timestamp, iNaT,
NaT)
-from tslibs.timezones cimport _is_utc, _is_tzlocal, _get_utcoffset
+from tslibs.timezones cimport is_utc, is_tzlocal, get_utcoffset
from tslib cimport (
maybe_get_tz,
_get_dst_info,
@@ -533,7 +533,7 @@ cdef _reso_local(ndarray[int64_t] stamps, object tz):
ndarray[int64_t] trans, deltas, pos
pandas_datetimestruct dts
- if _is_utc(tz):
+ if is_utc(tz):
for i in range(n):
if stamps[i] == NPY_NAT:
continue
@@ -541,7 +541,7 @@ cdef _reso_local(ndarray[int64_t] stamps, object tz):
curr_reso = _reso_stamp(&dts)
if curr_reso < reso:
reso = curr_reso
- elif _is_tzlocal(tz):
+ elif is_tzlocal(tz):
for i in range(n):
if stamps[i] == NPY_NAT:
continue
@@ -549,7 +549,7 @@ cdef _reso_local(ndarray[int64_t] stamps, object tz):
&dts)
dt = datetime(dts.year, dts.month, dts.day, dts.hour,
dts.min, dts.sec, dts.us, tz)
- delta = int(_get_utcoffset(tz, dt).total_seconds()) * 1000000000
+ delta = int(get_utcoffset(tz, dt).total_seconds()) * 1000000000
pandas_datetime_to_datetimestruct(stamps[i] + delta,
PANDAS_FR_ns, &dts)
curr_reso = _reso_stamp(&dts)
@@ -597,7 +597,7 @@ cdef ndarray[int64_t] localize_dt64arr_to_period(ndarray[int64_t] stamps,
ndarray[int64_t] trans, deltas, pos
pandas_datetimestruct dts
- if _is_utc(tz):
+ if is_utc(tz):
for i in range(n):
if stamps[i] == NPY_NAT:
result[i] = NPY_NAT
@@ -607,7 +607,7 @@ cdef ndarray[int64_t] localize_dt64arr_to_period(ndarray[int64_t] stamps,
dts.hour, dts.min, dts.sec,
dts.us, dts.ps, freq)
- elif _is_tzlocal(tz):
+ elif is_tzlocal(tz):
for i in range(n):
if stamps[i] == NPY_NAT:
result[i] = NPY_NAT
@@ -616,7 +616,7 @@ cdef ndarray[int64_t] localize_dt64arr_to_period(ndarray[int64_t] stamps,
&dts)
dt = datetime(dts.year, dts.month, dts.day, dts.hour,
dts.min, dts.sec, dts.us, tz)
- delta = int(_get_utcoffset(tz, dt).total_seconds()) * 1000000000
+ delta = int(get_utcoffset(tz, dt).total_seconds()) * 1000000000
pandas_datetime_to_datetimestruct(stamps[i] + delta,
PANDAS_FR_ns, &dts)
result[i] = get_period_ordinal(dts.year, dts.month, dts.day,
diff --git a/pandas/_libs/src/inference.pyx b/pandas/_libs/src/inference.pyx
index 95145ff49b02f..2bb362eab4097 100644
--- a/pandas/_libs/src/inference.pyx
+++ b/pandas/_libs/src/inference.pyx
@@ -3,7 +3,7 @@ from decimal import Decimal
cimport util
cimport cython
from tslib import NaT
-from tslibs.timezones cimport _get_zone
+from tslibs.timezones cimport get_timezone
from datetime import datetime, timedelta
iNaT = util.get_nat()
@@ -901,13 +901,13 @@ cpdef bint is_datetime_with_singletz_array(ndarray[object] values):
for i in range(n):
base_val = values[i]
if base_val is not NaT:
- base_tz = _get_zone(getattr(base_val, 'tzinfo', None))
+ base_tz = get_timezone(getattr(base_val, 'tzinfo', None))
for j in range(i, n):
val = values[j]
if val is not NaT:
tz = getattr(val, 'tzinfo', None)
- if base_tz != tz and base_tz != _get_zone(tz):
+ if base_tz != tz and base_tz != get_timezone(tz):
return False
break
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx
index a8ae0fcd733d6..629325c28ea9c 100644
--- a/pandas/_libs/tslib.pyx
+++ b/pandas/_libs/tslib.pyx
@@ -108,11 +108,11 @@ iNaT = NPY_NAT
from tslibs.timezones cimport (
- _is_utc, _is_tzlocal,
- _treat_tz_as_dateutil, _treat_tz_as_pytz,
- _get_zone,
- _get_utcoffset)
-from tslibs.timezones import get_timezone, _get_utcoffset # noqa
+ is_utc, is_tzlocal,
+ treat_tz_as_dateutil, treat_tz_as_pytz,
+ get_timezone,
+ get_utcoffset)
+from tslibs.timezones import get_timezone, get_utcoffset # noqa
cdef inline object create_timestamp_from_ts(
@@ -160,7 +160,7 @@ def ints_to_pydatetime(ndarray[int64_t] arr, tz=None, freq=None, box=False):
func_create = create_datetime_from_ts
if tz is not None:
- if _is_utc(tz):
+ if is_utc(tz):
for i in range(n):
value = arr[i]
if value == NPY_NAT:
@@ -169,7 +169,7 @@ def ints_to_pydatetime(ndarray[int64_t] arr, tz=None, freq=None, box=False):
pandas_datetime_to_datetimestruct(
value, PANDAS_FR_ns, &dts)
result[i] = func_create(value, dts, tz, freq)
- elif _is_tzlocal(tz) or _is_fixed_offset(tz):
+ elif is_tzlocal(tz) or _is_fixed_offset(tz):
for i in range(n):
value = arr[i]
if value == NPY_NAT:
@@ -194,7 +194,7 @@ def ints_to_pydatetime(ndarray[int64_t] arr, tz=None, freq=None, box=False):
# Adjust datetime64 timestamp, recompute datetimestruct
pos = trans.searchsorted(value, side='right') - 1
- if _treat_tz_as_pytz(tz):
+ if treat_tz_as_pytz(tz):
# find right representation of dst etc in pytz timezone
new_tz = tz._tzinfos[tz._transition_info[pos]]
else:
@@ -242,12 +242,12 @@ def ints_to_pytimedelta(ndarray[int64_t] arr, box=False):
cdef inline bint _is_fixed_offset(object tz):
- if _treat_tz_as_dateutil(tz):
+ if treat_tz_as_dateutil(tz):
if len(tz._trans_idx) == 0 and len(tz._trans_list) == 0:
return 1
else:
return 0
- elif _treat_tz_as_pytz(tz):
+ elif treat_tz_as_pytz(tz):
if (len(tz._transition_info) == 0
and len(tz._utc_transition_times) == 0):
return 1
@@ -1107,12 +1107,12 @@ cdef class _Timestamp(datetime):
try:
stamp += self.strftime('%z')
if self.tzinfo:
- zone = _get_zone(self.tzinfo)
+ zone = get_timezone(self.tzinfo)
except ValueError:
year2000 = self.replace(year=2000)
stamp += year2000.strftime('%z')
if self.tzinfo:
- zone = _get_zone(self.tzinfo)
+ zone = get_timezone(self.tzinfo)
try:
stamp += zone.strftime(' %%Z')
@@ -1272,7 +1272,7 @@ cdef class _Timestamp(datetime):
cdef:
int64_t val
val = self.value
- if self.tz is not None and not _is_utc(self.tz):
+ if self.tz is not None and not is_utc(self.tz):
val = tz_convert_single(self.value, 'UTC', self.tz)
return val
@@ -1510,14 +1510,14 @@ cdef convert_to_tsobject(object ts, object tz, object unit,
except:
pass
obj.value = _pydatetime_to_dts(ts, &obj.dts)
- ts_offset = _get_utcoffset(ts.tzinfo, ts)
+ ts_offset = get_utcoffset(ts.tzinfo, ts)
obj.value -= _delta_to_nanoseconds(ts_offset)
- tz_offset = _get_utcoffset(tz, ts)
+ tz_offset = get_utcoffset(tz, ts)
obj.value += _delta_to_nanoseconds(tz_offset)
pandas_datetime_to_datetimestruct(obj.value,
PANDAS_FR_ns, &obj.dts)
obj.tzinfo = tz
- elif not _is_utc(tz):
+ elif not is_utc(tz):
ts = _localize_pydatetime(ts, tz)
obj.value = _pydatetime_to_dts(ts, &obj.dts)
obj.tzinfo = ts.tzinfo
@@ -1529,8 +1529,8 @@ cdef convert_to_tsobject(object ts, object tz, object unit,
obj.value = _pydatetime_to_dts(ts, &obj.dts)
obj.tzinfo = ts.tzinfo
- if obj.tzinfo is not None and not _is_utc(obj.tzinfo):
- offset = _get_utcoffset(obj.tzinfo, ts)
+ if obj.tzinfo is not None and not is_utc(obj.tzinfo):
+ offset = get_utcoffset(obj.tzinfo, ts)
obj.value -= _delta_to_nanoseconds(offset)
if is_timestamp(ts):
@@ -1641,13 +1641,13 @@ cdef inline void _localize_tso(_TSObject obj, object tz):
"""
Take a TSObject in UTC and localizes to timezone tz.
"""
- if _is_utc(tz):
+ if is_utc(tz):
obj.tzinfo = tz
- elif _is_tzlocal(tz):
+ elif is_tzlocal(tz):
pandas_datetime_to_datetimestruct(obj.value, PANDAS_FR_ns, &obj.dts)
dt = datetime(obj.dts.year, obj.dts.month, obj.dts.day, obj.dts.hour,
obj.dts.min, obj.dts.sec, obj.dts.us, tz)
- delta = int(_get_utcoffset(tz, dt).total_seconds()) * 1000000000
+ delta = int(get_utcoffset(tz, dt).total_seconds()) * 1000000000
if obj.value != NPY_NAT:
pandas_datetime_to_datetimestruct(obj.value + delta,
PANDAS_FR_ns, &obj.dts)
@@ -1671,7 +1671,7 @@ cdef inline void _localize_tso(_TSObject obj, object tz):
pandas_datetime_to_datetimestruct(
obj.value, PANDAS_FR_ns, &obj.dts)
obj.tzinfo = tz
- elif _treat_tz_as_pytz(tz):
+ elif treat_tz_as_pytz(tz):
inf = tz._transition_info[pos]
if obj.value != NPY_NAT:
pandas_datetime_to_datetimestruct(obj.value + deltas[pos],
@@ -1680,7 +1680,7 @@ cdef inline void _localize_tso(_TSObject obj, object tz):
pandas_datetime_to_datetimestruct(obj.value,
PANDAS_FR_ns, &obj.dts)
obj.tzinfo = tz._tzinfos[inf]
- elif _treat_tz_as_dateutil(tz):
+ elif treat_tz_as_dateutil(tz):
if obj.value != NPY_NAT:
pandas_datetime_to_datetimestruct(obj.value + deltas[pos],
PANDAS_FR_ns, &obj.dts)
@@ -1770,10 +1770,10 @@ def datetime_to_datetime64(ndarray[object] values):
elif PyDateTime_Check(val):
if val.tzinfo is not None:
if inferred_tz is not None:
- if _get_zone(val.tzinfo) != inferred_tz:
+ if get_timezone(val.tzinfo) != inferred_tz:
raise ValueError('Array must be all same time zone')
else:
- inferred_tz = _get_zone(val.tzinfo)
+ inferred_tz = get_timezone(val.tzinfo)
_ts = convert_to_tsobject(val, None, None, 0, 0)
iresult[i] = _ts.value
@@ -4088,9 +4088,9 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2):
return np.array([], dtype=np.int64)
# Convert to UTC
- if _get_zone(tz1) != 'UTC':
+ if get_timezone(tz1) != 'UTC':
utc_dates = np.empty(n, dtype=np.int64)
- if _is_tzlocal(tz1):
+ if is_tzlocal(tz1):
for i in range(n):
v = vals[i]
if v == NPY_NAT:
@@ -4099,7 +4099,7 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2):
pandas_datetime_to_datetimestruct(v, PANDAS_FR_ns, &dts)
dt = datetime(dts.year, dts.month, dts.day, dts.hour,
dts.min, dts.sec, dts.us, tz1)
- delta = (int(_get_utcoffset(tz1, dt).total_seconds())
+ delta = (int(get_utcoffset(tz1, dt).total_seconds())
* 1000000000)
utc_dates[i] = v - delta
else:
@@ -4126,11 +4126,11 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2):
else:
utc_dates = vals
- if _get_zone(tz2) == 'UTC':
+ if get_timezone(tz2) == 'UTC':
return utc_dates
result = np.zeros(n, dtype=np.int64)
- if _is_tzlocal(tz2):
+ if is_tzlocal(tz2):
for i in range(n):
v = utc_dates[i]
if v == NPY_NAT:
@@ -4139,7 +4139,7 @@ def tz_convert(ndarray[int64_t] vals, object tz1, object tz2):
pandas_datetime_to_datetimestruct(v, PANDAS_FR_ns, &dts)
dt = datetime(dts.year, dts.month, dts.day, dts.hour,
dts.min, dts.sec, dts.us, tz2)
- delta = (int(_get_utcoffset(tz2, dt).total_seconds())
+ delta = (int(get_utcoffset(tz2, dt).total_seconds())
* 1000000000)
result[i] = v + delta
return result
@@ -4202,13 +4202,13 @@ def tz_convert_single(int64_t val, object tz1, object tz2):
return val
# Convert to UTC
- if _is_tzlocal(tz1):
+ if is_tzlocal(tz1):
pandas_datetime_to_datetimestruct(val, PANDAS_FR_ns, &dts)
dt = datetime(dts.year, dts.month, dts.day, dts.hour,
dts.min, dts.sec, dts.us, tz1)
- delta = int(_get_utcoffset(tz1, dt).total_seconds()) * 1000000000
+ delta = int(get_utcoffset(tz1, dt).total_seconds()) * 1000000000
utc_date = val - delta
- elif _get_zone(tz1) != 'UTC':
+ elif get_timezone(tz1) != 'UTC':
trans, deltas, typ = _get_dst_info(tz1)
pos = trans.searchsorted(val, side='right') - 1
if pos < 0:
@@ -4218,13 +4218,13 @@ def tz_convert_single(int64_t val, object tz1, object tz2):
else:
utc_date = val
- if _get_zone(tz2) == 'UTC':
+ if get_timezone(tz2) == 'UTC':
return utc_date
- if _is_tzlocal(tz2):
+ if is_tzlocal(tz2):
pandas_datetime_to_datetimestruct(val, PANDAS_FR_ns, &dts)
dt = datetime(dts.year, dts.month, dts.day, dts.hour,
dts.min, dts.sec, dts.us, tz2)
- delta = int(_get_utcoffset(tz2, dt).total_seconds()) * 1000000000
+ delta = int(get_utcoffset(tz2, dt).total_seconds()) * 1000000000
return utc_date + delta
# Convert UTC to other timezone
@@ -4289,13 +4289,13 @@ cdef object _get_dst_info(object tz):
"""
cache_key = _tz_cache_key(tz)
if cache_key is None:
- num = int(_get_utcoffset(tz, None).total_seconds()) * 1000000000
+ num = int(get_utcoffset(tz, None).total_seconds()) * 1000000000
return (np.array([NPY_NAT + 1], dtype=np.int64),
np.array([num], dtype=np.int64),
None)
if cache_key not in dst_cache:
- if _treat_tz_as_pytz(tz):
+ if treat_tz_as_pytz(tz):
trans = np.array(tz._utc_transition_times, dtype='M8[ns]')
trans = trans.view('i8')
try:
@@ -4306,7 +4306,7 @@ cdef object _get_dst_info(object tz):
deltas = _unbox_utcoffsets(tz._transition_info)
typ = 'pytz'
- elif _treat_tz_as_dateutil(tz):
+ elif treat_tz_as_dateutil(tz):
if len(tz._trans_list):
# get utc trans times
trans_list = _get_utc_trans_times_from_dateutil_tz(tz)
@@ -4336,7 +4336,7 @@ cdef object _get_dst_info(object tz):
else:
# static tzinfo
trans = np.array([NPY_NAT + 1], dtype=np.int64)
- num = int(_get_utcoffset(tz, None).total_seconds()) * 1000000000
+ num = int(get_utcoffset(tz, None).total_seconds()) * 1000000000
deltas = np.array([num], dtype=np.int64)
typ = 'static'
@@ -4405,13 +4405,13 @@ def tz_localize_to_utc(ndarray[int64_t] vals, object tz, object ambiguous=None,
result = np.empty(n, dtype=np.int64)
- if _is_tzlocal(tz):
+ if is_tzlocal(tz):
for i in range(n):
v = vals[i]
pandas_datetime_to_datetimestruct(v, PANDAS_FR_ns, &dts)
dt = datetime(dts.year, dts.month, dts.day, dts.hour,
dts.min, dts.sec, dts.us, tz)
- delta = int(_get_utcoffset(tz, dt).total_seconds()) * 1000000000
+ delta = int(get_utcoffset(tz, dt).total_seconds()) * 1000000000
result[i] = v - delta
return result
@@ -5116,7 +5116,7 @@ cdef _normalize_local(ndarray[int64_t] stamps, object tz):
ndarray[int64_t] trans, deltas, pos
pandas_datetimestruct dts
- if _is_utc(tz):
+ if is_utc(tz):
with nogil:
for i in range(n):
if stamps[i] == NPY_NAT:
@@ -5125,7 +5125,7 @@ cdef _normalize_local(ndarray[int64_t] stamps, object tz):
pandas_datetime_to_datetimestruct(
stamps[i], PANDAS_FR_ns, &dts)
result[i] = _normalized_stamp(&dts)
- elif _is_tzlocal(tz):
+ elif is_tzlocal(tz):
for i in range(n):
if stamps[i] == NPY_NAT:
result[i] = NPY_NAT
@@ -5133,7 +5133,7 @@ cdef _normalize_local(ndarray[int64_t] stamps, object tz):
pandas_datetime_to_datetimestruct(stamps[i], PANDAS_FR_ns, &dts)
dt = datetime(dts.year, dts.month, dts.day, dts.hour,
dts.min, dts.sec, dts.us, tz)
- delta = int(_get_utcoffset(tz, dt).total_seconds()) * 1000000000
+ delta = int(get_utcoffset(tz, dt).total_seconds()) * 1000000000
pandas_datetime_to_datetimestruct(stamps[i] + delta,
PANDAS_FR_ns, &dts)
result[i] = _normalized_stamp(&dts)
@@ -5180,12 +5180,12 @@ def dates_normalized(ndarray[int64_t] stamps, tz=None):
Py_ssize_t i, n = len(stamps)
pandas_datetimestruct dts
- if tz is None or _is_utc(tz):
+ if tz is None or is_utc(tz):
for i in range(n):
pandas_datetime_to_datetimestruct(stamps[i], PANDAS_FR_ns, &dts)
if (dts.hour + dts.min + dts.sec + dts.us) > 0:
return False
- elif _is_tzlocal(tz):
+ elif is_tzlocal(tz):
for i in range(n):
pandas_datetime_to_datetimestruct(stamps[i], PANDAS_FR_ns, &dts)
dt = datetime(dts.year, dts.month, dts.day, dts.hour, dts.min,
diff --git a/pandas/_libs/tslibs/timezones.pxd b/pandas/_libs/tslibs/timezones.pxd
index 897bd8af7e2de..ead5566440ca0 100644
--- a/pandas/_libs/tslibs/timezones.pxd
+++ b/pandas/_libs/tslibs/timezones.pxd
@@ -1,12 +1,12 @@
# -*- coding: utf-8 -*-
# cython: profile=False
-cdef bint _is_utc(object tz)
-cdef bint _is_tzlocal(object tz)
+cdef bint is_utc(object tz)
+cdef bint is_tzlocal(object tz)
-cdef bint _treat_tz_as_pytz(object tz)
-cdef bint _treat_tz_as_dateutil(object tz)
+cdef bint treat_tz_as_pytz(object tz)
+cdef bint treat_tz_as_dateutil(object tz)
-cdef object _get_zone(object tz)
+cpdef object get_timezone(object tz)
-cpdef _get_utcoffset(tzinfo, obj)
+cpdef get_utcoffset(tzinfo, obj)
diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx
index 249eedef4bb09..3db369a09ba2d 100644
--- a/pandas/_libs/tslibs/timezones.pyx
+++ b/pandas/_libs/tslibs/timezones.pyx
@@ -10,24 +10,24 @@ import pytz
UTC = pytz.utc
-cdef inline bint _is_utc(object tz):
+cdef inline bint is_utc(object tz):
return tz is UTC or isinstance(tz, _dateutil_tzutc)
-cdef inline bint _is_tzlocal(object tz):
+cdef inline bint is_tzlocal(object tz):
return isinstance(tz, _dateutil_tzlocal)
-cdef inline bint _treat_tz_as_pytz(object tz):
+cdef inline bint treat_tz_as_pytz(object tz):
return hasattr(tz, '_utc_transition_times') and hasattr(
tz, '_transition_info')
-cdef inline bint _treat_tz_as_dateutil(object tz):
+cdef inline bint treat_tz_as_dateutil(object tz):
return hasattr(tz, '_trans_list') and hasattr(tz, '_trans_idx')
-cdef inline object _get_zone(object tz):
+cpdef inline object get_timezone(object tz):
"""
We need to do several things here:
1) Distinguish between pytz and dateutil timezones
@@ -40,10 +40,10 @@ cdef inline object _get_zone(object tz):
the tz name. It needs to be a string so that we can serialize it with
UJSON/pytables. maybe_get_tz (below) is the inverse of this process.
"""
- if _is_utc(tz):
+ if is_utc(tz):
return 'UTC'
else:
- if _treat_tz_as_dateutil(tz):
+ if treat_tz_as_dateutil(tz):
if '.tar.gz' in tz._filename:
raise ValueError(
'Bad tz filename. Dateutil on python 3 on windows has a '
@@ -64,14 +64,10 @@ cdef inline object _get_zone(object tz):
except AttributeError:
return tz
-
-def get_timezone(tz):
- return _get_zone(tz)
-
#----------------------------------------------------------------------
# UTC Offsets
-cpdef _get_utcoffset(tzinfo, obj):
+cpdef get_utcoffset(tzinfo, obj):
try:
return tzinfo._utcoffset
except AttributeError:
| See discussion in #17497
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17502 | 2017-09-12T22:54:44Z | 2017-09-13T23:20:53Z | 2017-09-13T23:20:53Z | 2017-10-30T16:24:53Z |
added nearest to resample + test | diff --git a/doc/source/api.rst b/doc/source/api.rst
index 4e02f7b11f466..6b3e6bedcb24b 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -2025,6 +2025,7 @@ Upsampling
Resampler.backfill
Resampler.bfill
Resampler.pad
+ Resampler.nearest
Resampler.fillna
Resampler.asfreq
Resampler.interpolate
diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index 722e19d2703b5..86bd3c354ccc6 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -28,6 +28,7 @@ New features
and :class:`~pandas.ExcelWriter` to work properly with the file system path protocol (:issue:`13823`)
- Added ``skipna`` parameter to :func:`~pandas.api.types.infer_dtype` to
support type inference in the presence of missing values (:issue:`17059`).
+- :class:`~pandas.Resampler.nearest` is added to support nearest-neighbor upsampling (:issue:`17496`).
.. _whatsnew_0210.enhancements.infer_objects:
diff --git a/pandas/core/resample.py b/pandas/core/resample.py
index 96e7a6a3b3904..01c7e875b8ecc 100644
--- a/pandas/core/resample.py
+++ b/pandas/core/resample.py
@@ -455,6 +455,10 @@ def pad(self, limit=None):
limit : integer, optional
limit of how many values to fill
+ Returns
+ -------
+ an upsampled Series
+
See Also
--------
Series.fillna
@@ -463,6 +467,28 @@ def pad(self, limit=None):
return self._upsample('pad', limit=limit)
ffill = pad
+ def nearest(self, limit=None):
+ """
+ Fill values with nearest neighbor starting from center
+
+ Parameters
+ ----------
+ limit : integer, optional
+ limit of how many values to fill
+
+ .. versionadded:: 0.21.0
+
+ Returns
+ -------
+ an upsampled Series
+
+ See Also
+ --------
+ Series.fillna
+ DataFrame.fillna
+ """
+ return self._upsample('nearest', limit=limit)
+
def backfill(self, limit=None):
"""
Backward fill the values
@@ -472,6 +498,10 @@ def backfill(self, limit=None):
limit : integer, optional
limit of how many values to fill
+ Returns
+ -------
+ an upsampled Series
+
See Also
--------
Series.fillna
diff --git a/pandas/tests/test_resample.py b/pandas/tests/test_resample.py
index d42e37048d87f..28a68a0a6e36d 100644
--- a/pandas/tests/test_resample.py
+++ b/pandas/tests/test_resample.py
@@ -1329,6 +1329,14 @@ def test_upsample_with_limit(self):
expected = ts.reindex(result.index, method='ffill', limit=2)
assert_series_equal(result, expected)
+ def test_nearest_upsample_with_limit(self):
+ rng = date_range('1/1/2000', periods=3, freq='5t')
+ ts = Series(np.random.randn(len(rng)), rng)
+
+ result = ts.resample('t').nearest(limit=2)
+ expected = ts.reindex(result.index, method='nearest', limit=2)
+ assert_series_equal(result, expected)
+
def test_resample_ohlc(self):
s = self.series
@@ -2934,6 +2942,24 @@ def test_getitem_multiple(self):
result = r['buyer'].count()
assert_series_equal(result, expected)
+ def test_nearest(self):
+
+ # GH 17496
+ # Resample nearest
+ index = pd.date_range('1/1/2000', periods=3, freq='T')
+ result = pd.Series(range(3), index=index).resample('20s').nearest()
+
+ expected = pd.Series(
+ np.array([0, 0, 1, 1, 1, 2, 2]),
+ index=pd.DatetimeIndex(
+ ['2000-01-01 00:00:00', '2000-01-01 00:00:20',
+ '2000-01-01 00:00:40', '2000-01-01 00:01:00',
+ '2000-01-01 00:01:20', '2000-01-01 00:01:40',
+ '2000-01-01 00:02:00'],
+ dtype='datetime64[ns]',
+ freq='20S'))
+ assert_series_equal(result, expected)
+
def test_methods(self):
g = self.frame.groupby('A')
r = g.resample('2s')
@@ -2960,7 +2986,7 @@ def test_methods(self):
expected = g.B.apply(lambda x: getattr(x.resample('2s'), f)())
assert_series_equal(result, expected)
- for f in ['backfill', 'ffill', 'asfreq']:
+ for f in ['nearest', 'backfill', 'ffill', 'asfreq']:
result = getattr(r, f)()
expected = g.apply(lambda x: getattr(x.resample('2s'), f)())
assert_frame_equal(result, expected)
| - [x] closes #17496
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry | https://api.github.com/repos/pandas-dev/pandas/pulls/17498 | 2017-09-11T19:37:58Z | 2017-09-17T21:20:58Z | 2017-09-17T21:20:58Z | 2017-09-17T21:21:15Z |
Follow-up to #17419 | diff --git a/pandas/_libs/period.pyx b/pandas/_libs/period.pyx
index 08962bca824ca..2b0734f5cf2e7 100644
--- a/pandas/_libs/period.pyx
+++ b/pandas/_libs/period.pyx
@@ -33,11 +33,10 @@ from util cimport is_period_object, is_string_object
from lib cimport is_null_datetimelike, is_period
from pandas._libs import tslib, lib
from pandas._libs.tslib import (Timedelta, Timestamp, iNaT,
- NaT, _get_utcoffset)
-from tslibs.timezones cimport _is_utc
+ NaT)
+from tslibs.timezones cimport _is_utc, _is_tzlocal, _get_utcoffset
from tslib cimport (
maybe_get_tz,
- _is_tzlocal,
_get_dst_info,
_nat_scalar_rules)
diff --git a/pandas/_libs/src/inference.pyx b/pandas/_libs/src/inference.pyx
index 6b5a8f20f0067..95145ff49b02f 100644
--- a/pandas/_libs/src/inference.pyx
+++ b/pandas/_libs/src/inference.pyx
@@ -2,7 +2,8 @@ import sys
from decimal import Decimal
cimport util
cimport cython
-from tslib import NaT, get_timezone
+from tslib import NaT
+from tslibs.timezones cimport _get_zone
from datetime import datetime, timedelta
iNaT = util.get_nat()
@@ -900,13 +901,13 @@ cpdef bint is_datetime_with_singletz_array(ndarray[object] values):
for i in range(n):
base_val = values[i]
if base_val is not NaT:
- base_tz = get_timezone(getattr(base_val, 'tzinfo', None))
+ base_tz = _get_zone(getattr(base_val, 'tzinfo', None))
for j in range(i, n):
val = values[j]
if val is not NaT:
tz = getattr(val, 'tzinfo', None)
- if base_tz != tz and base_tz != get_timezone(tz):
+ if base_tz != tz and base_tz != _get_zone(tz):
return False
break
diff --git a/pandas/_libs/tslib.pxd b/pandas/_libs/tslib.pxd
index 1d81c3cc15cd8..c1b25963a6257 100644
--- a/pandas/_libs/tslib.pxd
+++ b/pandas/_libs/tslib.pxd
@@ -3,7 +3,6 @@ from numpy cimport ndarray, int64_t
cdef convert_to_tsobject(object, object, object, bint, bint)
cpdef convert_to_timedelta64(object, object)
cpdef object maybe_get_tz(object)
-cdef bint _is_tzlocal(object)
cdef object _get_dst_info(object)
cdef bint _nat_scalar_rules[6]
cdef bint _check_all_nulls(obj)
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx
index b1f794a0030d1..a8ae0fcd733d6 100644
--- a/pandas/_libs/tslib.pyx
+++ b/pandas/_libs/tslib.pyx
@@ -107,7 +107,13 @@ cdef int64_t NPY_NAT = util.get_nat()
iNaT = NPY_NAT
-from tslibs.timezones cimport _is_utc
+from tslibs.timezones cimport (
+ _is_utc, _is_tzlocal,
+ _treat_tz_as_dateutil, _treat_tz_as_pytz,
+ _get_zone,
+ _get_utcoffset)
+from tslibs.timezones import get_timezone, _get_utcoffset # noqa
+
cdef inline object create_timestamp_from_ts(
int64_t value, pandas_datetimestruct dts,
@@ -235,10 +241,6 @@ def ints_to_pytimedelta(ndarray[int64_t] arr, box=False):
return result
-cdef inline bint _is_tzlocal(object tz):
- return isinstance(tz, _dateutil_tzlocal)
-
-
cdef inline bint _is_fixed_offset(object tz):
if _treat_tz_as_dateutil(tz):
if len(tz._trans_idx) == 0 and len(tz._trans_list) == 0:
@@ -1443,11 +1445,6 @@ cdef class _TSObject:
def __get__(self):
return self.value
-cpdef _get_utcoffset(tzinfo, obj):
- try:
- return tzinfo._utcoffset
- except AttributeError:
- return tzinfo.utcoffset(obj)
# helper to extract datetime and int64 from several different possibilities
cdef convert_to_tsobject(object ts, object tz, object unit,
@@ -1712,48 +1709,6 @@ def _localize_pydatetime(object dt, object tz):
return dt.replace(tzinfo=tz)
-def get_timezone(tz):
- return _get_zone(tz)
-
-
-cdef inline object _get_zone(object tz):
- """
- We need to do several things here:
- 1) Distinguish between pytz and dateutil timezones
- 2) Not be over-specific (e.g. US/Eastern with/without DST is same *zone*
- but a different tz object)
- 3) Provide something to serialize when we're storing a datetime object
- in pytables.
-
- We return a string prefaced with dateutil if it's a dateutil tz, else just
- the tz name. It needs to be a string so that we can serialize it with
- UJSON/pytables. maybe_get_tz (below) is the inverse of this process.
- """
- if _is_utc(tz):
- return 'UTC'
- else:
- if _treat_tz_as_dateutil(tz):
- if '.tar.gz' in tz._filename:
- raise ValueError(
- 'Bad tz filename. Dateutil on python 3 on windows has a '
- 'bug which causes tzfile._filename to be the same for all '
- 'timezone files. Please construct dateutil timezones '
- 'implicitly by passing a string like "dateutil/Europe'
- '/London" when you construct your pandas objects instead '
- 'of passing a timezone object. See '
- 'https://github.com/pandas-dev/pandas/pull/7362')
- return 'dateutil/' + tz._filename
- else:
- # tz is a pytz timezone or unknown.
- try:
- zone = tz.zone
- if zone is None:
- return tz
- return zone
- except AttributeError:
- return tz
-
-
cpdef inline object maybe_get_tz(object tz):
"""
(Maybe) Construct a timezone object from a string. If tz is a string, use
@@ -4285,13 +4240,6 @@ def tz_convert_single(int64_t val, object tz1, object tz2):
# Timezone data caches, key is the pytz string or dateutil file name.
dst_cache = {}
-cdef inline bint _treat_tz_as_pytz(object tz):
- return hasattr(tz, '_utc_transition_times') and hasattr(
- tz, '_transition_info')
-
-cdef inline bint _treat_tz_as_dateutil(object tz):
- return hasattr(tz, '_trans_list') and hasattr(tz, '_trans_idx')
-
def _p_tz_cache_key(tz):
""" Python interface for cache function to facilitate testing."""
diff --git a/pandas/_libs/tslibs/timezones.pxd b/pandas/_libs/tslibs/timezones.pxd
index 0708282abe1d0..897bd8af7e2de 100644
--- a/pandas/_libs/tslibs/timezones.pxd
+++ b/pandas/_libs/tslibs/timezones.pxd
@@ -2,3 +2,11 @@
# cython: profile=False
cdef bint _is_utc(object tz)
+cdef bint _is_tzlocal(object tz)
+
+cdef bint _treat_tz_as_pytz(object tz)
+cdef bint _treat_tz_as_dateutil(object tz)
+
+cdef object _get_zone(object tz)
+
+cpdef _get_utcoffset(tzinfo, obj)
diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx
index 43709e77b70d5..249eedef4bb09 100644
--- a/pandas/_libs/tslibs/timezones.pyx
+++ b/pandas/_libs/tslibs/timezones.pyx
@@ -2,7 +2,9 @@
# cython: profile=False
# dateutil compat
-from dateutil.tz import tzutc as _dateutil_tzutc
+from dateutil.tz import (
+ tzutc as _dateutil_tzutc,
+ tzlocal as _dateutil_tzlocal)
import pytz
UTC = pytz.utc
@@ -10,3 +12,67 @@ UTC = pytz.utc
cdef inline bint _is_utc(object tz):
return tz is UTC or isinstance(tz, _dateutil_tzutc)
+
+
+cdef inline bint _is_tzlocal(object tz):
+ return isinstance(tz, _dateutil_tzlocal)
+
+
+cdef inline bint _treat_tz_as_pytz(object tz):
+ return hasattr(tz, '_utc_transition_times') and hasattr(
+ tz, '_transition_info')
+
+
+cdef inline bint _treat_tz_as_dateutil(object tz):
+ return hasattr(tz, '_trans_list') and hasattr(tz, '_trans_idx')
+
+
+cdef inline object _get_zone(object tz):
+ """
+ We need to do several things here:
+ 1) Distinguish between pytz and dateutil timezones
+ 2) Not be over-specific (e.g. US/Eastern with/without DST is same *zone*
+ but a different tz object)
+ 3) Provide something to serialize when we're storing a datetime object
+ in pytables.
+
+ We return a string prefaced with dateutil if it's a dateutil tz, else just
+ the tz name. It needs to be a string so that we can serialize it with
+ UJSON/pytables. maybe_get_tz (below) is the inverse of this process.
+ """
+ if _is_utc(tz):
+ return 'UTC'
+ else:
+ if _treat_tz_as_dateutil(tz):
+ if '.tar.gz' in tz._filename:
+ raise ValueError(
+ 'Bad tz filename. Dateutil on python 3 on windows has a '
+ 'bug which causes tzfile._filename to be the same for all '
+ 'timezone files. Please construct dateutil timezones '
+ 'implicitly by passing a string like "dateutil/Europe'
+ '/London" when you construct your pandas objects instead '
+ 'of passing a timezone object. See '
+ 'https://github.com/pandas-dev/pandas/pull/7362')
+ return 'dateutil/' + tz._filename
+ else:
+ # tz is a pytz timezone or unknown.
+ try:
+ zone = tz.zone
+ if zone is None:
+ return tz
+ return zone
+ except AttributeError:
+ return tz
+
+
+def get_timezone(tz):
+ return _get_zone(tz)
+
+#----------------------------------------------------------------------
+# UTC Offsets
+
+cpdef _get_utcoffset(tzinfo, obj):
+ try:
+ return tzinfo._utcoffset
+ except AttributeError:
+ return tzinfo.utcoffset(obj)
| This moves a few other 3ish line functions from tslib to tslibs.timezones.
One non-trivial function `_get_zone` is cut/pasted over.
Replaces imports in inference.pyx and period.pyx with imports from tslibs.timezones. In the inference, case, replaces the import of the python version `get_timezone` with the cython version `_get_zone`
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17497 | 2017-09-11T16:26:48Z | 2017-09-12T10:09:50Z | 2017-09-12T10:09:50Z | 2017-10-30T16:24:53Z |
DEPR: Add warning for True for dropna of SeriesGroupBy.nth | diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index f50052347cfb5..d39a17a01382d 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -340,6 +340,8 @@ Deprecations
- ``pd.options.html.border`` has been deprecated in favor of ``pd.options.display.html.border`` (:issue:`15793`).
+- :func:`SeriesGroupBy.nth` has deprecated ``True`` in favor of ``'all'`` for its kwarg ``dropna`` (:issue:`11038`).
+
.. _whatsnew_0210.prior_deprecations:
Removal of prior version deprecations/changes
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py
index 248f3b2095a78..f14ed08a27fae 100644
--- a/pandas/core/groupby.py
+++ b/pandas/core/groupby.py
@@ -1393,12 +1393,21 @@ def nth(self, n, dropna=None):
return out.sort_index() if self.sort else out
- if isinstance(self._selected_obj, DataFrame) and \
- dropna not in ['any', 'all']:
- # Note: when agg-ing picker doesn't raise this, just returns NaN
- raise ValueError("For a DataFrame groupby, dropna must be "
- "either None, 'any' or 'all', "
- "(was passed %s)." % (dropna),)
+ if dropna not in ['any', 'all']:
+ if isinstance(self._selected_obj, Series) and dropna is True:
+ warnings.warn("the dropna='%s' keyword is deprecated,"
+ "use dropna='all' instead. "
+ "For a Series groupby, dropna must be "
+ "either None, 'any' or 'all'." % (dropna),
+ FutureWarning,
+ stacklevel=2)
+ dropna = 'all'
+ else:
+ # Note: when agg-ing picker doesn't raise this,
+ # just returns NaN
+ raise ValueError("For a DataFrame groupby, dropna must be "
+ "either None, 'any' or 'all', "
+ "(was passed %s)." % (dropna),)
# old behaviour, but with all and any support for DataFrames.
# modified in GH 7559 to have better perf
diff --git a/pandas/tests/groupby/test_nth.py b/pandas/tests/groupby/test_nth.py
index 28392537be3c6..ffbede0eb208f 100644
--- a/pandas/tests/groupby/test_nth.py
+++ b/pandas/tests/groupby/test_nth.py
@@ -2,7 +2,10 @@
import pandas as pd
from pandas import DataFrame, MultiIndex, Index, Series, isna
from pandas.compat import lrange
-from pandas.util.testing import assert_frame_equal, assert_series_equal
+from pandas.util.testing import (
+ assert_frame_equal,
+ assert_produces_warning,
+ assert_series_equal)
from .common import MixIn
@@ -171,7 +174,10 @@ def test_nth(self):
# doc example
df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=['A', 'B'])
g = df.groupby('A')
- result = g.B.nth(0, dropna=True)
+ # PR 17493, related to issue 11038
+ # test Series.nth with True for dropna produces DeprecationWarning
+ with assert_produces_warning(FutureWarning):
+ result = g.B.nth(0, dropna=True)
expected = g.B.first()
assert_series_equal(result, expected)
| - [x] deprecates undocumented params to partially addresses #11038
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17493 | 2017-09-11T02:19:00Z | 2017-09-12T10:35:55Z | 2017-09-12T10:35:55Z | 2017-09-12T14:14:37Z |
Add file-like object to docs for Feather | diff --git a/pandas/io/feather_format.py b/pandas/io/feather_format.py
index 87a4931421d7d..b2bf4ab7ff7f1 100644
--- a/pandas/io/feather_format.py
+++ b/pandas/io/feather_format.py
@@ -41,8 +41,7 @@ def to_feather(df, path):
Parameters
----------
df : DataFrame
- path : string
- File path
+ path : string file path, or file-like object
"""
path = _stringify_path(path)
@@ -92,8 +91,7 @@ def read_feather(path, nthreads=1):
Parameters
----------
- path : string
- File path
+ path : string file path, or file-like object
nthreads : int, default 1
Number of CPU threads to use when reading to pandas.DataFrame
| `read_feather` and `to_feather` accept file-like object. For example, something like this works:
```
# python -uc "import pandas, sys; print(pandas.read_feather(sys.stdin))" < a.feather
id
0 1.0
1 2.0
2 3.0
3 NaN
4 5.0
5 6.0
6 7.0
7 8.0
# python -uc "import pandas, sys; pandas.to_feather(pandas.read_feather(sys.stdin), sys.stdout)" < a.feather > b.feather
```
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17492 | 2017-09-11T01:21:08Z | 2017-09-11T11:03:19Z | 2017-09-11T11:03:19Z | 2017-09-11T18:35:00Z |
COMPAT: Iteration should always yield a python scalar | diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index eccd71f45ec27..4cea36569e8e4 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -188,6 +188,53 @@ the target. Now, a ``ValueError`` will be raised when such an input is passed in
...
ValueError: Cannot operate inplace if there is no assignment
+.. _whatsnew_0210.api_breaking.iteration_scalars:
+
+Iteration of Series/Index will now return python scalars
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Previously, when using certain iteration methods for a ``Series`` with dtype ``int`` or ``float``, you would receive a ``numpy`` scalar, e.g. a ``np.int64``, rather than a python ``int``. Issue (:issue:`10904`) corrected this for ``Series.tolist()`` and ``list(Series)``. This change makes all iteration methods consistent, in particular, for ``__iter__()`` and ``.map()``; note that this only affect int/float dtypes. (:issue:`13236`, :issue:`13258`, :issue:`14216`).
+
+.. ipython:: python
+
+ s = Series([1, 2, 3])
+ s
+
+Previously:
+
+.. code-block:: python
+
+ In [2]: type(list(s)[0])
+ Out[2]: numpy.int64
+
+New Behaviour:
+
+.. ipython:: python
+
+ type(list(s)[0])
+
+Furthermore this will now correctly box the results of iteration for :func:`DataFrame.to_dict` as well.
+
+.. ipython:: python
+
+ d = {'a':[1], 'b':['b']}
+ df = DataFrame(d)
+
+Previously:
+
+.. code-block:: python
+
+ In [8]: type(df.to_dict()['a'][0])
+ Out[8]: numpy.int64
+
+New Behaviour:
+
+.. ipython:: python
+
+ type(df.to_dict()['a'][0])
+
+.. _whatsnew_0210.api_breaking.dtype_conversions:
+
Dtype Conversions
^^^^^^^^^^^^^^^^^
diff --git a/pandas/core/base.py b/pandas/core/base.py
index d60a8515dc920..62d89eac4b354 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -8,7 +8,12 @@
from pandas.core.dtypes.missing import isna
from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries, ABCIndexClass
-from pandas.core.dtypes.common import is_object_dtype, is_list_like, is_scalar
+from pandas.core.dtypes.common import (
+ is_object_dtype,
+ is_list_like,
+ is_scalar,
+ is_datetimelike)
+
from pandas.util._validators import validate_bool_kwarg
from pandas.core import common as com
@@ -18,7 +23,8 @@
from pandas.compat import PYPY
from pandas.util._decorators import (Appender, cache_readonly,
deprecate_kwarg, Substitution)
-from pandas.core.common import AbstractMethodError
+from pandas.core.common import AbstractMethodError, _maybe_box_datetimelike
+
from pandas.core.accessor import DirNamesMixin
_shared_docs = dict()
@@ -884,6 +890,21 @@ def argmin(self, axis=None):
"""
return nanops.nanargmin(self.values)
+ def tolist(self):
+ """
+ return a list of the values; box to scalars
+ """
+ return list(self.__iter__())
+
+ def __iter__(self):
+ """
+ provide iteration over the values; box to scalars
+ """
+ if is_datetimelike(self):
+ return (_maybe_box_datetimelike(x) for x in self._values)
+ else:
+ return iter(self._values.tolist())
+
@cache_readonly
def hasnans(self):
""" return if I have any nans; enables various perf speedups """
diff --git a/pandas/core/categorical.py b/pandas/core/categorical.py
index 1c2a29333001c..dbd2a79b7e46d 100644
--- a/pandas/core/categorical.py
+++ b/pandas/core/categorical.py
@@ -399,6 +399,12 @@ def itemsize(self):
""" return the size of a single category """
return self.categories.itemsize
+ def tolist(self):
+ """
+ return a list of my values
+ """
+ return np.array(self).tolist()
+
def reshape(self, new_shape, *args, **kwargs):
"""
.. deprecated:: 0.19.0
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index ef5f68936044a..008828cf4f309 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -585,12 +585,6 @@ def memory_usage(self, deep=False):
return result
# ops compat
- def tolist(self):
- """
- return a list of the Index values
- """
- return list(self.values)
-
@deprecate_kwarg(old_arg_name='n', new_arg_name='repeats')
def repeat(self, repeats, *args, **kwargs):
"""
@@ -1601,9 +1595,6 @@ def is_all_dates(self):
return False
return is_datetime_array(_ensure_object(self.values))
- def __iter__(self):
- return iter(self.values)
-
def __reduce__(self):
d = dict(data=self._data)
d.update(self._get_attributes_dict())
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index 0681202289311..c8044b14e4e57 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -253,6 +253,10 @@ def get_values(self):
""" return the underlying data as an ndarray """
return self._data.get_values()
+ def __iter__(self):
+ """ iterate like Categorical """
+ return self._data.__iter__()
+
@property
def codes(self):
return self._data.codes
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 6905fc1aced74..ac11c5f908fdc 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -19,7 +19,6 @@
is_integer, is_integer_dtype,
is_float_dtype,
is_extension_type, is_datetimetz,
- is_datetimelike,
is_datetime64tz_dtype,
is_timedelta64_dtype,
is_list_like,
@@ -1095,14 +1094,6 @@ def to_string(self, buf=None, na_rep='NaN', float_format=None, header=True,
with open(buf, 'w') as f:
f.write(result)
- def __iter__(self):
- """ provide iteration over the values of the Series
- box values if necessary """
- if is_datetimelike(self):
- return (_maybe_box_datetimelike(x) for x in self._values)
- else:
- return iter(self._values)
-
def iteritems(self):
"""
Lazily iterate over (index, value) tuples
@@ -1118,10 +1109,6 @@ def keys(self):
"""Alias for index"""
return self.index
- def tolist(self):
- """ Convert Series to a nested list """
- return list(self.asobject)
-
def to_dict(self, into=dict):
"""
Convert Series to {label -> value} dict or dict-like object.
diff --git a/pandas/core/sparse/array.py b/pandas/core/sparse/array.py
index 2f830a98db649..f965c91999a03 100644
--- a/pandas/core/sparse/array.py
+++ b/pandas/core/sparse/array.py
@@ -407,8 +407,18 @@ def to_dense(self, fill=None):
return self.values
def __iter__(self):
+ if np.issubdtype(self.dtype, np.floating):
+ boxer = float
+ elif np.issubdtype(self.dtype, np.integer):
+ boxer = int
+ else:
+ boxer = lambda x: x
+
for i in range(len(self)):
- yield self._get_val_at(i)
+ r = self._get_val_at(i)
+
+ # box em
+ yield boxer(r)
def __getitem__(self, key):
"""
diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py
index a62fcb506a34b..b3209da6449d6 100644
--- a/pandas/tests/frame/test_api.py
+++ b/pandas/tests/frame/test_api.py
@@ -9,7 +9,7 @@
import sys
from distutils.version import LooseVersion
-from pandas.compat import range, lrange
+from pandas.compat import range, lrange, long
from pandas import compat
from numpy.random import randn
@@ -205,15 +205,18 @@ def test_itertuples(self):
'ints': lrange(5)}, columns=['floats', 'ints'])
for tup in df.itertuples(index=False):
- assert isinstance(tup[1], np.integer)
+ assert isinstance(tup[1], (int, long))
df = self.klass(data={"a": [1, 2, 3], "b": [4, 5, 6]})
dfaa = df[['a', 'a']]
assert (list(dfaa.itertuples()) ==
[(0, 1, 1), (1, 2, 2), (2, 3, 3)])
- assert (repr(list(df.itertuples(name=None))) ==
- '[(0, 1, 4), (1, 2, 5), (2, 3, 6)]')
+
+ # repr with be int/long on windows
+ if not compat.is_platform_windows():
+ assert (repr(list(df.itertuples(name=None))) ==
+ '[(0, 1, 4), (1, 2, 5), (2, 3, 6)]')
tup = next(df.itertuples(name='TestName'))
diff --git a/pandas/tests/frame/test_convert_to.py b/pandas/tests/frame/test_convert_to.py
index 629c695b702fe..99e5630ce6a43 100644
--- a/pandas/tests/frame/test_convert_to.py
+++ b/pandas/tests/frame/test_convert_to.py
@@ -5,6 +5,7 @@
import numpy as np
from pandas import compat
+from pandas.compat import long
from pandas import (DataFrame, Series, MultiIndex, Timestamp,
date_range)
@@ -236,3 +237,15 @@ def test_to_records_datetimeindex_with_tz(self, tz):
# both converted to UTC, so they are equal
tm.assert_numpy_array_equal(result, expected)
+
+ def test_to_dict_box_scalars(self):
+ # 14216
+ # make sure that we are boxing properly
+ d = {'a': [1], 'b': ['b']}
+
+ result = DataFrame(d).to_dict()
+ assert isinstance(list(result['a'])[0], (int, long))
+ assert isinstance(list(result['b'])[0], (int, long))
+
+ result = DataFrame(d).to_dict(orient='records')
+ assert isinstance(result[0]['a'], (int, long))
diff --git a/pandas/tests/series/test_io.py b/pandas/tests/series/test_io.py
index 503185de427f1..5b7fd1ec94a90 100644
--- a/pandas/tests/series/test_io.py
+++ b/pandas/tests/series/test_io.py
@@ -10,7 +10,7 @@
from pandas import Series, DataFrame
-from pandas.compat import StringIO, u, long
+from pandas.compat import StringIO, u
from pandas.util.testing import (assert_series_equal, assert_almost_equal,
assert_frame_equal, ensure_clean)
import pandas.util.testing as tm
@@ -178,37 +178,3 @@ def test_to_dict(self, mapping):
from_method = Series(ts.to_dict(collections.Counter))
from_constructor = Series(collections.Counter(ts.iteritems()))
tm.assert_series_equal(from_method, from_constructor)
-
-
-class TestSeriesToList(TestData):
-
- def test_tolist(self):
- rs = self.ts.tolist()
- xp = self.ts.values.tolist()
- assert_almost_equal(rs, xp)
-
- # datetime64
- s = Series(self.ts.index)
- rs = s.tolist()
- assert self.ts.index[0] == rs[0]
-
- def test_tolist_np_int(self):
- # GH10904
- for t in ['int8', 'int16', 'int32', 'int64']:
- s = pd.Series([1], dtype=t)
- assert isinstance(s.tolist()[0], (int, long))
-
- def test_tolist_np_uint(self):
- # GH10904
- for t in ['uint8', 'uint16']:
- s = pd.Series([1], dtype=t)
- assert isinstance(s.tolist()[0], int)
- for t in ['uint32', 'uint64']:
- s = pd.Series([1], dtype=t)
- assert isinstance(s.tolist()[0], long)
-
- def test_tolist_np_float(self):
- # GH10904
- for t in ['float16', 'float32', 'float64']:
- s = pd.Series([1], dtype=t)
- assert isinstance(s.tolist()[0], float)
diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py
index 9e92c7cf1a9b8..210d0260b8d95 100644
--- a/pandas/tests/test_base.py
+++ b/pandas/tests/test_base.py
@@ -13,9 +13,10 @@
is_object_dtype, is_datetimetz,
needs_i8_conversion)
import pandas.util.testing as tm
-from pandas import (Series, Index, DatetimeIndex, TimedeltaIndex, PeriodIndex,
- Timedelta, IntervalIndex, Interval)
-from pandas.compat import StringIO, PYPY
+from pandas import (Series, Index, DatetimeIndex, TimedeltaIndex,
+ PeriodIndex, Timedelta, IntervalIndex, Interval,
+ CategoricalIndex, Timestamp)
+from pandas.compat import StringIO, PYPY, long
from pandas.compat.numpy import np_array_datetime64_compat
from pandas.core.base import PandasDelegate, NoNewAttributesMixin
from pandas.core.indexes.datetimelike import DatetimeIndexOpsMixin
@@ -433,7 +434,7 @@ def test_value_counts_unique_nunique(self):
# datetimetz Series returns array of Timestamp
assert result[0] == orig[0]
for r in result:
- assert isinstance(r, pd.Timestamp)
+ assert isinstance(r, Timestamp)
tm.assert_numpy_array_equal(result,
orig._values.asobject.values)
else:
@@ -1031,3 +1032,73 @@ def f():
pytest.raises(AttributeError, f)
assert not hasattr(t, "b")
+
+
+class TestToIterable(object):
+ # test that we convert an iterable to python types
+
+ dtypes = [
+ ('int8', (int, long)),
+ ('int16', (int, long)),
+ ('int32', (int, long)),
+ ('int64', (int, long)),
+ ('uint8', (int, long)),
+ ('uint16', (int, long)),
+ ('uint32', (int, long)),
+ ('uint64', (int, long)),
+ ('float16', float),
+ ('float32', float),
+ ('float64', float),
+ ('datetime64[ns]', Timestamp),
+ ('datetime64[ns, US/Eastern]', Timestamp),
+ ('timedelta64[ns]', Timedelta)]
+
+ @pytest.mark.parametrize(
+ 'dtype, rdtype',
+ dtypes + [
+ ('object', object),
+ ('category', object)])
+ @pytest.mark.parametrize(
+ 'method',
+ [
+ lambda x: x.tolist(),
+ lambda x: list(x),
+ lambda x: list(x.__iter__()),
+ ], ids=['tolist', 'list', 'iter'])
+ @pytest.mark.parametrize('typ', [Series, Index])
+ def test_iterable(self, typ, method, dtype, rdtype):
+ # gh-10904
+ # gh-13258
+ # coerce iteration to underlying python / pandas types
+ s = typ([1], dtype=dtype)
+ result = method(s)[0]
+ assert isinstance(result, rdtype)
+
+ @pytest.mark.parametrize(
+ 'dtype, rdtype',
+ dtypes + [
+ ('object', (int, long)),
+ ('category', (int, long))])
+ @pytest.mark.parametrize('typ', [Series, Index])
+ def test_iterable_map(self, typ, dtype, rdtype):
+ # gh-13236
+ # coerce iteration to underlying python / pandas types
+ s = typ([1], dtype=dtype)
+ result = s.map(type)[0]
+ if not isinstance(rdtype, tuple):
+ rdtype = tuple([rdtype])
+ assert result in rdtype
+
+ @pytest.mark.parametrize(
+ 'method',
+ [
+ lambda x: x.tolist(),
+ lambda x: list(x),
+ lambda x: list(x.__iter__()),
+ ], ids=['tolist', 'list', 'iter'])
+ def test_categorial_datetimelike(self, method):
+ i = CategoricalIndex([Timestamp('1999-12-31'),
+ Timestamp('2000-12-31')])
+
+ result = method(i)[0]
+ assert isinstance(result, Timestamp)
| xref #10904
closes #13236
closes #13258
xref #14216
| https://api.github.com/repos/pandas-dev/pandas/pulls/17491 | 2017-09-10T21:58:03Z | 2017-09-12T12:54:54Z | 2017-09-12T12:54:54Z | 2017-09-18T07:39:03Z |
Prevent UnicodeDecodeError in pivot_table under Py2 | diff --git a/doc/source/whatsnew/v0.20.0.txt b/doc/source/whatsnew/v0.20.0.txt
index 9d475390175b2..fe24f8f499172 100644
--- a/doc/source/whatsnew/v0.20.0.txt
+++ b/doc/source/whatsnew/v0.20.0.txt
@@ -1705,6 +1705,7 @@ Reshaping
- Bug in ``pd.concat()`` in which concatenating with an empty dataframe with ``join='inner'`` was being improperly handled (:issue:`15328`)
- Bug with ``sort=True`` in ``DataFrame.join`` and ``pd.merge`` when joining on indexes (:issue:`15582`)
- Bug in ``DataFrame.nsmallest`` and ``DataFrame.nlargest`` where identical values resulted in duplicated rows (:issue:`15297`)
+- Bug in :func:`pandas.pivot_table` incorrectly raising ``UnicodeError`` when passing unicode input for ```margins`` keyword (:issue:`13292`)
Numeric
^^^^^^^
diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py
index f07123ca18489..d19de6030d473 100644
--- a/pandas/core/reshape/pivot.py
+++ b/pandas/core/reshape/pivot.py
@@ -145,7 +145,7 @@ def _add_margins(table, data, values, rows, cols, aggfunc,
if not isinstance(margins_name, compat.string_types):
raise ValueError('margins_name argument must be a string')
- msg = 'Conflicting name "{name}" in margins'.format(name=margins_name)
+ msg = u'Conflicting name "{name}" in margins'.format(name=margins_name)
for level in table.index.names:
if margins_name in table.index.get_level_values(level):
raise ValueError(msg)
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
index 879ac96680fbb..bd8a999ce2330 100644
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -1625,3 +1625,13 @@ def test_isleapyear_deprecate(self):
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
assert isleapyear(2004)
+
+ def test_pivot_margins_name_unicode(self):
+ # issue #13292
+ greek = u'\u0394\u03bf\u03ba\u03b9\u03bc\u03ae'
+ frame = pd.DataFrame({'foo': [1, 2, 3]})
+ table = pd.pivot_table(frame, index=['foo'], aggfunc=len, margins=True,
+ margins_name=greek)
+ index = pd.Index([1, 2, 3, greek], dtype='object', name='foo')
+ expected = pd.DataFrame(index=index)
+ tm.assert_frame_equal(table, expected)
| - [x] closes #13292
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry | https://api.github.com/repos/pandas-dev/pandas/pulls/17489 | 2017-09-10T07:33:05Z | 2017-09-12T10:31:33Z | 2017-09-12T10:31:32Z | 2017-09-12T10:31:36Z |
BUG: DataFrame.first_valid_index() fails if there is no valid entry. | diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt
index f50052347cfb5..d5195cb1a6bf3 100644
--- a/doc/source/whatsnew/v0.21.0.txt
+++ b/doc/source/whatsnew/v0.21.0.txt
@@ -399,6 +399,7 @@ Indexing
- Bug in ``CategoricalIndex`` reindexing in which specified indices containing duplicates were not being respected (:issue:`17323`)
- Bug in intersection of ``RangeIndex`` with negative step (:issue:`17296`)
- Bug in ``IntervalIndex`` where performing a scalar lookup fails for included right endpoints of non-overlapping monotonic decreasing indexes (:issue:`16417`, :issue:`17271`)
+- Bug in :meth:`DataFrame.first_valid_index` and :meth:`DataFrame.last_valid_index` when no valid entry (:issue:`17400`)
I/O
^^^
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 5991ec825c841..2318f6133fc19 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4069,23 +4069,27 @@ def update(self, other, join='left', overwrite=True, filter_func=None,
# ----------------------------------------------------------------------
# Misc methods
+ def _get_valid_indices(self):
+ is_valid = self.count(1) > 0
+ return self.index[is_valid]
+
+ @Appender(_shared_docs['valid_index'] % {
+ 'position': 'first', 'klass': 'DataFrame'})
def first_valid_index(self):
- """
- Return label for first non-NA/null value
- """
if len(self) == 0:
return None
- return self.index[self.count(1) > 0][0]
+ valid_indices = self._get_valid_indices()
+ return valid_indices[0] if len(valid_indices) else None
+ @Appender(_shared_docs['valid_index'] % {
+ 'position': 'first', 'klass': 'DataFrame'})
def last_valid_index(self):
- """
- Return label for last non-NA/null value
- """
if len(self) == 0:
return None
- return self.index[self.count(1) > 0][-1]
+ valid_indices = self._get_valid_indices()
+ return valid_indices[-1] if len(valid_indices) else None
# ----------------------------------------------------------------------
# Data reshaping
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 8d16b079ba2c8..1d2fc29c2ea7b 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -6763,6 +6763,22 @@ def transform(self, func, *args, **kwargs):
cls.transform = transform
+ # ----------------------------------------------------------------------
+ # Misc methods
+
+ _shared_docs['valid_index'] = """
+ Return index for %(position)s non-NA/null value.
+
+ Notes
+ --------
+ If all elements are non-NA/null, returns None.
+ Also returns None for empty %(klass)s.
+
+ Returns
+ --------
+ scalar : type of index
+ """
+
def _doc_parms(cls):
"""Return a tuple of the doc parms."""
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 6905fc1aced74..a2a16af0d37e3 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2838,10 +2838,9 @@ def dropna(self, axis=0, inplace=False, **kwargs):
valid = lambda self, inplace=False, **kwargs: self.dropna(inplace=inplace,
**kwargs)
+ @Appender(generic._shared_docs['valid_index'] % {
+ 'position': 'first', 'klass': 'Series'})
def first_valid_index(self):
- """
- Return label for first non-NA/null value
- """
if len(self) == 0:
return None
@@ -2852,10 +2851,9 @@ def first_valid_index(self):
else:
return self.index[i]
+ @Appender(generic._shared_docs['valid_index'] % {
+ 'position': 'last', 'klass': 'Series'})
def last_valid_index(self):
- """
- Return label for last non-NA/null value
- """
if len(self) == 0:
return None
diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py
index 19fbf854256c6..26a2c6f9a5045 100644
--- a/pandas/tests/frame/test_timeseries.py
+++ b/pandas/tests/frame/test_timeseries.py
@@ -440,6 +440,11 @@ def test_first_last_valid(self):
assert empty.last_valid_index() is None
assert empty.first_valid_index() is None
+ # GH17400: no valid entries
+ frame[:] = nan
+ assert frame.last_valid_index() is None
+ assert frame.first_valid_index() is None
+
def test_at_time_frame(self):
rng = date_range('1/1/2000', '1/5/2000', freq='5min')
ts = DataFrame(np.random.randn(len(rng), 2), index=rng)
| Just checking the number of valid entries and if it's zero, return `None`.
Also fixed same issue on `DataFrame.last_valid_index()`.
Add docstrings to both methods of `DataFrame` and `Series`.
- [x] closes #17400
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17488 | 2017-09-10T06:17:43Z | 2017-09-23T16:14:10Z | 2017-09-23T16:14:10Z | 2017-09-23T16:14:12Z |
Remove incorrect kwds from DateOffset tests | diff --git a/pandas/tests/tseries/test_offsets.py b/pandas/tests/tseries/test_offsets.py
index e03b3e0a85e5e..7e6e85f322fe0 100644
--- a/pandas/tests/tseries/test_offsets.py
+++ b/pandas/tests/tseries/test_offsets.py
@@ -111,7 +111,10 @@ def offset_types(self):
def _get_offset(self, klass, value=1, normalize=False):
# create instance from offset class
- if klass is FY5253 or klass is FY5253Quarter:
+ if klass is FY5253:
+ klass = klass(n=value, startingMonth=1, weekday=1,
+ variation='last', normalize=normalize)
+ elif klass is FY5253Quarter:
klass = klass(n=value, startingMonth=1, weekday=1,
qtr_with_extra_week=1, variation='last',
normalize=normalize)
@@ -2629,7 +2632,7 @@ def test_offset(self):
def test_day_of_month(self):
dt = datetime(2007, 1, 1)
- offset = MonthEnd(day=20)
+ offset = MonthEnd()
result = dt + offset
assert result == Timestamp(2007, 1, 31)
@@ -3678,7 +3681,7 @@ def test_onOffset(self):
1, startingMonth=8, weekday=WeekDay.THU,
qtr_with_extra_week=4)
offset_n = FY5253(weekday=WeekDay.TUE, startingMonth=12,
- variation="nearest", qtr_with_extra_week=4)
+ variation="nearest")
tests = [
# From Wikipedia
| See discussion in #17176
- [ ] closes #xxxx
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/17486 | 2017-09-09T23:08:04Z | 2017-09-10T14:19:53Z | 2017-09-10T14:19:53Z | 2017-10-30T16:24:59Z |
REGR: Categorical with np.str_ categories | diff --git a/doc/source/whatsnew/v1.0.1.rst b/doc/source/whatsnew/v1.0.1.rst
index 180411afb117d..4259393f682e5 100644
--- a/doc/source/whatsnew/v1.0.1.rst
+++ b/doc/source/whatsnew/v1.0.1.rst
@@ -21,6 +21,7 @@ Fixed regressions
- Fixed regression in :meth:`GroupBy.apply` if called with a function which returned a non-pandas non-scalar object (e.g. a list or numpy array) (:issue:`31441`)
- Fixed regression in :meth:`to_datetime` when parsing non-nanosecond resolution datetimes (:issue:`31491`)
- Fixed regression in :meth:`~DataFrame.to_csv` where specifying an ``na_rep`` might truncate the values written (:issue:`31447`)
+- Fixed regression in :class:`Categorical` construction with ``numpy.str_`` categories (:issue:`31499`)
- Fixed regression where setting :attr:`pd.options.display.max_colwidth` was not accepting negative integer. In addition, this behavior has been deprecated in favor of using ``None`` (:issue:`31532`)
- Fixed regression in objTOJSON.c fix return-type warning (:issue:`31463`)
- Fixed regression in :meth:`qcut` when passed a nullable integer. (:issue:`31389`)
diff --git a/pandas/_libs/hashtable_class_helper.pxi.in b/pandas/_libs/hashtable_class_helper.pxi.in
index 7d57c67e70b58..6671375f628e7 100644
--- a/pandas/_libs/hashtable_class_helper.pxi.in
+++ b/pandas/_libs/hashtable_class_helper.pxi.in
@@ -670,7 +670,9 @@ cdef class StringHashTable(HashTable):
val = values[i]
if isinstance(val, str):
- v = get_c_string(val)
+ # GH#31499 if we have a np.str_ get_c_string wont recognize
+ # it as a str, even though isinstance does.
+ v = get_c_string(<str>val)
else:
v = get_c_string(self.na_string_sentinel)
vecs[i] = v
@@ -703,7 +705,9 @@ cdef class StringHashTable(HashTable):
val = values[i]
if isinstance(val, str):
- v = get_c_string(val)
+ # GH#31499 if we have a np.str_ get_c_string wont recognize
+ # it as a str, even though isinstance does.
+ v = get_c_string(<str>val)
else:
v = get_c_string(self.na_string_sentinel)
vecs[i] = v
diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py
index cfba3da354d44..70e1421c8dcf4 100644
--- a/pandas/tests/arrays/categorical/test_constructors.py
+++ b/pandas/tests/arrays/categorical/test_constructors.py
@@ -408,6 +408,11 @@ def test_constructor_str_unknown(self):
with pytest.raises(ValueError, match="Unknown dtype"):
Categorical([1, 2], dtype="foo")
+ def test_constructor_np_strs(self):
+ # GH#31499 Hastable.map_locations needs to work on np.str_ objects
+ cat = pd.Categorical(["1", "0", "1"], [np.str_("0"), np.str_("1")])
+ assert all(isinstance(x, np.str_) for x in cat.categories)
+
def test_constructor_from_categorical_with_dtype(self):
dtype = CategoricalDtype(["a", "b", "c"], ordered=True)
values = Categorical(["a", "b", "d"])
| - [x] closes #31499
- [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/31528 | 2020-02-01T03:40:31Z | 2020-02-04T16:24:00Z | 2020-02-04T16:23:59Z | 2020-02-04T16:31:28Z |
CLN: libperiod | diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx
index 3dd560ece188d..7fca624099b38 100644
--- a/pandas/_libs/tslibs/period.pyx
+++ b/pandas/_libs/tslibs/period.pyx
@@ -473,9 +473,6 @@ cdef int DtoQ_yq(int64_t ordinal, asfreq_info *af_info, int *year) nogil:
int quarter
pandas_datetime_to_datetimestruct(ordinal, NPY_FR_D, &dts)
- # TODO: Another version of this function used
- # date_info_from_days_and_time(&dts, unix_date, 0)
- # instead of pandas_datetime_to_datetimestruct; is one more performant?
if af_info.to_end != 12:
dts.month -= af_info.to_end
if dts.month <= 0:
@@ -516,7 +513,7 @@ cdef int64_t asfreq_DTtoW(int64_t ordinal, asfreq_info *af_info) nogil:
# Conversion _from_ BusinessDay Freq
cdef int64_t asfreq_BtoDT(int64_t ordinal, asfreq_info *af_info) nogil:
- ordinal = ((ordinal + 3) // 5) * 7 + (ordinal + 3) % 5 -3
+ ordinal = ((ordinal + 3) // 5) * 7 + (ordinal + 3) % 5 - 3
return upsample_daytime(ordinal, af_info)
@@ -753,14 +750,7 @@ cdef int64_t get_period_ordinal(npy_datetimestruct *dts, int freq) nogil:
if fmonth == 0:
fmonth = 12
- mdiff = dts.month - fmonth
- # TODO: Aren't the next two conditions equivalent to
- # unconditional incrementing?
- if mdiff < 0:
- mdiff += 12
- if dts.month >= fmonth:
- mdiff += 12
-
+ mdiff = dts.month - fmonth + 12
return (dts.year - 1970) * 4 + (mdiff - 1) // 3
elif freq == FR_MTH:
@@ -804,17 +794,16 @@ cdef int64_t get_period_ordinal(npy_datetimestruct *dts, int freq) nogil:
delta = (unix_date + 3) % 7 + 1
# return the number of business days in full weeks plus the business
# days in the last - possible partial - week
- if delta <= 5:
- return (5 * weeks) + delta - 4
- else:
- return (5 * weeks) + (5 + 1) - 4
+ if delta > 6:
+ # We have a Sunday, which rolls back to the previous Friday,
+ # just like Saturday, so decrement delta by 1 to treat as saturday
+ delta = 6
+ return (5 * weeks) + delta - 4
elif freq_group == FR_WK:
day_adj = freq - FR_WK
return (unix_date + 3 - day_adj) // 7 + 1
- # raise ValueError
-
cdef void get_date_info(int64_t ordinal, int freq,
npy_datetimestruct *dts) nogil:
@@ -983,7 +972,7 @@ cdef inline int month_to_quarter(int month) nogil:
@cython.wraparound(False)
@cython.boundscheck(False)
-def dt64arr_to_periodarr(int64_t[:] dtarr, int freq, tz=None):
+def dt64arr_to_periodarr(const int64_t[:] dtarr, int freq, tz=None):
"""
Convert array of datetime64 values (passed in as 'i8' dtype) to a set of
periods corresponding to desired frequency, per period convention.
@@ -1383,7 +1372,7 @@ cdef int pdays_in_month(int64_t ordinal, int freq):
@cython.wraparound(False)
@cython.boundscheck(False)
-def get_period_field_arr(int code, int64_t[:] arr, int freq):
+def get_period_field_arr(int code, const int64_t[:] arr, int freq):
cdef:
Py_ssize_t i, sz
int64_t[:] out
@@ -1496,7 +1485,7 @@ def extract_freq(ndarray[object] values):
@cython.wraparound(False)
@cython.boundscheck(False)
-cdef int64_t[:] localize_dt64arr_to_period(int64_t[:] stamps,
+cdef int64_t[:] localize_dt64arr_to_period(const int64_t[:] stamps,
int freq, object tz):
cdef:
Py_ssize_t n = len(stamps)
@@ -1584,7 +1573,7 @@ cdef class _Period:
return freq
@classmethod
- def _from_ordinal(cls, ordinal, freq):
+ def _from_ordinal(cls, ordinal: int, freq) -> "Period":
"""
Fast creation from an ordinal and freq that are already validated!
"""
@@ -1704,7 +1693,7 @@ cdef class _Period:
else:
return NotImplemented
- def asfreq(self, freq, how='E'):
+ def asfreq(self, freq, how='E') -> "Period":
"""
Convert Period to desired frequency, at the start or end of the interval.
@@ -1735,7 +1724,7 @@ cdef class _Period:
return Period(ordinal=ordinal, freq=freq)
@property
- def start_time(self):
+ def start_time(self) -> Timestamp:
"""
Get the Timestamp for the start of the period.
@@ -1765,13 +1754,13 @@ cdef class _Period:
return self.to_timestamp(how='S')
@property
- def end_time(self):
+ def end_time(self) -> Timestamp:
# freq.n can't be negative or 0
# ordinal = (self + self.freq.n).start_time.value - 1
ordinal = (self + self.freq).start_time.value - 1
return Timestamp(ordinal)
- def to_timestamp(self, freq=None, how='start', tz=None):
+ def to_timestamp(self, freq=None, how='start', tz=None) -> Timestamp:
"""
Return the Timestamp representation of the Period.
@@ -1811,17 +1800,17 @@ cdef class _Period:
return Timestamp(dt64, tz=tz)
@property
- def year(self):
+ def year(self) -> int:
base, mult = get_freq_code(self.freq)
return pyear(self.ordinal, base)
@property
- def month(self):
+ def month(self) -> int:
base, mult = get_freq_code(self.freq)
return pmonth(self.ordinal, base)
@property
- def day(self):
+ def day(self) -> int:
"""
Get day of the month that a Period falls on.
@@ -1844,7 +1833,7 @@ cdef class _Period:
return pday(self.ordinal, base)
@property
- def hour(self):
+ def hour(self) -> int:
"""
Get the hour of the day component of the Period.
@@ -1874,7 +1863,7 @@ cdef class _Period:
return phour(self.ordinal, base)
@property
- def minute(self):
+ def minute(self) -> int:
"""
Get minute of the hour component of the Period.
@@ -1898,7 +1887,7 @@ cdef class _Period:
return pminute(self.ordinal, base)
@property
- def second(self):
+ def second(self) -> int:
"""
Get the second component of the Period.
@@ -1922,12 +1911,12 @@ cdef class _Period:
return psecond(self.ordinal, base)
@property
- def weekofyear(self):
+ def weekofyear(self) -> int:
base, mult = get_freq_code(self.freq)
return pweek(self.ordinal, base)
@property
- def week(self):
+ def week(self) -> int:
"""
Get the week of the year on the given Period.
@@ -1957,7 +1946,7 @@ cdef class _Period:
return self.weekofyear
@property
- def dayofweek(self):
+ def dayofweek(self) -> int:
"""
Day of the week the period lies in, with Monday=0 and Sunday=6.
@@ -2008,7 +1997,7 @@ cdef class _Period:
return pweekday(self.ordinal, base)
@property
- def weekday(self):
+ def weekday(self) -> int:
"""
Day of the week the period lies in, with Monday=0 and Sunday=6.
@@ -2061,7 +2050,7 @@ cdef class _Period:
return self.dayofweek
@property
- def dayofyear(self):
+ def dayofyear(self) -> int:
"""
Return the day of the year.
@@ -2096,12 +2085,12 @@ cdef class _Period:
return pday_of_year(self.ordinal, base)
@property
- def quarter(self):
+ def quarter(self) -> int:
base, mult = get_freq_code(self.freq)
return pquarter(self.ordinal, base)
@property
- def qyear(self):
+ def qyear(self) -> int:
"""
Fiscal year the Period lies in according to its starting-quarter.
@@ -2145,7 +2134,7 @@ cdef class _Period:
return pqyear(self.ordinal, base)
@property
- def days_in_month(self):
+ def days_in_month(self) -> int:
"""
Get the total number of days in the month that this period falls on.
@@ -2179,7 +2168,7 @@ cdef class _Period:
return pdays_in_month(self.ordinal, base)
@property
- def daysinmonth(self):
+ def daysinmonth(self) -> int:
"""
Get the total number of days of the month that the Period falls in.
@@ -2209,7 +2198,7 @@ cdef class _Period:
return Period(datetime.now(), freq=freq)
@property
- def freqstr(self):
+ def freqstr(self) -> str:
return self.freq.freqstr
def __repr__(self) -> str:
diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py
index bbc81e0dbb6e6..995d47c1473be 100644
--- a/pandas/tests/scalar/period/test_period.py
+++ b/pandas/tests/scalar/period/test_period.py
@@ -925,7 +925,7 @@ def test_properties_secondly(self):
class TestPeriodField:
def test_get_period_field_array_raises_on_out_of_range(self):
- msg = "Buffer dtype mismatch, expected 'int64_t' but got 'double'"
+ msg = "Buffer dtype mismatch, expected 'const int64_t' but got 'double'"
with pytest.raises(ValueError, match=msg):
libperiod.get_period_field_arr(-1, np.empty(1), 0)
| separating cleanups from non-cleanup branches | https://api.github.com/repos/pandas-dev/pandas/pulls/31527 | 2020-02-01T03:04:35Z | 2020-02-01T23:23:06Z | 2020-02-01T23:23:06Z | 2020-02-01T23:34:49Z |
Unpin openpyxl | diff --git a/ci/deps/travis-36-cov.yaml b/ci/deps/travis-36-cov.yaml
index 869d2ab683f0c..6883301a63a9b 100644
--- a/ci/deps/travis-36-cov.yaml
+++ b/ci/deps/travis-36-cov.yaml
@@ -27,8 +27,7 @@ dependencies:
- numexpr
- numpy=1.15.*
- odfpy
- - openpyxl<=3.0.1
- # https://github.com/pandas-dev/pandas/pull/30009 openpyxl 3.0.2 broke
+ - openpyxl
- pandas-gbq
- psycopg2
- pyarrow>=0.13.0
| I *think* we pinned this originally because of issues with 3.0.2 specifically, but looks like a newer version is available on conda
ref #30009 | https://api.github.com/repos/pandas-dev/pandas/pulls/31525 | 2020-01-31T23:59:19Z | 2020-02-02T19:32:23Z | 2020-02-02T19:32:23Z | 2020-04-07T14:43:02Z |
BUG: non-iterable value in meta raise error in json_normalize | diff --git a/doc/source/whatsnew/v1.0.2.rst b/doc/source/whatsnew/v1.0.2.rst
index 462f243f14494..61d730f7a285b 100644
--- a/doc/source/whatsnew/v1.0.2.rst
+++ b/doc/source/whatsnew/v1.0.2.rst
@@ -75,6 +75,7 @@ Bug fixes
**I/O**
- Using ``pd.NA`` with :meth:`DataFrame.to_json` now correctly outputs a null value instead of an empty object (:issue:`31615`)
+- Bug in :meth:`pandas.json_normalize` when value in meta path is not iterable (:issue:`31507`)
- Fixed pickling of ``pandas.NA``. Previously a new object was returned, which broke computations relying on ``NA`` being a singleton (:issue:`31847`)
- Fixed bug in parquet roundtrip with nullable unsigned integer dtypes (:issue:`31896`).
diff --git a/pandas/io/json/_normalize.py b/pandas/io/json/_normalize.py
index 4b153d3cb69bf..6e68c1cf5e27e 100644
--- a/pandas/io/json/_normalize.py
+++ b/pandas/io/json/_normalize.py
@@ -8,6 +8,7 @@
import numpy as np
from pandas._libs.writers import convert_json_to_lines
+from pandas._typing import Scalar
from pandas.util._decorators import deprecate
import pandas as pd
@@ -226,14 +227,28 @@ def _json_normalize(
Returns normalized data with columns prefixed with the given string.
"""
- def _pull_field(js: Dict[str, Any], spec: Union[List, str]) -> Iterable:
+ def _pull_field(
+ js: Dict[str, Any], spec: Union[List, str]
+ ) -> Union[Scalar, Iterable]:
+ """Internal function to pull field"""
result = js # type: ignore
if isinstance(spec, list):
for field in spec:
result = result[field]
else:
result = result[spec]
+ return result
+
+ def _pull_records(js: Dict[str, Any], spec: Union[List, str]) -> Iterable:
+ """
+ Interal function to pull field for records, and similar to
+ _pull_field, but require to return Iterable. And will raise error
+ if has non iterable value.
+ """
+ result = _pull_field(js, spec)
+ # GH 31507 GH 30145, if result is not Iterable, raise TypeError if not
+ # null, otherwise return an empty list
if not isinstance(result, Iterable):
if pd.isnull(result):
result = [] # type: ignore
@@ -242,7 +257,6 @@ def _pull_field(js: Dict[str, Any], spec: Union[List, str]) -> Iterable:
f"{js} has non iterable value {result} for path {spec}. "
"Must be iterable or null."
)
-
return result
if isinstance(data, list) and not data:
@@ -292,7 +306,7 @@ def _recursive_extract(data, path, seen_meta, level=0):
_recursive_extract(obj[path[0]], path[1:], seen_meta, level=level + 1)
else:
for obj in data:
- recs = _pull_field(obj, path[0])
+ recs = _pull_records(obj, path[0])
recs = [
nested_to_record(r, sep=sep, max_level=max_level)
if isinstance(r, dict)
diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py
index 91b204ed41ebc..b7a9918ff46da 100644
--- a/pandas/tests/io/json/test_normalize.py
+++ b/pandas/tests/io/json/test_normalize.py
@@ -486,6 +486,16 @@ def test_non_interable_record_path_errors(self):
with pytest.raises(TypeError, match=msg):
json_normalize([test_input], record_path=[test_path])
+ def test_meta_non_iterable(self):
+ # GH 31507
+ data = """[{"id": 99, "data": [{"one": 1, "two": 2}]}]"""
+
+ result = json_normalize(json.loads(data), record_path=["data"], meta=["id"])
+ expected = DataFrame(
+ {"one": [1], "two": [2], "id": np.array([99], dtype=object)}
+ )
+ tm.assert_frame_equal(result, expected)
+
class TestNestedToRecord:
def test_flat_stays_flat(self):
| - [x] closes #31507
- [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/31524 | 2020-01-31T23:14:26Z | 2020-03-11T15:02:32Z | 2020-03-11T15:02:32Z | 2020-03-11T15:02:43Z |
REGR: Fixed slicing DatetimeIndex with date | diff --git a/doc/source/whatsnew/v1.0.1.rst b/doc/source/whatsnew/v1.0.1.rst
index 206be97fe202f..e300574e87341 100644
--- a/doc/source/whatsnew/v1.0.1.rst
+++ b/doc/source/whatsnew/v1.0.1.rst
@@ -67,6 +67,8 @@ Interval
Indexing
^^^^^^^^
+
+- Fixed regression when indexing a ``Series`` or ``DataFrame`` indexed by ``DatetimeIndex`` with a slice containg a :class:`datetime.date` (:issue:`31501`)
- Fixed regression in :class:`DataFrame` setting values with a slice (e.g. ``df[-4:] = 1``) indexing by label instead of position (:issue:`31469`)
-
-
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index 2b4636155111f..416c3d0701a85 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -1,4 +1,4 @@
-from datetime import datetime, time, timedelta, tzinfo
+from datetime import date, datetime, time, timedelta, tzinfo
import operator
from typing import Optional
import warnings
@@ -758,6 +758,13 @@ def slice_indexer(self, start=None, end=None, step=None, kind=None):
if isinstance(start, time) or isinstance(end, time):
raise KeyError("Cannot mix time and non-time slice keys")
+ # Pandas supports slicing with dates, treated as datetimes at midnight.
+ # https://github.com/pandas-dev/pandas/issues/31501
+ if isinstance(start, date) and not isinstance(start, datetime):
+ start = datetime.combine(start, time(0, 0))
+ if isinstance(end, date) and not isinstance(end, datetime):
+ end = datetime.combine(end, time(0, 0))
+
try:
return Index.slice_indexer(self, start, end, step, kind=kind)
except KeyError:
diff --git a/pandas/tests/indexing/test_datetime.py b/pandas/tests/indexing/test_datetime.py
index 42f992339f036..c8c2d1ed587cf 100644
--- a/pandas/tests/indexing/test_datetime.py
+++ b/pandas/tests/indexing/test_datetime.py
@@ -1,4 +1,4 @@
-from datetime import datetime, timedelta
+from datetime import date, datetime, timedelta
from dateutil import tz
import numpy as np
@@ -350,3 +350,23 @@ def test_loc_label_slicing(self):
expected = ser.iloc[:-1]
tm.assert_series_equal(result, expected)
+
+ @pytest.mark.parametrize(
+ "slice_, positions",
+ [
+ [slice(date(2018, 1, 1), None), [0, 1, 2]],
+ [slice(date(2019, 1, 2), None), [2]],
+ [slice(date(2020, 1, 1), None), []],
+ [slice(None, date(2020, 1, 1)), [0, 1, 2]],
+ [slice(None, date(2019, 1, 1)), [0]],
+ ],
+ )
+ def test_getitem_slice_date(self, slice_, positions):
+ # https://github.com/pandas-dev/pandas/issues/31501
+ s = pd.Series(
+ [0, 1, 2],
+ pd.DatetimeIndex(["2019-01-01", "2019-01-01T06:00:00", "2019-01-02"]),
+ )
+ result = s[slice_]
+ expected = s.take(positions)
+ tm.assert_series_equal(result, expected)
| Closes https://github.com/pandas-dev/pandas/issues/31501 | https://api.github.com/repos/pandas-dev/pandas/pulls/31521 | 2020-01-31T22:10:44Z | 2020-02-01T14:56:13Z | 2020-02-01T14:56:13Z | 2020-02-03T16:49:38Z |
REGR: to_datetime, unique with OOB values | diff --git a/doc/source/whatsnew/v1.0.1.rst b/doc/source/whatsnew/v1.0.1.rst
index ff8433c7cafd9..95fab6a18ffe1 100644
--- a/doc/source/whatsnew/v1.0.1.rst
+++ b/doc/source/whatsnew/v1.0.1.rst
@@ -25,8 +25,8 @@ Categorical
Datetimelike
^^^^^^^^^^^^
--
--
+- Fixed regression in :meth:`to_datetime` when parsing non-nanosecond resolution datetimes (:issue:`31491`)
+- Fixed bug in :meth:`to_datetime` raising when ``cache=True`` and out-of-bound values are present (:issue:`31491`)
Timedelta
^^^^^^^^^
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 8af9e2cc9790f..886b0a3c5fec1 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -29,6 +29,7 @@
is_categorical_dtype,
is_complex_dtype,
is_datetime64_any_dtype,
+ is_datetime64_dtype,
is_datetime64_ns_dtype,
is_extension_array_dtype,
is_float_dtype,
@@ -191,6 +192,11 @@ def _reconstruct_data(values, dtype, original):
if isinstance(original, ABCIndexClass):
values = values.astype(object, copy=False)
elif dtype is not None:
+ if is_datetime64_dtype(dtype):
+ dtype = "datetime64[ns]"
+ elif is_timedelta64_dtype(dtype):
+ dtype = "timedelta64[ns]"
+
values = values.astype(dtype, copy=False)
return values
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py
index 0cf0f943ae442..6d45ddd29d783 100644
--- a/pandas/core/tools/datetimes.py
+++ b/pandas/core/tools/datetimes.py
@@ -602,7 +602,9 @@ def to_datetime(
cache : bool, default True
If True, use a cache of unique, converted dates to apply the datetime
conversion. May produce significant speed-up when parsing duplicate
- date strings, especially ones with timezone offsets.
+ date strings, especially ones with timezone offsets. The cache is only
+ used when there are at least 50 values. The presence of out-of-bounds
+ values will render the cache unusable and may slow down parsing.
.. versionadded:: 0.23.0
@@ -734,7 +736,17 @@ def to_datetime(
convert_listlike = partial(convert_listlike, name=arg.name)
result = convert_listlike(arg, format)
elif is_list_like(arg):
- cache_array = _maybe_cache(arg, format, cache, convert_listlike)
+ try:
+ cache_array = _maybe_cache(arg, format, cache, convert_listlike)
+ except tslibs.OutOfBoundsDatetime:
+ # caching attempts to create a DatetimeIndex, which may raise
+ # an OOB. If that's the desired behavior, then just reraise...
+ if errors == "raise":
+ raise
+ # ... otherwise, continue without the cache.
+ from pandas import Series
+
+ cache_array = Series([], dtype=object) # just an empty array
if not cache_array.empty:
result = _convert_and_box_cache(arg, cache_array)
else:
diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py
index 7abf810e6bcfc..df3a49fb7c292 100644
--- a/pandas/tests/indexes/datetimes/test_tools.py
+++ b/pandas/tests/indexes/datetimes/test_tools.py
@@ -559,9 +559,14 @@ def test_to_datetime_dt64s_out_of_bounds(self, cache, dt):
assert pd.to_datetime(dt, errors="coerce", cache=cache) is NaT
@pytest.mark.parametrize("cache", [True, False])
- def test_to_datetime_array_of_dt64s(self, cache):
- dts = [np.datetime64("2000-01-01"), np.datetime64("2000-01-02")]
-
+ @pytest.mark.parametrize("unit", ["s", "D"])
+ def test_to_datetime_array_of_dt64s(self, cache, unit):
+ # https://github.com/pandas-dev/pandas/issues/31491
+ # Need at least 50 to ensure cache is used.
+ dts = [
+ np.datetime64("2000-01-01", unit),
+ np.datetime64("2000-01-02", unit),
+ ] * 30
# Assuming all datetimes are in bounds, to_datetime() returns
# an array that is equal to Timestamp() parsing
tm.assert_index_equal(
@@ -579,11 +584,8 @@ def test_to_datetime_array_of_dt64s(self, cache):
tm.assert_index_equal(
pd.to_datetime(dts_with_oob, errors="coerce", cache=cache),
pd.DatetimeIndex(
- [
- Timestamp(dts_with_oob[0]).asm8,
- Timestamp(dts_with_oob[1]).asm8,
- pd.NaT,
- ]
+ [Timestamp(dts_with_oob[0]).asm8, Timestamp(dts_with_oob[1]).asm8] * 30
+ + [pd.NaT],
),
)
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index 6c7f8c9b0475e..a1de9c435c9ba 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -420,6 +420,18 @@ def test_datetime64_dtype_array_returned(self):
tm.assert_numpy_array_equal(result, expected)
assert result.dtype == expected.dtype
+ def test_datetime_non_ns(self):
+ a = np.array(["2000", "2000", "2001"], dtype="datetime64[s]")
+ result = pd.unique(a)
+ expected = np.array(["2000", "2001"], dtype="datetime64[ns]")
+ tm.assert_numpy_array_equal(result, expected)
+
+ def test_timedelta_non_ns(self):
+ a = np.array(["2000", "2000", "2001"], dtype="timedelta64[s]")
+ result = pd.unique(a)
+ expected = np.array([2000000000000, 2001000000000], dtype="timedelta64[ns]")
+ tm.assert_numpy_array_equal(result, expected)
+
def test_timedelta64_dtype_array_returned(self):
# GH 9431
expected = np.array([31200, 45678, 10000], dtype="m8[ns]")
| Closes https://github.com/pandas-dev/pandas/issues/31491
This turned up two bugs:
1. `to_datetime(oob_values, cache=True, errors='coerce')` would raise. We had tests intended to catch this, but we didn't actually hit it because caching is disabled for inputs less than length 50. We only tested with length 3. I've updated the test to pass that threshold
2. The original report, that `to_datetime` was raising for non-ns resolution values that aren't OOB for ns resolution. This was a bug in `unique`. | https://api.github.com/repos/pandas-dev/pandas/pulls/31520 | 2020-01-31T21:45:02Z | 2020-02-01T14:29:37Z | 2020-02-01T14:29:37Z | 2020-02-01T14:29:37Z |
REF: simplify DTI._parse_string_to_bounds | diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index 46c896a724dae..837160450c18e 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -5,15 +5,8 @@
import numpy as np
-from pandas._libs import (
- NaT,
- Timedelta,
- Timestamp,
- index as libindex,
- lib,
- tslib as libts,
-)
-from pandas._libs.tslibs import ccalendar, fields, parsing, timezones
+from pandas._libs import NaT, Period, Timestamp, index as libindex, lib, tslib as libts
+from pandas._libs.tslibs import fields, parsing, timezones
from pandas.util._decorators import cache_readonly
from pandas.core.dtypes.common import _NS_DTYPE, is_float, is_integer, is_scalar
@@ -465,7 +458,7 @@ def _parsed_string_to_bounds(self, reso: str, parsed: datetime):
Parameters
----------
- reso : Resolution
+ reso : str
Resolution provided by parsed string.
parsed : datetime
Datetime from parsed string.
@@ -473,7 +466,6 @@ def _parsed_string_to_bounds(self, reso: str, parsed: datetime):
Returns
-------
lower, upper: pd.Timestamp
-
"""
valid_resos = {
"year",
@@ -489,50 +481,11 @@ def _parsed_string_to_bounds(self, reso: str, parsed: datetime):
}
if reso not in valid_resos:
raise KeyError
- if reso == "year":
- start = Timestamp(parsed.year, 1, 1)
- end = Timestamp(parsed.year + 1, 1, 1) - Timedelta(nanoseconds=1)
- elif reso == "month":
- d = ccalendar.get_days_in_month(parsed.year, parsed.month)
- start = Timestamp(parsed.year, parsed.month, 1)
- end = start + Timedelta(days=d, nanoseconds=-1)
- elif reso == "quarter":
- qe = (((parsed.month - 1) + 2) % 12) + 1 # two months ahead
- d = ccalendar.get_days_in_month(parsed.year, qe) # at end of month
- start = Timestamp(parsed.year, parsed.month, 1)
- end = Timestamp(parsed.year, qe, 1) + Timedelta(days=d, nanoseconds=-1)
- elif reso == "day":
- start = Timestamp(parsed.year, parsed.month, parsed.day)
- end = start + Timedelta(days=1, nanoseconds=-1)
- elif reso == "hour":
- start = Timestamp(parsed.year, parsed.month, parsed.day, parsed.hour)
- end = start + Timedelta(hours=1, nanoseconds=-1)
- elif reso == "minute":
- start = Timestamp(
- parsed.year, parsed.month, parsed.day, parsed.hour, parsed.minute
- )
- end = start + Timedelta(minutes=1, nanoseconds=-1)
- elif reso == "second":
- start = Timestamp(
- parsed.year,
- parsed.month,
- parsed.day,
- parsed.hour,
- parsed.minute,
- parsed.second,
- )
- end = start + Timedelta(seconds=1, nanoseconds=-1)
- elif reso == "microsecond":
- start = Timestamp(
- parsed.year,
- parsed.month,
- parsed.day,
- parsed.hour,
- parsed.minute,
- parsed.second,
- parsed.microsecond,
- )
- end = start + Timedelta(microseconds=1, nanoseconds=-1)
+
+ grp = Resolution.get_freq_group(reso)
+ per = Period(parsed, freq=(grp, 1))
+ start, end = per.start_time, per.end_time
+
# GH 24076
# If an incoming date string contained a UTC offset, need to localize
# the parsed date to this offset first before aligning with the index's
| Sits on top of #31475. i.e. once that is merged, the only diff remaining here will be in indexes.datetimes.
After this, we are within striking distance of sharing the method between DTI/PI. | https://api.github.com/repos/pandas-dev/pandas/pulls/31519 | 2020-01-31T21:09:53Z | 2020-02-05T01:46:22Z | 2020-02-05T01:46:22Z | 2020-04-05T17:34:10Z |
REGR: DataFrame.__setitem__(slice, val) is positional | diff --git a/doc/source/whatsnew/v1.0.1.rst b/doc/source/whatsnew/v1.0.1.rst
index ff8433c7cafd9..206be97fe202f 100644
--- a/doc/source/whatsnew/v1.0.1.rst
+++ b/doc/source/whatsnew/v1.0.1.rst
@@ -67,7 +67,7 @@ Interval
Indexing
^^^^^^^^
-
+- Fixed regression in :class:`DataFrame` setting values with a slice (e.g. ``df[-4:] = 1``) indexing by label instead of position (:issue:`31469`)
-
-
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 70e440b49ae6c..0dea8235e9d3f 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2937,8 +2937,11 @@ def __setitem__(self, key, value):
self._set_item(key, value)
def _setitem_slice(self, key, value):
+ # NB: we can't just use self.loc[key] = value because that
+ # operates on labels and we need to operate positional for
+ # backwards-compat, xref GH#31469
self._check_setitem_copy()
- self.loc[key] = value
+ self.loc._setitem_with_indexer(key, value)
def _setitem_array(self, key, value):
# also raises Exception if object array with NA values
diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py
index cbb9dd09bbede..64d0f9ee2b062 100644
--- a/pandas/tests/frame/indexing/test_indexing.py
+++ b/pandas/tests/frame/indexing/test_indexing.py
@@ -860,6 +860,15 @@ def test_fancy_getitem_slice_mixed(self, float_frame, float_string_frame):
assert (float_frame["C"] == 4).all()
+ def test_setitem_slice_position(self):
+ # GH#31469
+ df = pd.DataFrame(np.zeros((100, 1)))
+ df[-4:] = 1
+ arr = np.zeros((100, 1))
+ arr[-4:] = 1
+ expected = pd.DataFrame(arr)
+ tm.assert_frame_equal(df, expected)
+
def test_getitem_setitem_non_ix_labels(self):
df = tm.makeTimeDataFrame()
| - [x] closes #31469
- [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/31515 | 2020-01-31T19:36:38Z | 2020-02-01T14:22:06Z | 2020-02-01T14:22:05Z | 2020-02-05T12:34:52Z |
REGR: Fixed truncation with na_rep | diff --git a/doc/source/whatsnew/v1.0.1.rst b/doc/source/whatsnew/v1.0.1.rst
index ff8433c7cafd9..1a5a420ab8b55 100644
--- a/doc/source/whatsnew/v1.0.1.rst
+++ b/doc/source/whatsnew/v1.0.1.rst
@@ -86,6 +86,7 @@ MultiIndex
I/O
^^^
+- Fixed regression in :meth:`~DataFrame.to_csv` where specifying an ``na_rep`` might truncate the values written (:issue:`31447`)
-
-
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 22901051ec345..9e31ccebd0f1b 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -684,7 +684,10 @@ def to_native_types(self, slicer=None, na_rep="nan", quoting=None, **kwargs):
itemsize = writers.word_len(na_rep)
if not self.is_object and not quoting and itemsize:
- values = values.astype(f"<U{itemsize}")
+ values = values.astype(str)
+ if values.dtype.itemsize / np.dtype("U1").itemsize < itemsize:
+ # enlarge for the na_rep
+ values = values.astype(f"<U{itemsize}")
else:
values = np.array(values, dtype="object")
diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py
index a211ac11cf725..b3ee8da52dece 100644
--- a/pandas/tests/io/formats/test_to_csv.py
+++ b/pandas/tests/io/formats/test_to_csv.py
@@ -583,3 +583,17 @@ def test_to_csv_timedelta_precision(self):
]
expected = tm.convert_rows_list_to_csv_str(expected_rows)
assert result == expected
+
+ def test_na_rep_truncated(self):
+ # https://github.com/pandas-dev/pandas/issues/31447
+ result = pd.Series(range(8, 12)).to_csv(na_rep="-")
+ expected = tm.convert_rows_list_to_csv_str([",0", "0,8", "1,9", "2,10", "3,11"])
+ assert result == expected
+
+ result = pd.Series([True, False]).to_csv(na_rep="nan")
+ expected = tm.convert_rows_list_to_csv_str([",0", "0,True", "1,False"])
+ assert result == expected
+
+ result = pd.Series([1.1, 2.2]).to_csv(na_rep=".")
+ expected = tm.convert_rows_list_to_csv_str([",0", "0,1.1", "1,2.2"])
+ assert result == expected
| Closes https://github.com/pandas-dev/pandas/issues/31447 | https://api.github.com/repos/pandas-dev/pandas/pulls/31513 | 2020-01-31T18:31:06Z | 2020-02-01T15:21:12Z | 2020-02-01T15:21:12Z | 2020-02-01T15:21:16Z |
CLN: inherit PeriodIndex._box_func | diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index e3eeca2c45e76..66723969c9f10 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -80,7 +80,16 @@ def wrapper(left, right):
cache=True,
)
@inherit_names(
- ["__iter__", "mean", "freq", "freqstr", "_ndarray_values", "asi8", "_box_values"],
+ [
+ "__iter__",
+ "mean",
+ "freq",
+ "freqstr",
+ "_ndarray_values",
+ "asi8",
+ "_box_values",
+ "_box_func",
+ ],
DatetimeLikeArrayMixin,
)
class DatetimeIndexOpsMixin(ExtensionIndex):
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index 2b4636155111f..e3245d6e419ed 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -70,7 +70,6 @@ def _new_DatetimeIndex(cls, d):
"_field_ops",
"_datetimelike_ops",
"_datetimelike_methods",
- "_box_func",
"tz",
"tzinfo",
"dtype",
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py
index 75c100c9d2c08..ad88608dba1c9 100644
--- a/pandas/core/indexes/period.py
+++ b/pandas/core/indexes/period.py
@@ -280,22 +280,6 @@ def _shallow_copy_with_infer(self, values=None, **kwargs):
""" we always want to return a PeriodIndex """
return self._shallow_copy(values=values, **kwargs)
- @property
- def _box_func(self):
- """Maybe box an ordinal or Period"""
- # TODO(DatetimeArray): Avoid double-boxing
- # PeriodArray takes care of boxing already, so we need to check
- # whether we're given an ordinal or a Period. It seems like some
- # places outside of indexes/period.py are calling this _box_func,
- # but passing data that's already boxed.
- def func(x):
- if isinstance(x, Period) or x is NaT:
- return x
- else:
- return Period._from_ordinal(ordinal=x, freq=self.freq)
-
- return func
-
def _maybe_convert_timedelta(self, other):
"""
Convert timedelta-like input to an integer multiple of self.freq
diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py
index 08a07e8d30348..f5cf87ea700a6 100644
--- a/pandas/core/indexes/timedeltas.py
+++ b/pandas/core/indexes/timedeltas.py
@@ -53,7 +53,6 @@
"_datetimelike_methods",
"_other_ops",
"components",
- "_box_func",
"to_pytimedelta",
"sum",
"std",
| https://api.github.com/repos/pandas-dev/pandas/pulls/31512 | 2020-01-31T18:23:53Z | 2020-02-02T22:35:54Z | 2020-02-02T22:35:54Z | 2020-02-02T22:39:04Z | |
BUG: fix reindexing with a tz-aware index and method='nearest' | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index dfb5ae56cbe1f..9fdda83abe944 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -108,6 +108,7 @@ Datetimelike
- Bug in :class:`Timestamp` where constructing :class:`Timestamp` from ambiguous epoch time and calling constructor again changed :meth:`Timestamp.value` property (:issue:`24329`)
- :meth:`DatetimeArray.searchsorted`, :meth:`TimedeltaArray.searchsorted`, :meth:`PeriodArray.searchsorted` not recognizing non-pandas scalars and incorrectly raising ``ValueError`` instead of ``TypeError`` (:issue:`30950`)
- Bug in :class:`Timestamp` where constructing :class:`Timestamp` with dateutil timezone less than 128 nanoseconds before daylight saving time switch from winter to summer would result in nonexistent time (:issue:`31043`)
+- Bug in :meth:`DataFrame.reindex` and :meth:`Series.reindex` when reindexing with a tz-aware index (:issue:`26683`)
Timedelta
^^^^^^^^^
@@ -154,7 +155,6 @@ Indexing
- Bug in :meth:`Series.at` and :meth:`DataFrame.at` not matching ``.loc`` behavior when looking up an integer in a :class:`Float64Index` (:issue:`31329`)
- Bug in :meth:`PeriodIndex.is_monotonic` incorrectly returning ``True`` when containing leading ``NaT`` entries (:issue:`31437`)
- Bug in :meth:`DatetimeIndex.get_loc` raising ``KeyError`` with converted-integer key instead of the user-passed key (:issue:`31425`)
--
Missing
^^^^^^^
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index d8b6457464ed3..6a7551391f2a8 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -3073,9 +3073,8 @@ def _get_nearest_indexer(self, target: "Index", limit, tolerance) -> np.ndarray:
left_indexer = self.get_indexer(target, "pad", limit=limit)
right_indexer = self.get_indexer(target, "backfill", limit=limit)
- target = np.asarray(target)
- left_distances = abs(self.values[left_indexer] - target)
- right_distances = abs(self.values[right_indexer] - target)
+ left_distances = np.abs(self[left_indexer] - target)
+ right_distances = np.abs(self[right_indexer] - target)
op = operator.lt if self.is_monotonic_increasing else operator.le
indexer = np.where(
diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py
index 2e86acf4f789a..9a01ee18928c0 100644
--- a/pandas/tests/frame/indexing/test_indexing.py
+++ b/pandas/tests/frame/indexing/test_indexing.py
@@ -1602,6 +1602,16 @@ def test_reindex_methods_nearest_special(self):
actual = df.reindex(target, method="nearest", tolerance=[0.5, 0.01, 0.4, 0.1])
tm.assert_frame_equal(expected, actual)
+ def test_reindex_nearest_tz(self, tz_aware_fixture):
+ # GH26683
+ tz = tz_aware_fixture
+ idx = pd.date_range("2019-01-01", periods=5, tz=tz)
+ df = pd.DataFrame({"x": list(range(5))}, index=idx)
+
+ expected = df.head(3)
+ actual = df.reindex(idx[:3], method="nearest")
+ tm.assert_frame_equal(expected, actual)
+
def test_reindex_frame_add_nat(self):
rng = date_range("1/1/2000 00:00:00", periods=10, freq="10s")
df = DataFrame({"A": np.random.randn(len(rng)), "B": rng})
| - [x] closes #26683
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
First pandas PR, happy to make changes as needed. Is a whatsnew entry needed? And if so, I assume it should go in v1.0.1.rst? | https://api.github.com/repos/pandas-dev/pandas/pulls/31511 | 2020-01-31T18:23:51Z | 2020-02-03T03:48:29Z | 2020-02-03T03:48:28Z | 2023-03-10T21:23:01Z |
CLN: remove IndexEngine.set_value | diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx
index 1915eaf6e07dd..b39afc57f34f6 100644
--- a/pandas/_libs/index.pyx
+++ b/pandas/_libs/index.pyx
@@ -87,20 +87,6 @@ cdef class IndexEngine:
else:
return get_value_at(arr, loc, tz=tz)
- cpdef set_value(self, ndarray arr, object key, object value):
- """
- Parameters
- ----------
- arr : 1-dimensional ndarray
- """
- cdef:
- object loc
-
- loc = self.get_loc(key)
- value = convert_scalar(arr, value)
-
- arr[loc] = value
-
cpdef get_loc(self, object val):
cdef:
Py_ssize_t loc
@@ -585,16 +571,23 @@ cpdef convert_scalar(ndarray arr, object value):
raise ValueError("cannot set a Timedelta with a non-timedelta "
f"{type(value).__name__}")
- if (issubclass(arr.dtype.type, (np.integer, np.floating, np.complex)) and
- not issubclass(arr.dtype.type, np.bool_)):
- if util.is_bool_object(value):
- raise ValueError("Cannot assign bool to float/integer series")
+ else:
+ validate_numeric_casting(arr.dtype, value)
+
+ return value
+
- if issubclass(arr.dtype.type, (np.integer, np.bool_)):
+cpdef validate_numeric_casting(dtype, object value):
+ # Note: we can't annotate dtype as cnp.dtype because that cases dtype.type
+ # to integer
+ if issubclass(dtype.type, (np.integer, np.bool_)):
if util.is_float_object(value) and value != value:
raise ValueError("Cannot assign nan to integer series")
- return value
+ if (issubclass(dtype.type, (np.integer, np.floating, np.complex)) and
+ not issubclass(dtype.type, np.bool_)):
+ if util.is_bool_object(value):
+ raise ValueError("Cannot assign bool to float/integer series")
cdef class BaseMultiIndexCodesEngine:
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 0dea8235e9d3f..7ea4ece76201d 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -40,7 +40,7 @@
from pandas._config import get_option
-from pandas._libs import algos as libalgos, lib, properties
+from pandas._libs import algos as libalgos, index as libindex, lib, properties
from pandas._typing import Axes, Axis, Dtype, FilePathOrBuffer, Label, Level, Renamer
from pandas.compat import PY37
from pandas.compat._optional import import_optional_dependency
@@ -3028,10 +3028,14 @@ def _set_value(self, index, col, value, takeable: bool = False):
series = self._get_item_cache(col)
engine = self.index._engine
- engine.set_value(series._values, index, value)
+ loc = engine.get_loc(index)
+ libindex.validate_numeric_casting(series.dtype, value)
+
+ series._values[loc] = value
+ # Note: trying to use series._set_value breaks tests in
+ # tests.frame.indexing.test_indexing and tests.indexing.test_partial
return self
except (KeyError, TypeError):
-
# set using a non-recursive method & reset the cache
if takeable:
self.iloc[index, col] = value
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 5e6018d85bd2d..5cac95c6702e1 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -4650,9 +4650,9 @@ def set_value(self, arr, key, value):
FutureWarning,
stacklevel=2,
)
- self._engine.set_value(
- com.values_from_object(arr), com.values_from_object(key), value
- )
+ loc = self._engine.get_loc(key)
+ libindex.validate_numeric_casting(arr.dtype, value)
+ arr[loc] = value
_index_shared_docs[
"get_indexer_non_unique"
diff --git a/pandas/core/series.py b/pandas/core/series.py
index e5cea8ebfc914..8ad0fe8f705b1 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1026,17 +1026,10 @@ def __setitem__(self, key, value):
self._maybe_update_cacher()
def _set_with_engine(self, key, value):
- values = self._values
- if is_extension_array_dtype(values.dtype):
- # The cython indexing engine does not support ExtensionArrays.
- values[self.index.get_loc(key)] = value
- return
- try:
- self.index._engine.set_value(values, key, value)
- return
- except KeyError:
- values[self.index.get_loc(key)] = value
- return
+ # fails with AttributeError for IntervalIndex
+ loc = self.index._engine.get_loc(key)
+ libindex.validate_numeric_casting(self.dtype, value)
+ self._values[loc] = value
def _set_with(self, key, value):
# other: fancy integer or otherwise
@@ -1116,11 +1109,10 @@ def _set_value(self, label, value, takeable: bool = False):
try:
if takeable:
self._values[label] = value
- elif isinstance(self._values, np.ndarray):
- # i.e. not EA, so we can use _engine
- self.index._engine.set_value(self._values, label, value)
else:
- self.loc[label] = value
+ loc = self.index.get_loc(label)
+ libindex.validate_numeric_casting(self.dtype, value)
+ self._values[loc] = value
except KeyError:
# set using a non-recursive method
diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py
index 1913caae93932..ae32274c02dcd 100644
--- a/pandas/tests/indexing/test_indexing.py
+++ b/pandas/tests/indexing/test_indexing.py
@@ -137,7 +137,7 @@ def test_setitem_ndarray_3d(self, index, obj, idxr, idxr_id):
r"Buffer has wrong number of dimensions \(expected 1, "
r"got 3\)|"
"'pandas._libs.interval.IntervalTree' object has no attribute "
- "'set_value'|" # AttributeError
+ "'get_loc'|" # AttributeError
"unhashable type: 'numpy.ndarray'|" # TypeError
"No matching signature found|" # TypeError
r"^\[\[\[|" # pandas.core.indexing.IndexingError
| made possible bc Series._values now returns DTA/TDA for datetime64/timedelta64
Small perf improvement
```
In [3]: dti = pd.date_range('2016-01-01', freq='D', periods=10**4)
In [4]: idx = list('abcdefghijklmnop')
In [5]: arr = np.random.random(len(idx)*len(dti)).reshape(len(dti), -1)
In [6]: df = pd.DataFrame(arr, index=dti, columns=idx)
In [7]: %timeit df2 = df._set_value("2043-05-14", "c", 4)
381 µs ± 14.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) # <-- master
330 µs ± 13 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) # <-- PR
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/31510 | 2020-01-31T18:11:52Z | 2020-02-02T22:42:11Z | 2020-02-02T22:42:11Z | 2020-02-02T23:24:41Z |
Dead JSON Code Cleanup | diff --git a/pandas/_libs/src/ujson/python/objToJSON.c b/pandas/_libs/src/ujson/python/objToJSON.c
index 62c2870c198c4..d04e873fff7bd 100644
--- a/pandas/_libs/src/ujson/python/objToJSON.c
+++ b/pandas/_libs/src/ujson/python/objToJSON.c
@@ -127,7 +127,6 @@ typedef struct __PyObjectEncoder {
// pass-through to encode numpy data directly
int npyType;
void *npyValue;
- TypeContext basicTypeContext;
int datetimeIso;
NPY_DATETIMEUNIT datetimeUnit;
@@ -2115,10 +2114,7 @@ void Object_endTypeContext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) {
PyObject_Free(GET_TC(tc)->cStr);
GET_TC(tc)->cStr = NULL;
- if (tc->prv !=
- &(((PyObjectEncoder *)tc->encoder)->basicTypeContext)) { // NOLINT
- PyObject_Free(tc->prv);
- }
+ PyObject_Free(tc->prv);
tc->prv = NULL;
}
}
@@ -2216,16 +2212,6 @@ PyObject *objToJSON(PyObject *Py_UNUSED(self), PyObject *args,
pyEncoder.datetimeUnit = NPY_FR_ms;
pyEncoder.outputFormat = COLUMNS;
pyEncoder.defaultHandler = 0;
- pyEncoder.basicTypeContext.newObj = NULL;
- pyEncoder.basicTypeContext.dictObj = NULL;
- pyEncoder.basicTypeContext.itemValue = NULL;
- pyEncoder.basicTypeContext.itemName = NULL;
- pyEncoder.basicTypeContext.attrList = NULL;
- pyEncoder.basicTypeContext.iterator = NULL;
- pyEncoder.basicTypeContext.cStr = NULL;
- pyEncoder.basicTypeContext.npyarr = NULL;
- pyEncoder.basicTypeContext.rowLabels = NULL;
- pyEncoder.basicTypeContext.columnLabels = NULL;
PRINTMARK();
| https://api.github.com/repos/pandas-dev/pandas/pulls/31509 | 2020-01-31T17:54:25Z | 2020-02-02T22:42:56Z | 2020-02-02T22:42:56Z | 2023-04-12T20:17:37Z | |
JSON Set Name Cleanup | diff --git a/pandas/_libs/src/ujson/python/objToJSON.c b/pandas/_libs/src/ujson/python/objToJSON.c
index 62c2870c198c4..a895a46a5977d 100644
--- a/pandas/_libs/src/ujson/python/objToJSON.c
+++ b/pandas/_libs/src/ujson/python/objToJSON.c
@@ -925,15 +925,15 @@ char *Tuple_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *Py_UNUSED(tc),
}
//=============================================================================
-// Iterator iteration functions
+// Set iteration functions
// itemValue is borrowed reference, no ref counting
//=============================================================================
-void Iter_iterBegin(JSOBJ obj, JSONTypeContext *tc) {
+void Set_iterBegin(JSOBJ obj, JSONTypeContext *tc) {
GET_TC(tc)->itemValue = NULL;
GET_TC(tc)->iterator = PyObject_GetIter(obj);
}
-int Iter_iterNext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) {
+int Set_iterNext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) {
PyObject *item;
if (GET_TC(tc)->itemValue) {
@@ -951,7 +951,7 @@ int Iter_iterNext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) {
return 1;
}
-void Iter_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) {
+void Set_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) {
if (GET_TC(tc)->itemValue) {
Py_DECREF(GET_TC(tc)->itemValue);
GET_TC(tc)->itemValue = NULL;
@@ -963,11 +963,11 @@ void Iter_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) {
}
}
-JSOBJ Iter_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) {
+JSOBJ Set_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) {
return GET_TC(tc)->itemValue;
}
-char *Iter_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *Py_UNUSED(tc),
+char *Set_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *Py_UNUSED(tc),
size_t *Py_UNUSED(outLen)) {
return NULL;
}
@@ -2040,11 +2040,11 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) {
} else if (PyAnySet_Check(obj)) {
PRINTMARK();
tc->type = JT_ARRAY;
- pc->iterBegin = Iter_iterBegin;
- pc->iterEnd = Iter_iterEnd;
- pc->iterNext = Iter_iterNext;
- pc->iterGetValue = Iter_iterGetValue;
- pc->iterGetName = Iter_iterGetName;
+ pc->iterBegin = Set_iterBegin;
+ pc->iterEnd = Set_iterEnd;
+ pc->iterNext = Set_iterNext;
+ pc->iterGetValue = Set_iterGetValue;
+ pc->iterGetName = Set_iterGetName;
return;
}
| Makes this consistent with List, Tuple
| https://api.github.com/repos/pandas-dev/pandas/pulls/31508 | 2020-01-31T17:53:15Z | 2020-02-02T22:43:53Z | 2020-02-02T22:43:53Z | 2023-04-12T20:17:15Z |
CLN: No need to use libindex.get_value_at | diff --git a/pandas/core/base.py b/pandas/core/base.py
index 9fe1af776dd2b..f3c8b50e774af 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -1027,12 +1027,10 @@ def tolist(self):
--------
numpy.ndarray.tolist
"""
- if self.dtype.kind in ["m", "M"]:
- return [com.maybe_box_datetimelike(x) for x in self._values]
- elif is_extension_array_dtype(self._values):
+ if not isinstance(self._values, np.ndarray):
+ # check for ndarray instead of dtype to catch DTA/TDA
return list(self._values)
- else:
- return self._values.tolist()
+ return self._values.tolist()
to_list = tolist
@@ -1049,9 +1047,8 @@ def __iter__(self):
iterator
"""
# We are explicitly making element iterators.
- if self.dtype.kind in ["m", "M"]:
- return map(com.maybe_box_datetimelike, self._values)
- elif is_extension_array_dtype(self._values):
+ if not isinstance(self._values, np.ndarray):
+ # Check type instead of dtype to catch DTA/TDA
return iter(self._values)
else:
return map(self._values.item, range(self._values.size))
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 70e440b49ae6c..35d84922925d4 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -2900,12 +2900,8 @@ def _get_value(self, index, col, takeable: bool = False):
engine = self.index._engine
try:
- if isinstance(series._values, np.ndarray):
- # i.e. not EA, we can use engine
- return engine.get_value(series._values, index)
- else:
- loc = series.index.get_loc(index)
- return series._values[loc]
+ loc = engine.get_loc(index)
+ return series._values[loc]
except KeyError:
# GH 20629
if self.index.nlevels > 1:
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 22ba317e78e63..d91f899d7fa42 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -4620,10 +4620,6 @@ def _get_values_for_loc(self, series, loc):
Assumes that `series.index is self`
"""
if is_integer(loc):
- if isinstance(series._values, np.ndarray):
- # Since we have an ndarray and not DatetimeArray, we dont
- # have to worry about a tz.
- return libindex.get_value_at(series._values, loc, tz=None)
return series._values[loc]
return series.iloc[loc]
diff --git a/pandas/core/series.py b/pandas/core/series.py
index e5cea8ebfc914..645322401cd2d 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -22,7 +22,7 @@
from pandas._config import get_option
-from pandas._libs import index as libindex, lib, properties, reshape, tslibs
+from pandas._libs import lib, properties, reshape, tslibs
from pandas._typing import Label
from pandas.compat.numpy import function as nv
from pandas.util._decorators import Appender, Substitution
@@ -838,13 +838,7 @@ def _ixs(self, i: int, axis: int = 0):
-------
scalar (int) or Series (slice, sequence)
"""
-
- # dispatch to the values if we need
- values = self._values
- if isinstance(values, np.ndarray):
- return libindex.get_value_at(values, i)
- else:
- return values[i]
+ return self._values[i]
def _slice(self, slobj: slice, axis: int = 0, kind=None) -> "Series":
slobj = self.index._convert_slice_indexer(slobj, kind=kind or "getitem")
@@ -981,7 +975,7 @@ def _get_value(self, label, takeable: bool = False):
scalar value
"""
if takeable:
- return com.maybe_box_datetimelike(self._values[label])
+ return self._values[label]
return self.index.get_value(self, label)
def __setitem__(self, key, value):
diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py
index 38514594efe09..fffc4a7562306 100644
--- a/pandas/tests/indexes/period/test_indexing.py
+++ b/pandas/tests/indexes/period/test_indexing.py
@@ -486,15 +486,17 @@ def test_get_value_datetime_hourly(self, freq):
assert ser.loc[ts2] == 7
def test_get_value_integer(self):
+ msg = "index 16801 is out of bounds for axis 0 with size 3"
dti = pd.date_range("2016-01-01", periods=3)
pi = dti.to_period("D")
ser = pd.Series(range(3), index=pi)
- with pytest.raises(IndexError, match="index out of bounds"):
+ with pytest.raises(IndexError, match=msg):
pi.get_value(ser, 16801)
+ msg = "index 46 is out of bounds for axis 0 with size 3"
pi2 = dti.to_period("Y") # duplicates, ordinals are all 46
ser2 = pd.Series(range(3), index=pi2)
- with pytest.raises(IndexError, match="index out of bounds"):
+ with pytest.raises(IndexError, match=msg):
pi2.get_value(ser2, 46)
def test_is_monotonic_increasing(self):
diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py
index 18dbd22b73b35..ed05be3dedc7d 100644
--- a/pandas/tests/series/indexing/test_indexing.py
+++ b/pandas/tests/series/indexing/test_indexing.py
@@ -17,10 +17,9 @@
def test_basic_indexing():
s = Series(np.random.randn(5), index=["a", "b", "a", "a", "b"])
- msg = "index out of bounds"
+ msg = "index 5 is out of bounds for axis 0 with size 5"
with pytest.raises(IndexError, match=msg):
s[5]
- msg = "index 5 is out of bounds for axis 0 with size 5"
with pytest.raises(IndexError, match=msg):
s[5] = 0
@@ -29,7 +28,6 @@ def test_basic_indexing():
s = s.sort_index()
- msg = r"index out of bounds|^5$"
with pytest.raises(IndexError, match=msg):
s[5]
msg = r"index 5 is out of bounds for axis (0|1) with size 5|^5$"
@@ -165,11 +163,12 @@ def test_getitem_with_duplicates_indices(result_1, duplicate_item, expected_1):
def test_getitem_out_of_bounds(datetime_series):
# don't segfault, GH #495
- msg = "index out of bounds"
+ msg = r"index \d+ is out of bounds for axis 0 with size \d+"
with pytest.raises(IndexError, match=msg):
datetime_series[len(datetime_series)]
# GH #917
+ msg = r"index -\d+ is out of bounds for axis 0 with size \d+"
s = Series([], dtype=object)
with pytest.raises(IndexError, match=msg):
s[-1]
diff --git a/pandas/tests/series/indexing/test_numeric.py b/pandas/tests/series/indexing/test_numeric.py
index 3684ca00c2f17..771f5533f29d8 100644
--- a/pandas/tests/series/indexing/test_numeric.py
+++ b/pandas/tests/series/indexing/test_numeric.py
@@ -202,10 +202,9 @@ def test_slice_float64():
def test_getitem_negative_out_of_bounds():
s = Series(tm.rands_array(5, 10), index=tm.rands_array(10, 10))
- msg = "index out of bounds"
+ msg = "index -11 is out of bounds for axis 0 with size 10"
with pytest.raises(IndexError, match=msg):
s[-11]
- msg = "index -11 is out of bounds for axis 0 with size 10"
with pytest.raises(IndexError, match=msg):
s[-11] = "foo"
| Made possible because Series._values returns DTA/TDA for datetime64/timedelta64. | https://api.github.com/repos/pandas-dev/pandas/pulls/31506 | 2020-01-31T17:48:46Z | 2020-02-02T22:45:26Z | 2020-02-02T22:45:26Z | 2020-02-02T23:19:12Z |
BUG: Fixed IntervalArray[int].shift | diff --git a/doc/source/whatsnew/v1.0.1.rst b/doc/source/whatsnew/v1.0.1.rst
index 180411afb117d..be0d144e541b1 100644
--- a/doc/source/whatsnew/v1.0.1.rst
+++ b/doc/source/whatsnew/v1.0.1.rst
@@ -55,6 +55,9 @@ Bug fixes
- Plotting tz-aware timeseries no longer gives UserWarning (:issue:`31205`)
+**Interval**
+
+- Bug in :meth:`Series.shift` with ``interval`` dtype raising a ``TypeError`` when shifting an interval array of integers or datetimes (:issue:`34195`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 398ed75c060ca..0b35a031bc53f 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -27,6 +27,7 @@
from pandas.core.dtypes.dtypes import IntervalDtype
from pandas.core.dtypes.generic import (
ABCDatetimeIndex,
+ ABCExtensionArray,
ABCIndexClass,
ABCInterval,
ABCIntervalIndex,
@@ -789,6 +790,33 @@ def size(self) -> int:
# Avoid materializing self.values
return self.left.size
+ def shift(self, periods: int = 1, fill_value: object = None) -> ABCExtensionArray:
+ if not len(self) or periods == 0:
+ return self.copy()
+
+ if isna(fill_value):
+ fill_value = self.dtype.na_value
+
+ # ExtensionArray.shift doesn't work for two reasons
+ # 1. IntervalArray.dtype.na_value may not be correct for the dtype.
+ # 2. IntervalArray._from_sequence only accepts NaN for missing values,
+ # not other values like NaT
+
+ empty_len = min(abs(periods), len(self))
+ if isna(fill_value):
+ fill_value = self.left._na_value
+ empty = IntervalArray.from_breaks([fill_value] * (empty_len + 1))
+ else:
+ empty = self._from_sequence([fill_value] * empty_len)
+
+ if periods > 0:
+ a = empty
+ b = self[:-periods]
+ else:
+ a = self[abs(periods) :]
+ b = empty
+ return self._concat_same_type([a, b])
+
def take(self, indices, allow_fill=False, fill_value=None, axis=None, **kwargs):
"""
Take elements from the IntervalArray.
diff --git a/pandas/tests/arrays/interval/test_interval.py b/pandas/tests/arrays/interval/test_interval.py
index 35eda4a0ec5bc..7e7762d8973a0 100644
--- a/pandas/tests/arrays/interval/test_interval.py
+++ b/pandas/tests/arrays/interval/test_interval.py
@@ -81,6 +81,24 @@ def test_where_raises(self, other):
with pytest.raises(ValueError, match=match):
ser.where([True, False, True], other=other)
+ def test_shift(self):
+ # https://github.com/pandas-dev/pandas/issues/31495
+ a = IntervalArray.from_breaks([1, 2, 3])
+ result = a.shift()
+ # int -> float
+ expected = IntervalArray.from_tuples([(np.nan, np.nan), (1.0, 2.0)])
+ tm.assert_interval_array_equal(result, expected)
+
+ def test_shift_datetime(self):
+ a = IntervalArray.from_breaks(pd.date_range("2000", periods=4))
+ result = a.shift(2)
+ expected = a.take([-1, -1, 0], allow_fill=True)
+ tm.assert_interval_array_equal(result, expected)
+
+ result = a.shift(-1)
+ expected = a.take([1, 2, -1], allow_fill=True)
+ tm.assert_interval_array_equal(result, expected)
+
class TestSetitem:
def test_set_na(self, left_right_dtypes):
diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py
index 4a84a21084de2..22e53dbc89f01 100644
--- a/pandas/tests/extension/base/methods.py
+++ b/pandas/tests/extension/base/methods.py
@@ -280,6 +280,13 @@ def test_shift_empty_array(self, data, periods):
expected = empty
self.assert_extension_array_equal(result, expected)
+ def test_shift_zero_copies(self, data):
+ result = data.shift(0)
+ assert result is not data
+
+ result = data[:0].shift(2)
+ assert result is not data
+
def test_shift_fill_value(self, data):
arr = data[:4]
fill_value = data[0]
| Closes https://github.com/pandas-dev/pandas/issues/31495
In ExtensionArray.shift, we have the note
```
# Note: this implementation assumes that `self.dtype.na_value` can be
# stored in an instance of your ExtensionArray with `self.dtype`.
```
I wonder, should we have a method / property like
```
@property
def _can_hold_na_value(self):
return True
```
And for IntervalArray, we would do something like
```python
@property
def _can_hold_na_value(self):
return is_float_dtype(self.dtype.subtype)
```
That would let us deduplicate things, since the call to `_from_sequence` would know to not pass `dtype=self.dtype` and trigger a re-inference. | https://api.github.com/repos/pandas-dev/pandas/pulls/31502 | 2020-01-31T16:51:03Z | 2020-02-04T16:56:08Z | 2020-02-04T16:56:08Z | 2020-02-04T16:56:08Z |
DOC: Replaced "the the" with "the" | diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx
index 93ea94f7b18fc..edc44f1c94589 100644
--- a/pandas/_libs/groupby.pyx
+++ b/pandas/_libs/groupby.pyx
@@ -1143,7 +1143,7 @@ def group_rank(float64_t[:, :] out,
# Update out only when there is a transition of values or labels.
# When a new value or group is encountered, go back #dups steps(
# the number of occurrence of current value) and assign the ranks
- # based on the the starting index of the current group (grp_start)
+ # based on the starting index of the current group (grp_start)
# and the current index
if (i == N - 1 or
(masked_vals[_as[i]] != masked_vals[_as[i+1]]) or
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index d890c0c16aecc..4574cd7bea1ae 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -729,11 +729,11 @@ def _shallow_copy(self, left=None, right=None, closed=None):
Parameters
----------
left : array-like
- Values to be used for the left-side of the the intervals.
+ Values to be used for the left-side of the intervals.
If None, the existing left and right values will be used.
right : array-like
- Values to be used for the right-side of the the intervals.
+ Values to be used for the right-side of the intervals.
If None and left is IntervalArray-like, the left and right
of the IntervalArray-like will be used.
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index f8ee47de94edd..3b1d7e4c50be5 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -2681,7 +2681,7 @@ def to_clipboard(
... # 0,1,2,3
... # 1,4,5,6
- We can omit the the index by passing the keyword `index` and setting
+ We can omit the index by passing the keyword `index` and setting
it to false.
>>> df.to_clipboard(sep=',', index=False)
diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py
index 139e0f2bbad8b..1fe383706f74d 100644
--- a/pandas/plotting/_core.py
+++ b/pandas/plotting/_core.py
@@ -1426,7 +1426,7 @@ def pie(self, **kwargs):
Examples
--------
In the example below we have a DataFrame with the information about
- planet's mass and radius. We pass the the 'mass' column to the
+ planet's mass and radius. We pass the 'mass' column to the
pie function to get a pie plot.
.. plot::
| - [ ] 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/31500 | 2020-01-31T16:29:37Z | 2020-01-31T17:39:35Z | 2020-01-31T17:39:35Z | 2020-02-01T10:51:13Z |
Backport PR #31494 on branch 1.0.x (DOC: move whatnew entry for invert from 1.0.0 t 1.0.1) | diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index 5cde01310eeea..b0b88c8b04ad1 100755
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -1108,7 +1108,6 @@ Numeric
- Bug in :meth:`DataFrame.round` where a :class:`DataFrame` with a :class:`CategoricalIndex` of :class:`IntervalIndex` columns would incorrectly raise a ``TypeError`` (:issue:`30063`)
- Bug in :meth:`Series.pct_change` and :meth:`DataFrame.pct_change` when there are duplicated indices (:issue:`30463`)
- Bug in :class:`DataFrame` cumulative operations (e.g. cumsum, cummax) incorrect casting to object-dtype (:issue:`19296`)
-- Bug in dtypes being lost in ``DataFrame.__invert__`` (``~`` operator) with mixed dtypes (:issue:`31183`)
- Bug in :class:`~DataFrame.diff` losing the dtype for extension types (:issue:`30889`)
- Bug in :class:`DataFrame.diff` raising an ``IndexError`` when one of the columns was a nullable integer dtype (:issue:`30967`)
@@ -1261,8 +1260,6 @@ ExtensionArray
- Bug in :class:`arrays.PandasArray` when setting a scalar string (:issue:`28118`, :issue:`28150`).
- Bug where nullable integers could not be compared to strings (:issue:`28930`)
- Bug where :class:`DataFrame` constructor raised ``ValueError`` with list-like data and ``dtype`` specified (:issue:`30280`)
-- Bug in dtype being lost in ``__invert__`` (``~`` operator) for extension-array backed ``Series`` and ``DataFrame`` (:issue:`23087`)
-
Other
^^^^^
diff --git a/doc/source/whatsnew/v1.0.1.rst b/doc/source/whatsnew/v1.0.1.rst
index b84448e3bf896..ff8433c7cafd9 100644
--- a/doc/source/whatsnew/v1.0.1.rst
+++ b/doc/source/whatsnew/v1.0.1.rst
@@ -43,7 +43,7 @@ Timezones
Numeric
^^^^^^^
--
+- Bug in dtypes being lost in ``DataFrame.__invert__`` (``~`` operator) with mixed dtypes (:issue:`31183`)
-
Conversion
@@ -117,7 +117,7 @@ Sparse
ExtensionArray
^^^^^^^^^^^^^^
--
+- Bug in dtype being lost in ``__invert__`` (``~`` operator) for extension-array backed ``Series`` and ``DataFrame`` (:issue:`23087`)
-
| Backport PR #31494: DOC: move whatnew entry for invert from 1.0.0 t 1.0.1 | https://api.github.com/repos/pandas-dev/pandas/pulls/31496 | 2020-01-31T14:04:52Z | 2020-01-31T16:24:17Z | 2020-01-31T16:24:17Z | 2020-01-31T16:24:17Z |
DOC: move whatnew entry for invert from 1.0.0 t 1.0.1 | diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index 00dc3fdb28f26..6597b764581a4 100755
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -1107,7 +1107,6 @@ Numeric
- Bug in :meth:`DataFrame.round` where a :class:`DataFrame` with a :class:`CategoricalIndex` of :class:`IntervalIndex` columns would incorrectly raise a ``TypeError`` (:issue:`30063`)
- Bug in :meth:`Series.pct_change` and :meth:`DataFrame.pct_change` when there are duplicated indices (:issue:`30463`)
- Bug in :class:`DataFrame` cumulative operations (e.g. cumsum, cummax) incorrect casting to object-dtype (:issue:`19296`)
-- Bug in dtypes being lost in ``DataFrame.__invert__`` (``~`` operator) with mixed dtypes (:issue:`31183`)
- Bug in :class:`~DataFrame.diff` losing the dtype for extension types (:issue:`30889`)
- Bug in :class:`DataFrame.diff` raising an ``IndexError`` when one of the columns was a nullable integer dtype (:issue:`30967`)
@@ -1260,8 +1259,6 @@ ExtensionArray
- Bug in :class:`arrays.PandasArray` when setting a scalar string (:issue:`28118`, :issue:`28150`).
- Bug where nullable integers could not be compared to strings (:issue:`28930`)
- Bug where :class:`DataFrame` constructor raised ``ValueError`` with list-like data and ``dtype`` specified (:issue:`30280`)
-- Bug in dtype being lost in ``__invert__`` (``~`` operator) for extension-array backed ``Series`` and ``DataFrame`` (:issue:`23087`)
-
Other
^^^^^
diff --git a/doc/source/whatsnew/v1.0.1.rst b/doc/source/whatsnew/v1.0.1.rst
index b84448e3bf896..ff8433c7cafd9 100644
--- a/doc/source/whatsnew/v1.0.1.rst
+++ b/doc/source/whatsnew/v1.0.1.rst
@@ -43,7 +43,7 @@ Timezones
Numeric
^^^^^^^
--
+- Bug in dtypes being lost in ``DataFrame.__invert__`` (``~`` operator) with mixed dtypes (:issue:`31183`)
-
Conversion
@@ -117,7 +117,7 @@ Sparse
ExtensionArray
^^^^^^^^^^^^^^
--
+- Bug in dtype being lost in ``__invert__`` (``~`` operator) for extension-array backed ``Series`` and ``DataFrame`` (:issue:`23087`)
-
| see https://github.com/pandas-dev/pandas/pull/31493, forgot to backport, so the fix will only be included in 1.0.1 | https://api.github.com/repos/pandas-dev/pandas/pulls/31494 | 2020-01-31T12:29:48Z | 2020-01-31T14:03:59Z | 2020-01-31T14:03:59Z | 2020-01-31T14:04:57Z |
Backport PR #31183: BUG: Series/Frame invert dtypes' | diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index 989cc9b5d78c2..5cde01310eeea 100755
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -1108,6 +1108,7 @@ Numeric
- Bug in :meth:`DataFrame.round` where a :class:`DataFrame` with a :class:`CategoricalIndex` of :class:`IntervalIndex` columns would incorrectly raise a ``TypeError`` (:issue:`30063`)
- Bug in :meth:`Series.pct_change` and :meth:`DataFrame.pct_change` when there are duplicated indices (:issue:`30463`)
- Bug in :class:`DataFrame` cumulative operations (e.g. cumsum, cummax) incorrect casting to object-dtype (:issue:`19296`)
+- Bug in dtypes being lost in ``DataFrame.__invert__`` (``~`` operator) with mixed dtypes (:issue:`31183`)
- Bug in :class:`~DataFrame.diff` losing the dtype for extension types (:issue:`30889`)
- Bug in :class:`DataFrame.diff` raising an ``IndexError`` when one of the columns was a nullable integer dtype (:issue:`30967`)
@@ -1260,6 +1261,7 @@ ExtensionArray
- Bug in :class:`arrays.PandasArray` when setting a scalar string (:issue:`28118`, :issue:`28150`).
- Bug where nullable integers could not be compared to strings (:issue:`28930`)
- Bug where :class:`DataFrame` constructor raised ``ValueError`` with list-like data and ``dtype`` specified (:issue:`30280`)
+- Bug in dtype being lost in ``__invert__`` (``~`` operator) for extension-array backed ``Series`` and ``DataFrame`` (:issue:`23087`)
Other
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index aa716848ec4d5..80e317123126a 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -48,6 +48,9 @@ def __iter__(self):
def __len__(self) -> int:
return len(self._data)
+ def __invert__(self):
+ return type(self)(~self._data, self._mask)
+
def to_numpy(
self, dtype=None, copy=False, na_value: "Scalar" = lib.no_default,
):
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index f158126f52e8f..18e6b913cc10d 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1470,8 +1470,9 @@ def __invert__(self):
# inv fails with 0 len
return self
- arr = operator.inv(com.values_from_object(self))
- return self.__array_wrap__(arr)
+ new_data = self._data.apply(operator.invert)
+ result = self._constructor(new_data).__finalize__(self)
+ return result
def __nonzero__(self):
raise ValueError(
diff --git a/pandas/tests/arrays/sparse/test_arithmetics.py b/pandas/tests/arrays/sparse/test_arithmetics.py
index 73652da78654f..bf7d275e4ff7b 100644
--- a/pandas/tests/arrays/sparse/test_arithmetics.py
+++ b/pandas/tests/arrays/sparse/test_arithmetics.py
@@ -476,6 +476,14 @@ def test_invert(fill_value):
expected = SparseArray(~arr, fill_value=not fill_value)
tm.assert_sp_array_equal(result, expected)
+ result = ~pd.Series(sparray)
+ expected = pd.Series(expected)
+ tm.assert_series_equal(result, expected)
+
+ result = ~pd.DataFrame({"A": sparray})
+ expected = pd.DataFrame({"A": expected})
+ tm.assert_frame_equal(result, expected)
+
@pytest.mark.parametrize("fill_value", [0, np.nan])
@pytest.mark.parametrize("op", [operator.pos, operator.neg])
diff --git a/pandas/tests/arrays/test_boolean.py b/pandas/tests/arrays/test_boolean.py
index 200446f79af8a..cb9b07db4a0df 100644
--- a/pandas/tests/arrays/test_boolean.py
+++ b/pandas/tests/arrays/test_boolean.py
@@ -471,6 +471,24 @@ def test_ufunc_reduce_raises(values):
np.add.reduce(a)
+class TestUnaryOps:
+ def test_invert(self):
+ a = pd.array([True, False, None], dtype="boolean")
+ expected = pd.array([False, True, None], dtype="boolean")
+ tm.assert_extension_array_equal(~a, expected)
+
+ expected = pd.Series(expected, index=["a", "b", "c"], name="name")
+ result = ~pd.Series(a, index=["a", "b", "c"], name="name")
+ tm.assert_series_equal(result, expected)
+
+ df = pd.DataFrame({"A": a, "B": [True, False, False]}, index=["a", "b", "c"])
+ result = ~df
+ expected = pd.DataFrame(
+ {"A": expected, "B": [False, True, True]}, index=["a", "b", "c"]
+ )
+ tm.assert_frame_equal(result, expected)
+
+
class TestLogicalOps(BaseOpsUtil):
def test_numpy_scalars_ok(self, all_logical_operators):
a = pd.array([True, False, None], dtype="boolean")
diff --git a/pandas/tests/extension/base/__init__.py b/pandas/tests/extension/base/__init__.py
index 090df35bd94c9..e2b6ea0304f6a 100644
--- a/pandas/tests/extension/base/__init__.py
+++ b/pandas/tests/extension/base/__init__.py
@@ -49,7 +49,12 @@ class TestMyDtype(BaseDtypeTests):
from .io import BaseParsingTests # noqa
from .methods import BaseMethodsTests # noqa
from .missing import BaseMissingTests # noqa
-from .ops import BaseArithmeticOpsTests, BaseComparisonOpsTests, BaseOpsUtil # noqa
+from .ops import ( # noqa
+ BaseArithmeticOpsTests,
+ BaseComparisonOpsTests,
+ BaseOpsUtil,
+ BaseUnaryOpsTests,
+)
from .printing import BasePrintingTests # noqa
from .reduce import ( # noqa
BaseBooleanReduceTests,
diff --git a/pandas/tests/extension/base/ops.py b/pandas/tests/extension/base/ops.py
index 20d06ef2e5647..0609f19c8e0c3 100644
--- a/pandas/tests/extension/base/ops.py
+++ b/pandas/tests/extension/base/ops.py
@@ -168,3 +168,11 @@ def test_direct_arith_with_series_returns_not_implemented(self, data):
assert result is NotImplemented
else:
raise pytest.skip(f"{type(data).__name__} does not implement __eq__")
+
+
+class BaseUnaryOpsTests(BaseOpsUtil):
+ def test_invert(self, data):
+ s = pd.Series(data, name="name")
+ result = ~s
+ expected = pd.Series(~data, name="name")
+ self.assert_series_equal(result, expected)
diff --git a/pandas/tests/extension/test_boolean.py b/pandas/tests/extension/test_boolean.py
index c489445d8512a..0c6b187eac1fc 100644
--- a/pandas/tests/extension/test_boolean.py
+++ b/pandas/tests/extension/test_boolean.py
@@ -342,6 +342,10 @@ class TestPrinting(base.BasePrintingTests):
pass
+class TestUnaryOps(base.BaseUnaryOpsTests):
+ pass
+
+
# TODO parsing not yet supported
# class TestParsing(base.BaseParsingTests):
# pass
diff --git a/pandas/tests/frame/test_operators.py b/pandas/tests/frame/test_operators.py
index c727cb398d53e..55f1216a0efd7 100644
--- a/pandas/tests/frame/test_operators.py
+++ b/pandas/tests/frame/test_operators.py
@@ -61,6 +61,27 @@ def test_invert(self, float_frame):
tm.assert_frame_equal(-(df < 0), ~(df < 0))
+ def test_invert_mixed(self):
+ shape = (10, 5)
+ df = pd.concat(
+ [
+ pd.DataFrame(np.zeros(shape, dtype="bool")),
+ pd.DataFrame(np.zeros(shape, dtype=int)),
+ ],
+ axis=1,
+ ignore_index=True,
+ )
+ result = ~df
+ expected = pd.concat(
+ [
+ pd.DataFrame(np.ones(shape, dtype="bool")),
+ pd.DataFrame(-np.ones(shape, dtype=int)),
+ ],
+ axis=1,
+ ignore_index=True,
+ )
+ tm.assert_frame_equal(result, expected)
+
@pytest.mark.parametrize(
"df",
[
| We forgot to backport this: https://github.com/pandas-dev/pandas/pull/31183
Closes #31489 | https://api.github.com/repos/pandas-dev/pandas/pulls/31493 | 2020-01-31T12:26:42Z | 2020-01-31T14:03:42Z | 2020-01-31T14:03:42Z | 2020-01-31T16:24:04Z |
DOC: Fix the description of the 'day' field accessor in DatetimeArray | diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index 4b6b54cce64ec..5888600d2fa8e 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -1262,7 +1262,7 @@ def date(self):
"day",
"D",
"""
- The month as January=1, December=12.
+ The day of the datetime.
""",
)
hour = _field_accessor(
| Fix a wrong description in the field accessor `day` of the DatetimeArray class | https://api.github.com/repos/pandas-dev/pandas/pulls/31490 | 2020-01-31T11:11:56Z | 2020-01-31T11:51:10Z | 2020-01-31T11:51:10Z | 2020-01-31T11:51:18Z |
DOC: Parameter doc strings for Groupby.(sum|prod|min|max|first|last) | diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 71e7aafbca27d..54275dc52bb56 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1351,13 +1351,22 @@ def groupby_function(
_local_template = """
Compute %(f)s of group values.
+ Parameters
+ ----------
+ numeric_only : bool, default %(no)s
+ Include only float, int, boolean columns. If None, will attempt to use
+ everything, then use only numeric data.
+ min_count : int, default %(mc)s
+ The required number of valid values to perform the operation. If fewer
+ than ``min_count`` non-NA values are present the result will be NA.
+
Returns
-------
Series or DataFrame
Computed %(f)s of values within each group.
"""
- @Substitution(name="groupby", f=name)
+ @Substitution(name="groupby", f=name, no=numeric_only, mc=min_count)
@Appender(_common_see_also)
@Appender(_local_template)
def func(self, numeric_only=numeric_only, min_count=min_count):
| Follow-up to #31473. | https://api.github.com/repos/pandas-dev/pandas/pulls/31486 | 2020-01-31T10:20:17Z | 2020-01-31T11:54:35Z | 2020-01-31T11:54:35Z | 2020-02-12T22:12:38Z |
CLN: named parameters for GroupBy.(mean|median|var|std) | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index cf2f507dc019c..aad11eeee38f2 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -60,6 +60,9 @@ Backwards incompatible API changes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- :meth:`DataFrame.swaplevels` now raises a ``TypeError`` if the axis is not a :class:`MultiIndex`.
Previously a ``AttributeError`` was raised (:issue:`31126`)
+- :meth:`DataFrameGroupby.mean` and :meth:`SeriesGroupby.mean` (and similarly for :meth:`~DataFrameGroupby.median`, :meth:`~DataFrameGroupby.std`` and :meth:`~DataFrameGroupby.var``)
+ now raise a ``TypeError`` if a not-accepted keyword argument is passed into it.
+ Previously a ``UnsupportedFunctionCall`` was raised (``AssertionError`` if ``min_count`` passed into :meth:`~DataFrameGroupby.median``) (:issue:`31485`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 54275dc52bb56..b52d1bb4db360 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1180,10 +1180,16 @@ def count(self):
@Substitution(name="groupby")
@Substitution(see_also=_common_see_also)
- def mean(self, *args, **kwargs):
+ def mean(self, numeric_only: bool = True):
"""
Compute mean of groups, excluding missing values.
+ Parameters
+ ----------
+ numeric_only : bool, default True
+ Include only float, int, boolean columns. If None, will attempt to use
+ everything, then use only numeric data.
+
Returns
-------
pandas.Series or pandas.DataFrame
@@ -1222,19 +1228,26 @@ def mean(self, *args, **kwargs):
2 4.0
Name: B, dtype: float64
"""
- nv.validate_groupby_func("mean", args, kwargs, ["numeric_only"])
return self._cython_agg_general(
- "mean", alt=lambda x, axis: Series(x).mean(**kwargs), **kwargs
+ "mean",
+ alt=lambda x, axis: Series(x).mean(numeric_only=numeric_only),
+ numeric_only=numeric_only,
)
@Substitution(name="groupby")
@Appender(_common_see_also)
- def median(self, **kwargs):
+ def median(self, numeric_only=True):
"""
Compute median of groups, excluding missing values.
For multiple groupings, the result index will be a MultiIndex
+ Parameters
+ ----------
+ numeric_only : bool, default True
+ Include only float, int, boolean columns. If None, will attempt to use
+ everything, then use only numeric data.
+
Returns
-------
Series or DataFrame
@@ -1242,13 +1255,13 @@ def median(self, **kwargs):
"""
return self._cython_agg_general(
"median",
- alt=lambda x, axis: Series(x).median(axis=axis, **kwargs),
- **kwargs,
+ alt=lambda x, axis: Series(x).median(axis=axis, numeric_only=numeric_only),
+ numeric_only=numeric_only,
)
@Substitution(name="groupby")
@Appender(_common_see_also)
- def std(self, ddof: int = 1, *args, **kwargs):
+ def std(self, ddof: int = 1):
"""
Compute standard deviation of groups, excluding missing values.
@@ -1266,12 +1279,11 @@ def std(self, ddof: int = 1, *args, **kwargs):
"""
# TODO: implement at Cython level?
- nv.validate_groupby_func("std", args, kwargs)
- return np.sqrt(self.var(ddof=ddof, **kwargs))
+ return np.sqrt(self.var(ddof=ddof))
@Substitution(name="groupby")
@Appender(_common_see_also)
- def var(self, ddof: int = 1, *args, **kwargs):
+ def var(self, ddof: int = 1):
"""
Compute variance of groups, excluding missing values.
@@ -1287,15 +1299,14 @@ def var(self, ddof: int = 1, *args, **kwargs):
Series or DataFrame
Variance of values within each group.
"""
- nv.validate_groupby_func("var", args, kwargs)
if ddof == 1:
return self._cython_agg_general(
- "var", alt=lambda x, axis: Series(x).var(ddof=ddof, **kwargs), **kwargs
+ "var", alt=lambda x, axis: Series(x).var(ddof=ddof)
)
else:
- f = lambda x: x.var(ddof=ddof, **kwargs)
+ func = lambda x: x.var(ddof=ddof)
with _group_selection_context(self):
- return self._python_agg_general(f)
+ return self._python_agg_general(func)
@Substitution(name="groupby")
@Appender(_common_see_also)
diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py
index 97cf1af1d2e9e..73e36cb5e6c84 100644
--- a/pandas/tests/groupby/test_function.py
+++ b/pandas/tests/groupby/test_function.py
@@ -671,7 +671,7 @@ def test_nsmallest():
tm.assert_series_equal(gb.nsmallest(3, keep="last"), e)
-@pytest.mark.parametrize("func", ["mean", "var", "std", "cumprod", "cumsum"])
+@pytest.mark.parametrize("func", ["cumprod", "cumsum"])
def test_numpy_compat(func):
# see gh-12811
df = pd.DataFrame({"A": [1, 2, 1], "B": [1, 2, 3]})
| Drops *args & **kwargs, replace with named parameters for groupby methods mean, median, var & std. Similar to #31473.
This PR has the side effect that the raised error when a parameter is not allowed, is now ``TypeError`` instead of ``UnsupportedFunctionCall``, so technically a API change... | https://api.github.com/repos/pandas-dev/pandas/pulls/31485 | 2020-01-31T09:41:52Z | 2020-02-02T22:46:32Z | 2020-02-02T22:46:32Z | 2020-02-04T16:25:32Z |
BUG: Array.__setitem__ failing with nullable boolean mask | diff --git a/doc/source/whatsnew/v1.0.1.rst b/doc/source/whatsnew/v1.0.1.rst
index b84448e3bf896..2e694e601e79e 100644
--- a/doc/source/whatsnew/v1.0.1.rst
+++ b/doc/source/whatsnew/v1.0.1.rst
@@ -70,6 +70,7 @@ Indexing
-
-
+- Bug where assigning to a :class:`Series` using a IntegerArray / BooleanArray as a mask would raise ``TypeError`` (:issue:`31446`)
Missing
^^^^^^^
diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py
index 7b12f3348e7e7..9eeed42124f2a 100644
--- a/pandas/core/arrays/boolean.py
+++ b/pandas/core/arrays/boolean.py
@@ -26,6 +26,7 @@
from pandas.core.dtypes.missing import isna, notna
from pandas.core import nanops, ops
+from pandas.core.indexers import check_array_indexer
from .masked import BaseMaskedArray
@@ -369,6 +370,7 @@ def __setitem__(self, key, value):
value = value[0]
mask = mask[0]
+ key = check_array_indexer(self, key)
self._data[key] = value
self._mask[key] = mask
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index 412422397af06..3a6662d3e3ae2 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -2073,6 +2073,8 @@ def __setitem__(self, key, value):
lindexer = self.categories.get_indexer(rvalue)
lindexer = self._maybe_coerce_indexer(lindexer)
+
+ key = check_array_indexer(self, key)
self._codes[key] = lindexer
def _reverse_indexer(self) -> Dict[Hashable, np.ndarray]:
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 0ea707e1ae69d..4f14ac2a14157 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -601,6 +601,8 @@ def __setitem__(
f"or array of those. Got '{type(value).__name__}' instead."
)
raise TypeError(msg)
+
+ key = check_array_indexer(self, key)
self._data[key] = value
self._maybe_clear_freq()
diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py
index 022e6a7322872..9a0f5794e7607 100644
--- a/pandas/core/arrays/integer.py
+++ b/pandas/core/arrays/integer.py
@@ -25,6 +25,7 @@
from pandas.core.dtypes.missing import isna
from pandas.core import nanops, ops
+from pandas.core.indexers import check_array_indexer
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
@@ -414,6 +415,7 @@ def __setitem__(self, key, value):
value = value[0]
mask = mask[0]
+ key = check_array_indexer(self, key)
self._data[key] = value
self._mask[key] = mask
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index d890c0c16aecc..23cf5f317ac7d 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -541,6 +541,7 @@ def __setitem__(self, key, value):
msg = f"'value' should be an interval type, got {type(value)} instead."
raise TypeError(msg)
+ key = check_array_indexer(self, key)
# Need to ensure that left and right are updated atomically, so we're
# forced to copy, update the copy, and swap in the new values.
left = self.left.copy(deep=True)
diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py
index 6a2d15d1e79aa..e56d6a7d2f089 100644
--- a/pandas/core/arrays/numpy_.py
+++ b/pandas/core/arrays/numpy_.py
@@ -245,6 +245,7 @@ def __getitem__(self, item):
def __setitem__(self, key, value):
value = extract_array(value, extract_numpy=True)
+ key = check_array_indexer(self, key)
scalar_key = lib.is_scalar(key)
scalar_value = lib.is_scalar(value)
diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py
index c485d1f50dc9d..b53484e1892f9 100644
--- a/pandas/core/arrays/string_.py
+++ b/pandas/core/arrays/string_.py
@@ -15,6 +15,7 @@
from pandas.core import ops
from pandas.core.arrays import PandasArray
from pandas.core.construction import extract_array
+from pandas.core.indexers import check_array_indexer
from pandas.core.missing import isna
@@ -224,6 +225,7 @@ def __setitem__(self, key, value):
# extract_array doesn't extract PandasArray subclasses
value = value._ndarray
+ key = check_array_indexer(self, key)
scalar_key = lib.is_scalar(key)
scalar_value = lib.is_scalar(value)
if scalar_key and not scalar_value:
diff --git a/pandas/tests/arrays/test_integer.py b/pandas/tests/arrays/test_integer.py
index 63e3c946df912..cc81ae4504dd8 100644
--- a/pandas/tests/arrays/test_integer.py
+++ b/pandas/tests/arrays/test_integer.py
@@ -1074,6 +1074,23 @@ def test_cut(bins, right, include_lowest):
tm.assert_categorical_equal(result, expected)
+def test_array_setitem_nullable_boolean_mask():
+ # GH 31446
+ ser = pd.Series([1, 2], dtype="Int64")
+ result = ser.where(ser > 1)
+ expected = pd.Series([pd.NA, 2], dtype="Int64")
+ tm.assert_series_equal(result, expected)
+
+
+def test_array_setitem():
+ # GH 31446
+ arr = pd.Series([1, 2], dtype="Int64").array
+ arr[arr > 1] = 1
+
+ expected = pd.array([1, 1], dtype="Int64")
+ tm.assert_extension_array_equal(arr, expected)
+
+
# TODO(jreback) - these need testing / are broken
# shift
diff --git a/pandas/tests/extension/base/setitem.py b/pandas/tests/extension/base/setitem.py
index 0bb8aede6298c..e0ca603aaa0ed 100644
--- a/pandas/tests/extension/base/setitem.py
+++ b/pandas/tests/extension/base/setitem.py
@@ -4,6 +4,7 @@
import pytest
import pandas as pd
+from pandas.core.arrays.numpy_ import PandasDtype
from .base import BaseExtensionTests
@@ -195,3 +196,14 @@ def test_setitem_preserves_views(self, data):
data[0] = data[1]
assert view1[0] == data[1]
assert view2[0] == data[1]
+
+ def test_setitem_nullable_mask(self, data):
+ # GH 31446
+ # TODO: there is some issue with PandasArray, therefore,
+ # TODO: skip the setitem test for now, and fix it later
+ if data.dtype != PandasDtype("object"):
+ arr = data[:5]
+ expected = data.take([0, 0, 0, 3, 4])
+ mask = pd.array([True, True, True, False, False])
+ arr[mask] = data[0]
+ self.assert_extension_array_equal(expected, arr)
diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py
index 02153ade46610..2614d8c72c342 100644
--- a/pandas/tests/extension/decimal/array.py
+++ b/pandas/tests/extension/decimal/array.py
@@ -11,6 +11,7 @@
import pandas as pd
from pandas.api.extensions import no_default, register_extension_dtype
from pandas.core.arrays import ExtensionArray, ExtensionScalarOpsMixin
+from pandas.core.indexers import check_array_indexer
@register_extension_dtype
@@ -138,6 +139,8 @@ def __setitem__(self, key, value):
value = [decimal.Decimal(v) for v in value]
else:
value = decimal.Decimal(value)
+
+ key = check_array_indexer(self, key)
self._data[key] = value
def __len__(self) -> int:
| - [x] closes #31446
- [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/31484 | 2020-01-31T09:14:04Z | 2020-02-01T14:37:26Z | 2020-02-01T14:37:26Z | 2020-02-06T09:08:02Z |
TST: preserve dtypes on assignment | diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py
index b9dc96adfa738..0cb4bdcc334d8 100644
--- a/pandas/tests/indexing/test_loc.py
+++ b/pandas/tests/indexing/test_loc.py
@@ -92,6 +92,18 @@ def test_loc_setitem_slice(self):
expected = DataFrame({"a": [0, 1, 1], "b": [100, 200, 300]}, dtype="uint64")
tm.assert_frame_equal(df2, expected)
+ def test_loc_setitem_dtype(self):
+ # GH31340
+ df = DataFrame({"id": ["A"], "a": [1.2], "b": [0.0], "c": [-2.5]})
+ cols = ["a", "b", "c"]
+ df.loc[:, cols] = df.loc[:, cols].astype("float32")
+
+ expected = DataFrame(
+ {"id": ["A"], "a": [1.2], "b": [0.0], "c": [-2.5]}, dtype="float32"
+ ) # id is inferred as object
+
+ tm.assert_frame_equal(df, expected)
+
def test_loc_getitem_int(self):
# int label
| - [x] closes #31340
- [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/31483 | 2020-01-31T08:49:46Z | 2020-02-01T23:20:37Z | 2020-02-01T23:20:37Z | 2020-02-01T23:20:49Z |
BUG: objToJson.c - fix return value | diff --git a/doc/source/whatsnew/v1.0.1.rst b/doc/source/whatsnew/v1.0.1.rst
index b84448e3bf896..9b3d496827d3f 100644
--- a/doc/source/whatsnew/v1.0.1.rst
+++ b/doc/source/whatsnew/v1.0.1.rst
@@ -123,7 +123,7 @@ ExtensionArray
Other
^^^^^
--
+- Regression fixed in objTOJSON.c fix return-type warning (:issue:`31463`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/_libs/src/ujson/python/objToJSON.c b/pandas/_libs/src/ujson/python/objToJSON.c
index 62c2870c198c4..da85196550c9f 100644
--- a/pandas/_libs/src/ujson/python/objToJSON.c
+++ b/pandas/_libs/src/ujson/python/objToJSON.c
@@ -177,6 +177,8 @@ void *initObjToJSON(void) {
/* Initialise numpy API */
import_array();
+ // GH 31463
+ return NULL;
}
static TypeContext *createTypeContext(void) {
| - [x] closes #31463
https://dev.azure.com/pandas-dev/pandas/_build/results?buildId=27217&view=logs&j=3a03f79d-0b41-5610-1aa4-b4a014d0bc70&t=fe74a338-551b-5fbb-553d-25f48b1836e8&l=687
Seems like this warning is somehow causing an error in the users builds of pandas | https://api.github.com/repos/pandas-dev/pandas/pulls/31482 | 2020-01-31T08:08:46Z | 2020-02-02T17:09:19Z | 2020-02-02T17:09:19Z | 2020-02-02T17:10:20Z |
Backport PR #31461 on branch 1.0.x (DOC: Fix DataFrame.to_csv example) | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 32ea4760fb86d..f158126f52e8f 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -3166,10 +3166,10 @@ def to_csv(
>>> df.to_csv(index=False)
'name,mask,weapon\nRaphael,red,sai\nDonatello,purple,bo staff\n'
- # create 'out.zip' containing 'out.csv'
+ Create 'out.zip' containing 'out.csv'
+
>>> compression_opts = dict(method='zip',
... archive_name='out.csv') # doctest: +SKIP
-
>>> df.to_csv('out.zip', index=False,
... compression=compression_opts) # doctest: +SKIP
"""
| Backport PR #31461: DOC: Fix DataFrame.to_csv example | https://api.github.com/repos/pandas-dev/pandas/pulls/31481 | 2020-01-31T07:20:16Z | 2020-01-31T09:16:48Z | 2020-01-31T09:16:48Z | 2020-01-31T09:16:48Z |
CLN: remove DatetimelikeDelegateMixin | diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index 0f385d9aba9c5..e123fdd228aaf 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -1,8 +1,7 @@
"""
Base and utility classes for tseries type pandas objects.
"""
-import operator
-from typing import Any, List, Optional, Set, Union
+from typing import Any, List, Optional, Union
import numpy as np
@@ -30,7 +29,6 @@
from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna
from pandas.core import algorithms
-from pandas.core.accessor import PandasDelegate
from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray
from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin
from pandas.core.base import _shared_docs
@@ -932,42 +930,3 @@ def insert(self, loc, item):
raise TypeError(
f"cannot insert {type(self).__name__} with incompatible label"
)
-
-
-class DatetimelikeDelegateMixin(PandasDelegate):
- """
- Delegation mechanism, specific for Datetime, Timedelta, and Period types.
-
- Functionality is delegated from the Index class to an Array class. A
- few things can be customized
-
- * _delegated_methods, delegated_properties : List
- The list of property / method names being delagated.
- * raw_methods : Set
- The set of methods whose results should should *not* be
- boxed in an index, after being returned from the array
- * raw_properties : Set
- The set of properties whose results should should *not* be
- boxed in an index, after being returned from the array
- """
-
- # raw_methods : dispatch methods that shouldn't be boxed in an Index
- _raw_methods: Set[str] = set()
- # raw_properties : dispatch properties that shouldn't be boxed in an Index
- _raw_properties: Set[str] = set()
- _data: Union[DatetimeArray, TimedeltaArray, PeriodArray]
-
- def _delegate_property_get(self, name, *args, **kwargs):
- result = getattr(self._data, name)
- if name not in self._raw_properties:
- result = Index(result, name=self.name)
- return result
-
- def _delegate_property_set(self, name: str, value, *args, **kwargs):
- setattr(self._data, name, value)
-
- def _delegate_method(self, name, *args, **kwargs):
- result = operator.methodcaller(name, *args, **kwargs)(self._data)
- if name not in self._raw_methods:
- result = Index(result, name=self.name)
- return result
| Made possibly by #31433. | https://api.github.com/repos/pandas-dev/pandas/pulls/31480 | 2020-01-31T04:21:35Z | 2020-01-31T12:01:35Z | 2020-01-31T12:01:34Z | 2020-01-31T15:48:02Z |
REGR: Fix TypeError in groupby min / max of period column | diff --git a/doc/source/whatsnew/v1.0.1.rst b/doc/source/whatsnew/v1.0.1.rst
index f9c756b2518af..20cfcfbde389c 100644
--- a/doc/source/whatsnew/v1.0.1.rst
+++ b/doc/source/whatsnew/v1.0.1.rst
@@ -20,6 +20,7 @@ Fixed regressions
- Fixed regression in ``DataFrame.__setitem__`` raising an ``AttributeError`` with a :class:`MultiIndex` and a non-monotonic indexer (:issue:`31449`)
- Fixed regression in :class:`Series` multiplication when multiplying a numeric :class:`Series` with >10000 elements with a timedelta-like scalar (:issue:`31457`)
- Fixed regression in :meth:`GroupBy.apply` if called with a function which returned a non-pandas non-scalar object (e.g. a list or numpy array) (:issue:`31441`)
+- Fixed regression in :meth:`DataFrame.groupby` whereby taking the minimum or maximum of a column with period dtype would raise a ``TypeError``. (:issue:`31471`)
- Fixed regression in :meth:`to_datetime` when parsing non-nanosecond resolution datetimes (:issue:`31491`)
- Fixed regression in :meth:`~DataFrame.to_csv` where specifying an ``na_rep`` might truncate the values written (:issue:`31447`)
- Fixed regression in :class:`Categorical` construction with ``numpy.str_`` categories (:issue:`31499`)
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 77c54ec736aaa..761353ca5a6ca 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -31,6 +31,7 @@
is_extension_array_dtype,
is_integer_dtype,
is_numeric_dtype,
+ is_period_dtype,
is_sparse,
is_timedelta64_dtype,
needs_i8_conversion,
@@ -567,7 +568,12 @@ def _cython_operation(
if swapped:
result = result.swapaxes(0, axis)
- if is_datetime64tz_dtype(orig_values.dtype):
+ if is_datetime64tz_dtype(orig_values.dtype) or is_period_dtype(
+ orig_values.dtype
+ ):
+ # We need to use the constructors directly for these dtypes
+ # since numpy won't recognize them
+ # https://github.com/pandas-dev/pandas/issues/31471
result = type(orig_values)(result.astype(np.int64), dtype=orig_values.dtype)
elif is_datetimelike and kind == "aggregate":
result = result.astype(orig_values.dtype)
diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py
index 2d31996a8a964..71af6533db764 100644
--- a/pandas/tests/groupby/aggregate/test_aggregate.py
+++ b/pandas/tests/groupby/aggregate/test_aggregate.py
@@ -684,6 +684,34 @@ def aggfunc(x):
tm.assert_frame_equal(result, expected)
+@pytest.mark.parametrize("func", ["min", "max"])
+def test_groupby_aggregate_period_column(func):
+ # GH 31471
+ groups = [1, 2]
+ periods = pd.period_range("2020", periods=2, freq="Y")
+ df = pd.DataFrame({"a": groups, "b": periods})
+
+ result = getattr(df.groupby("a")["b"], func)()
+ idx = pd.Int64Index([1, 2], name="a")
+ expected = pd.Series(periods, index=idx, name="b")
+
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("func", ["min", "max"])
+def test_groupby_aggregate_period_frame(func):
+ # GH 31471
+ groups = [1, 2]
+ periods = pd.period_range("2020", periods=2, freq="Y")
+ df = pd.DataFrame({"a": groups, "b": periods})
+
+ result = getattr(df.groupby("a"), func)()
+ idx = pd.Int64Index([1, 2], name="a")
+ expected = pd.DataFrame({"b": periods}, index=idx)
+
+ tm.assert_frame_equal(result, expected)
+
+
class TestLambdaMangling:
def test_basic(self):
df = pd.DataFrame({"A": [0, 0, 1, 1], "B": [1, 2, 3, 4]})
| - [x] closes #31471
- [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/31477 | 2020-01-31T02:06:23Z | 2020-02-04T22:52:28Z | 2020-02-04T22:52:27Z | 2020-02-04T22:54:20Z |
BUG: Period[us] start_time off by 1 nanosecond | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 9fdda83abe944..6fe42560f80ef 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -109,6 +109,7 @@ Datetimelike
- :meth:`DatetimeArray.searchsorted`, :meth:`TimedeltaArray.searchsorted`, :meth:`PeriodArray.searchsorted` not recognizing non-pandas scalars and incorrectly raising ``ValueError`` instead of ``TypeError`` (:issue:`30950`)
- Bug in :class:`Timestamp` where constructing :class:`Timestamp` with dateutil timezone less than 128 nanoseconds before daylight saving time switch from winter to summer would result in nonexistent time (:issue:`31043`)
- Bug in :meth:`DataFrame.reindex` and :meth:`Series.reindex` when reindexing with a tz-aware index (:issue:`26683`)
+- Bug in :meth:`Period.to_timestamp`, :meth:`Period.start_time` with microsecond frequency returning a timestamp one nanosecond earlier than the correct time (:issue:`31475`)
Timedelta
^^^^^^^^^
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx
index f3ae28578240f..9419f0eba39aa 100644
--- a/pandas/_libs/tslibs/period.pyx
+++ b/pandas/_libs/tslibs/period.pyx
@@ -22,7 +22,7 @@ PyDateTime_IMPORT
from pandas._libs.tslibs.np_datetime cimport (
npy_datetimestruct, dtstruct_to_dt64, dt64_to_dtstruct,
pandas_datetime_to_datetimestruct, check_dts_bounds,
- NPY_DATETIMEUNIT, NPY_FR_D)
+ NPY_DATETIMEUNIT, NPY_FR_D, NPY_FR_us)
cdef extern from "src/datetime/np_datetime.h":
int64_t npy_datetimestruct_to_datetime(NPY_DATETIMEUNIT fr,
@@ -1169,7 +1169,12 @@ cdef int64_t period_ordinal_to_dt64(int64_t ordinal, int freq) except? -1:
if ordinal == NPY_NAT:
return NPY_NAT
- get_date_info(ordinal, freq, &dts)
+ if freq == 11000:
+ # Microsecond, avoid get_date_info to prevent floating point errors
+ pandas_datetime_to_datetimestruct(ordinal, NPY_FR_us, &dts)
+ else:
+ get_date_info(ordinal, freq, &dts)
+
check_dts_bounds(&dts)
return dtstruct_to_dt64(&dts)
diff --git a/pandas/tests/scalar/period/test_asfreq.py b/pandas/tests/scalar/period/test_asfreq.py
index 357274e724c68..436810042186a 100644
--- a/pandas/tests/scalar/period/test_asfreq.py
+++ b/pandas/tests/scalar/period/test_asfreq.py
@@ -3,7 +3,7 @@
from pandas._libs.tslibs.frequencies import INVALID_FREQ_ERR_MSG, _period_code_map
from pandas.errors import OutOfBoundsDatetime
-from pandas import Period, offsets
+from pandas import Period, Timestamp, offsets
class TestFreqConversion:
@@ -656,6 +656,23 @@ def test_conv_secondly(self):
assert ival_S.asfreq("S") == ival_S
+ def test_conv_microsecond(self):
+ # GH#31475 Avoid floating point errors dropping the start_time to
+ # before the beginning of the Period
+ per = Period("2020-01-30 15:57:27.576166", freq="U")
+ assert per.ordinal == 1580399847576166
+
+ start = per.start_time
+ expected = Timestamp("2020-01-30 15:57:27.576166")
+ assert start == expected
+ assert start.value == per.ordinal * 1000
+
+ per2 = Period("2300-01-01", "us")
+ with pytest.raises(OutOfBoundsDatetime, match="2300-01-01"):
+ per2.start_time
+ with pytest.raises(OutOfBoundsDatetime, match="2300-01-01"):
+ per2.end_time
+
def test_asfreq_mult(self):
# normal freq to mult freq
p = Period(freq="A", year=2007)
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/31475 | 2020-01-31T00:19:37Z | 2020-02-04T00:12:17Z | 2020-02-04T00:12:17Z | 2020-02-04T00:13:45Z |
CLN: clean signature in Groupby.add_numeric_operations | diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index aa21aa452be95..8ff04948240ab 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -1359,17 +1359,17 @@ def groupby_function(
@Substitution(name="groupby", f=name)
@Appender(_common_see_also)
@Appender(_local_template)
- def f(self, **kwargs):
- if "numeric_only" not in kwargs:
- kwargs["numeric_only"] = numeric_only
- if "min_count" not in kwargs:
- kwargs["min_count"] = min_count
-
+ def func(self, numeric_only=numeric_only, min_count=min_count):
self._set_group_selection()
# try a cython aggregation if we can
try:
- return self._cython_agg_general(alias, alt=npfunc, **kwargs)
+ return self._cython_agg_general(
+ how=alias,
+ alt=npfunc,
+ numeric_only=numeric_only,
+ min_count=min_count,
+ )
except DataError:
pass
except NotImplementedError as err:
@@ -1384,9 +1384,9 @@ def f(self, **kwargs):
result = self.aggregate(lambda x: npfunc(x, axis=self.axis))
return result
- set_function_name(f, name, cls)
+ set_function_name(func, name, cls)
- return f
+ return func
def first_compat(x, axis=0):
def first(x):
| Avoid **kwars, replace with named parameters. | https://api.github.com/repos/pandas-dev/pandas/pulls/31473 | 2020-01-30T22:33:41Z | 2020-01-31T03:51:26Z | 2020-01-31T03:51:26Z | 2020-02-12T22:13:34Z |
DOC: Fix examples in documentation | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index e2dc543360a62..8cf9f164d140a 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -267,11 +267,6 @@ if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then
-k"-nonzero -reindex -searchsorted -to_dict"
RET=$(($RET + $?)) ; echo $MSG "DONE"
- MSG='Doctests generic.py' ; echo $MSG
- pytest -q --doctest-modules pandas/core/generic.py \
- -k"-_set_axis_name -_xs -describe -groupby -interpolate -pct_change -pipe -reindex -reindex_axis -to_json -transpose -values -xs -to_clipboard"
- RET=$(($RET + $?)) ; echo $MSG "DONE"
-
MSG='Doctests groupby.py' ; echo $MSG
pytest -q --doctest-modules pandas/core/groupby/groupby.py -k"-cumcount -describe -pipe"
RET=$(($RET + $?)) ; echo $MSG "DONE"
@@ -311,6 +306,17 @@ if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then
pytest -q --doctest-modules pandas/core/arrays/boolean.py
RET=$(($RET + $?)) ; echo $MSG "DONE"
+ MSG='Doctests base.py' ; echo $MSG
+ pytest -q --doctest-modules pandas/core/base.py
+ RET=$(($RET + $?)) ; echo $MSG "DONE"
+
+ MSG='Doctests construction.py' ; echo $MSG
+ pytest -q --doctest-modules pandas/core/construction.py
+ RET=$(($RET + $?)) ; echo $MSG "DONE"
+
+ MSG='Doctests generic.py' ; echo $MSG
+ pytest -q --doctest-modules pandas/core/generic.py
+ RET=$(($RET + $?)) ; echo $MSG "DONE"
fi
### DOCSTRINGS ###
diff --git a/pandas/core/base.py b/pandas/core/base.py
index b9aeb32eea5c1..f2b678500a985 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -1480,41 +1480,49 @@ def factorize(self, sort=False, na_sentinel=-1):
Examples
--------
- >>> x = pd.Series([1, 2, 3])
- >>> x
+ >>> ser = pd.Series([1, 2, 3])
+ >>> ser
0 1
1 2
2 3
dtype: int64
- >>> x.searchsorted(4)
+ >>> ser.searchsorted(4)
3
- >>> x.searchsorted([0, 4])
+ >>> ser.searchsorted([0, 4])
array([0, 3])
- >>> x.searchsorted([1, 3], side='left')
+ >>> ser.searchsorted([1, 3], side='left')
array([0, 2])
- >>> x.searchsorted([1, 3], side='right')
+ >>> ser.searchsorted([1, 3], side='right')
array([1, 3])
- >>> x = pd.Categorical(['apple', 'bread', 'bread',
- 'cheese', 'milk'], ordered=True)
+ >>> ser = pd.Categorical(
+ ... ['apple', 'bread', 'bread', 'cheese', 'milk'], ordered=True
+ ... )
+ >>> ser
[apple, bread, bread, cheese, milk]
Categories (4, object): [apple < bread < cheese < milk]
- >>> x.searchsorted('bread')
+ >>> ser.searchsorted('bread')
1
- >>> x.searchsorted(['bread'], side='right')
+ >>> ser.searchsorted(['bread'], side='right')
array([3])
If the values are not monotonically sorted, wrong locations
may be returned:
- >>> x = pd.Series([2, 1, 3])
- >>> x.searchsorted(1)
+ >>> ser = pd.Series([2, 1, 3])
+ >>> ser
+ 0 2
+ 1 1
+ 2 3
+ dtype: int64
+
+ >>> ser.searchsorted(1) # doctest: +SKIP
0 # wrong result, correct would be 1
"""
diff --git a/pandas/core/construction.py b/pandas/core/construction.py
index f947a1fda49f1..e2d8fba8d4148 100644
--- a/pandas/core/construction.py
+++ b/pandas/core/construction.py
@@ -4,6 +4,7 @@
These should not depend on core.internals.
"""
+
from typing import TYPE_CHECKING, Any, Optional, Sequence, Union, cast
import numpy as np
@@ -200,12 +201,12 @@ def array(
>>> pd.array([1, 2, np.nan])
<IntegerArray>
- [1, 2, NaN]
+ [1, 2, <NA>]
Length: 3, dtype: Int64
>>> pd.array(["a", None, "c"])
<StringArray>
- ['a', nan, 'c']
+ ['a', <NA>, 'c']
Length: 3, dtype: string
>>> pd.array([pd.Period('2000', freq="D"), pd.Period("2000", freq="D")])
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index ff7c481d550d4..b03ba2d325db5 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1210,7 +1210,7 @@ def _set_axis_name(self, name, axis=0, inplace=False):
>>> df.index = pd.MultiIndex.from_product(
... [["mammal"], ['dog', 'cat', 'monkey']])
>>> df._set_axis_name(["type", "name"])
- legs
+ num_legs
type name
mammal dog 4
cat 4
@@ -2181,45 +2181,141 @@ def to_json(
Examples
--------
- >>> df = pd.DataFrame([['a', 'b'], ['c', 'd']],
- ... index=['row 1', 'row 2'],
- ... columns=['col 1', 'col 2'])
- >>> df.to_json(orient='split')
- '{"columns":["col 1","col 2"],
- "index":["row 1","row 2"],
- "data":[["a","b"],["c","d"]]}'
+ >>> import json
+ >>> df = pd.DataFrame(
+ ... [["a", "b"], ["c", "d"]],
+ ... index=["row 1", "row 2"],
+ ... columns=["col 1", "col 2"],
+ ... )
+
+ >>> result = df.to_json(orient="split")
+ >>> parsed = json.loads(result)
+ >>> json.dumps(parsed, indent=4) # doctest: +SKIP
+ {
+ "columns": [
+ "col 1",
+ "col 2"
+ ],
+ "index": [
+ "row 1",
+ "row 2"
+ ],
+ "data": [
+ [
+ "a",
+ "b"
+ ],
+ [
+ "c",
+ "d"
+ ]
+ ]
+ }
Encoding/decoding a Dataframe using ``'records'`` formatted JSON.
Note that index labels are not preserved with this encoding.
- >>> df.to_json(orient='records')
- '[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]'
+ >>> result = df.to_json(orient="records")
+ >>> parsed = json.loads(result)
+ >>> json.dumps(parsed, indent=4) # doctest: +SKIP
+ [
+ {
+ "col 1": "a",
+ "col 2": "b"
+ },
+ {
+ "col 1": "c",
+ "col 2": "d"
+ }
+ ]
Encoding/decoding a Dataframe using ``'index'`` formatted JSON:
- >>> df.to_json(orient='index')
- '{"row 1":{"col 1":"a","col 2":"b"},"row 2":{"col 1":"c","col 2":"d"}}'
+ >>> result = df.to_json(orient="index")
+ >>> parsed = json.loads(result)
+ >>> json.dumps(parsed, indent=4) # doctest: +SKIP
+ {
+ "row 1": {
+ "col 1": "a",
+ "col 2": "b"
+ },
+ "row 2": {
+ "col 1": "c",
+ "col 2": "d"
+ }
+ }
Encoding/decoding a Dataframe using ``'columns'`` formatted JSON:
- >>> df.to_json(orient='columns')
- '{"col 1":{"row 1":"a","row 2":"c"},"col 2":{"row 1":"b","row 2":"d"}}'
+ >>> result = df.to_json(orient="columns")
+ >>> parsed = json.loads(result)
+ >>> json.dumps(parsed, indent=4) # doctest: +SKIP
+ {
+ "col 1": {
+ "row 1": "a",
+ "row 2": "c"
+ },
+ "col 2": {
+ "row 1": "b",
+ "row 2": "d"
+ }
+ }
Encoding/decoding a Dataframe using ``'values'`` formatted JSON:
- >>> df.to_json(orient='values')
- '[["a","b"],["c","d"]]'
-
- Encoding with Table Schema
+ >>> result = df.to_json(orient="values")
+ >>> parsed = json.loads(result)
+ >>> json.dumps(parsed, indent=4) # doctest: +SKIP
+ [
+ [
+ "a",
+ "b"
+ ],
+ [
+ "c",
+ "d"
+ ]
+ ]
- >>> df.to_json(orient='table')
- '{"schema": {"fields": [{"name": "index", "type": "string"},
- {"name": "col 1", "type": "string"},
- {"name": "col 2", "type": "string"}],
- "primaryKey": "index",
- "pandas_version": "0.20.0"},
- "data": [{"index": "row 1", "col 1": "a", "col 2": "b"},
- {"index": "row 2", "col 1": "c", "col 2": "d"}]}'
+ Encoding with Table Schema:
+
+ >>> result = df.to_json(orient="table")
+ >>> parsed = json.loads(result)
+ >>> json.dumps(parsed, indent=4) # doctest: +SKIP
+ {
+ "schema": {
+ "fields": [
+ {
+ "name": "index",
+ "type": "string"
+ },
+ {
+ "name": "col 1",
+ "type": "string"
+ },
+ {
+ "name": "col 2",
+ "type": "string"
+ }
+ ],
+ "primaryKey": [
+ "index"
+ ],
+ "pandas_version": "0.20.0"
+ },
+ "data": [
+ {
+ "index": "row 1",
+ "col 1": "a",
+ "col 2": "b"
+ },
+ {
+ "index": "row 2",
+ "col 1": "c",
+ "col 2": "d"
+ }
+ ]
+ }
"""
from pandas.io import json
@@ -2646,7 +2742,8 @@ def to_clipboard(
Copy the contents of a DataFrame to the clipboard.
>>> df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['A', 'B', 'C'])
- >>> df.to_clipboard(sep=',')
+
+ >>> df.to_clipboard(sep=',') # doctest: +SKIP
... # Wrote the following to the system clipboard:
... # ,A,B,C
... # 0,1,2,3
@@ -2655,7 +2752,7 @@ def to_clipboard(
We can omit the index by passing the keyword `index` and setting
it to false.
- >>> df.to_clipboard(sep=',', index=False)
+ >>> df.to_clipboard(sep=',', index=False) # doctest: +SKIP
... # Wrote the following to the system clipboard:
... # A,B,C
... # 1,2,3
@@ -4887,18 +4984,17 @@ def sample(
Notes
-----
-
Use ``.pipe`` when chaining together functions that expect
Series, DataFrames or GroupBy objects. Instead of writing
- >>> f(g(h(df), arg1=a), arg2=b, arg3=c)
+ >>> func(g(h(df), arg1=a), arg2=b, arg3=c) # doctest: +SKIP
You can write
>>> (df.pipe(h)
... .pipe(g, arg1=a)
- ... .pipe(f, arg2=b, arg3=c)
- ... )
+ ... .pipe(func, arg2=b, arg3=c)
+ ... ) # doctest: +SKIP
If you have a function that takes the data as (say) the second
argument, pass a tuple indicating which keyword expects the
@@ -4906,8 +5002,8 @@ def sample(
>>> (df.pipe(h)
... .pipe(g, arg1=a)
- ... .pipe((f, 'arg2'), arg1=a, arg3=c)
- ... )
+ ... .pipe((func, 'arg2'), arg1=a, arg3=c)
+ ... ) # doctest: +SKIP
"""
@Appender(_shared_docs["pipe"] % _shared_doc_kwargs)
@@ -5256,7 +5352,7 @@ def values(self) -> np.ndarray:
dtype: object
>>> df.values
array([[ 3, 94, 31],
- [ 29, 170, 115]], dtype=int64)
+ [ 29, 170, 115]])
A DataFrame with mixed type columns(e.g., str/object, int64, float32)
results in an ndarray of the broadest type that accommodates these
@@ -9511,12 +9607,13 @@ def describe(
... np.datetime64("2010-01-01")
... ])
>>> s.describe()
- count 3
- unique 2
- top 2010-01-01 00:00:00
- freq 2
- first 2000-01-01 00:00:00
- last 2010-01-01 00:00:00
+ count 3
+ mean 2006-09-01 08:00:00
+ min 2000-01-01 00:00:00
+ 25% 2004-12-31 12:00:00
+ 50% 2010-01-01 00:00:00
+ 75% 2010-01-01 00:00:00
+ max 2010-01-01 00:00:00
dtype: object
Describing a ``DataFrame``. By default only numeric fields
@@ -9539,11 +9636,11 @@ def describe(
Describing all columns of a ``DataFrame`` regardless of data type.
- >>> df.describe(include='all')
- categorical numeric object
+ >>> df.describe(include='all') # doctest: +SKIP
+ categorical numeric object
count 3 3.0 3
unique 3 NaN 3
- top f NaN c
+ top f NaN a
freq 1 NaN 1
mean NaN 2.0 NaN
std NaN 1.0 NaN
@@ -9582,11 +9679,11 @@ def describe(
Including only string columns in a ``DataFrame`` description.
- >>> df.describe(include=[np.object])
+ >>> df.describe(include=[np.object]) # doctest: +SKIP
object
count 3
unique 3
- top c
+ top a
freq 1
Including only categorical columns from a ``DataFrame`` description.
@@ -9600,16 +9697,16 @@ def describe(
Excluding numeric columns from a ``DataFrame`` description.
- >>> df.describe(exclude=[np.number])
+ >>> df.describe(exclude=[np.number]) # doctest: +SKIP
categorical object
count 3 3
unique 3 3
- top f c
+ top f a
freq 1 1
Excluding object columns from a ``DataFrame`` description.
- >>> df.describe(exclude=[np.object])
+ >>> df.describe(exclude=[np.object]) # doctest: +SKIP
categorical numeric
count 3 3.0
unique 3 NaN
| - [ ] 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/31472 | 2020-01-30T20:36:31Z | 2020-03-07T20:10:21Z | 2020-03-07T20:10:21Z | 2020-03-14T14:05:25Z |
REF: use inherit_names for DTI | diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index 3afd1ff35806d..ca0ccf857276a 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -20,7 +20,6 @@
from pandas.core.dtypes.dtypes import DatetimeTZDtype
from pandas.core.dtypes.missing import is_valid_nat_for_dtype
-from pandas.core.accessor import delegate_names
from pandas.core.arrays.datetimes import (
DatetimeArray,
tz_to_dtype,
@@ -28,10 +27,7 @@
)
import pandas.core.common as com
from pandas.core.indexes.base import Index, InvalidIndexError, maybe_extract_name
-from pandas.core.indexes.datetimelike import (
- DatetimelikeDelegateMixin,
- DatetimeTimedeltaMixin,
-)
+from pandas.core.indexes.datetimelike import DatetimeTimedeltaMixin
from pandas.core.indexes.extension import inherit_names
from pandas.core.ops import get_op_result_name
import pandas.core.tools.datetimes as tools
@@ -59,32 +55,13 @@ def _new_DatetimeIndex(cls, d):
return result
-class DatetimeDelegateMixin(DatetimelikeDelegateMixin):
- # Most attrs are dispatched via datetimelike_{ops,methods}
- # Some are "raw" methods, the result is not not re-boxed in an Index
- # We also have a few "extra" attrs, which may or may not be raw,
- # which we we dont' want to expose in the .dt accessor.
- _extra_methods = ["to_period", "to_perioddelta", "to_julian_date", "strftime"]
- _extra_raw_methods = [
- "to_pydatetime",
- "_local_timestamps",
- "_has_same_tz",
- "_format_native_types",
- "__iter__",
- ]
- _extra_raw_properties = ["_box_func", "tz", "tzinfo", "dtype"]
- _delegated_properties = DatetimeArray._datetimelike_ops + _extra_raw_properties
- _delegated_methods = (
- DatetimeArray._datetimelike_methods + _extra_methods + _extra_raw_methods
- )
- _raw_properties = (
- {"date", "time", "timetz"}
- | set(DatetimeArray._bool_ops)
- | set(_extra_raw_properties)
- )
- _raw_methods = set(_extra_raw_methods)
-
-
+@inherit_names(
+ ["to_period", "to_perioddelta", "to_julian_date", "strftime"]
+ + DatetimeArray._field_ops
+ + DatetimeArray._datetimelike_methods,
+ DatetimeArray,
+ wrap=True,
+)
@inherit_names(["_timezone", "is_normalized", "_resolution"], DatetimeArray, cache=True)
@inherit_names(
[
@@ -93,19 +70,22 @@ class DatetimeDelegateMixin(DatetimelikeDelegateMixin):
"_field_ops",
"_datetimelike_ops",
"_datetimelike_methods",
- ],
- DatetimeArray,
-)
-@delegate_names(
- DatetimeArray, DatetimeDelegateMixin._delegated_properties, typ="property"
-)
-@delegate_names(
+ "_box_func",
+ "tz",
+ "tzinfo",
+ "dtype",
+ "to_pydatetime",
+ "_local_timestamps",
+ "_has_same_tz",
+ "_format_native_types",
+ "date",
+ "time",
+ "timetz",
+ ]
+ + DatetimeArray._bool_ops,
DatetimeArray,
- DatetimeDelegateMixin._delegated_methods,
- typ="method",
- overwrite=True,
)
-class DatetimeIndex(DatetimeTimedeltaMixin, DatetimeDelegateMixin):
+class DatetimeIndex(DatetimeTimedeltaMixin):
"""
Immutable ndarray of datetime64 data, represented internally as int64, and
which can be boxed to Timestamp objects that are subclasses of datetime and
| xref #31427, #31433. With all three of these in, we can then remove indexes.datetimelike.DatetimelikeDelegateMixin
Using inherit_names, we also have the option of making tz, tzinfo, dtype cache_readonly if that turns out to make a difference. | https://api.github.com/repos/pandas-dev/pandas/pulls/31468 | 2020-01-30T18:13:38Z | 2020-01-31T03:09:34Z | 2020-01-31T03:09:34Z | 2020-01-31T04:19:20Z |
Some code cleanups | diff --git a/pandas/core/base.py b/pandas/core/base.py
index 05e3302abddbe..9fe1af776dd2b 100644
--- a/pandas/core/base.py
+++ b/pandas/core/base.py
@@ -1,6 +1,7 @@
"""
Base and utility classes for pandas objects.
"""
+
import builtins
import textwrap
from typing import Dict, FrozenSet, List, Optional, Union
@@ -45,11 +46,15 @@
class PandasObject(DirNamesMixin):
- """baseclass for various pandas objects"""
+ """
+ Baseclass for various pandas objects.
+ """
@property
def _constructor(self):
- """class constructor (for this class it's just `__class__`"""
+ """
+ Class constructor (for this class it's just `__class__`.
+ """
return type(self)
def __repr__(self) -> str:
@@ -77,16 +82,14 @@ def __sizeof__(self):
"""
if hasattr(self, "memory_usage"):
mem = self.memory_usage(deep=True)
- if not is_scalar(mem):
- mem = mem.sum()
- return int(mem)
+ return int(mem if is_scalar(mem) else mem.sum())
- # no memory_usage attribute, so fall back to
- # object's 'sizeof'
+ # no memory_usage attribute, so fall back to object's 'sizeof'
return super().__sizeof__()
def _ensure_type(self: T, obj) -> T:
- """Ensure that an object has same type as self.
+ """
+ Ensure that an object has same type as self.
Used by type checkers.
"""
@@ -95,7 +98,8 @@ def _ensure_type(self: T, obj) -> T:
class NoNewAttributesMixin:
- """Mixin which prevents adding new attributes.
+ """
+ Mixin which prevents adding new attributes.
Prevents additional attributes via xxx.attribute = "something" after a
call to `self.__freeze()`. Mainly used to prevent the user from using
@@ -106,7 +110,9 @@ class NoNewAttributesMixin:
"""
def _freeze(self):
- """Prevents setting additional attributes"""
+ """
+ Prevents setting additional attributes.
+ """
object.__setattr__(self, "__frozen", True)
# prevent adding any attribute via s.xxx.new_attribute = ...
@@ -180,14 +186,12 @@ class SelectionMixin:
@property
def _selection_name(self):
"""
- return a name for myself; this would ideally be called
- the 'name' property, but we cannot conflict with the
- Series.name property which can be set
+ Return a name for myself;
+
+ This would ideally be called the 'name' property,
+ but we cannot conflict with the Series.name property which can be set.
"""
- if self._selection is None:
- return None # 'result'
- else:
- return self._selection
+ return self._selection
@property
def _selection_list(self):
@@ -199,7 +203,6 @@ def _selection_list(self):
@cache_readonly
def _selected_obj(self):
-
if self._selection is None or isinstance(self.obj, ABCSeries):
return self.obj
else:
@@ -246,12 +249,11 @@ def _gotitem(self, key, ndim: int, subset=None):
Parameters
----------
- key : string / list of selections
+ key : str / list of selections
ndim : 1,2
requested ndim of result
subset : object, default None
subset to act on
-
"""
raise AbstractMethodError(self)
@@ -266,7 +268,6 @@ def _try_aggregate_string_function(self, arg: str, *args, **kwargs):
- try to find a function (or attribute) on ourselves
- try to find a numpy function
- raise
-
"""
assert isinstance(arg, str)
@@ -585,7 +586,6 @@ def _shallow_copy(self, obj, **kwargs):
"""
return a new object with the replacement attributes
"""
-
if isinstance(obj, self._constructor):
obj = obj.obj
for attr in self._attributes:
@@ -669,8 +669,7 @@ def item(self):
if len(self) == 1:
return next(iter(self))
- else:
- raise ValueError("can only convert an array of size 1 to a Python scalar")
+ raise ValueError("can only convert an array of size 1 to a Python scalar")
@property
def nbytes(self) -> int:
@@ -735,7 +734,6 @@ def array(self) -> ExtensionArray:
Examples
--------
-
For regular NumPy types like int, and float, a PandasArray
is returned.
@@ -851,12 +849,11 @@ def to_numpy(self, dtype=None, copy=False, na_value=lib.no_default, **kwargs):
"""
if is_extension_array_dtype(self.dtype):
return self.array.to_numpy(dtype, copy=copy, na_value=na_value, **kwargs)
- else:
- if kwargs:
- msg = "to_numpy() got an unexpected keyword argument '{}'".format(
- list(kwargs.keys())[0]
- )
- raise TypeError(msg)
+ elif kwargs:
+ bad_keys = list(kwargs.keys())[0]
+ raise TypeError(
+ f"to_numpy() got an unexpected keyword argument '{bad_keys}'"
+ )
result = np.asarray(self._values, dtype=dtype)
# TODO(GH-24345): Avoid potential double copy
@@ -1076,7 +1073,9 @@ def _reduce(
filter_type=None,
**kwds,
):
- """ perform the reduction type operation if we can """
+ """
+ Perform the reduction type operation if we can.
+ """
func = getattr(self, name, None)
if func is None:
raise TypeError(
@@ -1103,9 +1102,7 @@ def _map_values(self, mapper, na_action=None):
The output of the mapping function applied to the index.
If the function returns a tuple with more than one element
a MultiIndex will be returned.
-
"""
-
# we can fastpath dict/Series to an efficient map
# as we know that we are not going to have to yield
# python types
@@ -1341,7 +1338,9 @@ def is_monotonic(self) -> bool:
@property
def is_monotonic_increasing(self) -> bool:
- """alias for is_monotonic"""
+ """
+ Alias for is_monotonic.
+ """
# mypy complains if we alias directly
return self.is_monotonic
@@ -1455,7 +1454,6 @@ def factorize(self, sort=False, na_sentinel=-1):
Examples
--------
-
>>> x = pd.Series([1, 2, 3])
>>> x
0 1
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index f3a0cf3841b5b..5016dff4d7efa 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -874,8 +874,8 @@ def style(self) -> "Styler":
polar bear 22000
koala marsupial 80000
>>> for label, content in df.items():
- ... print('label:', label)
- ... print('content:', content, sep='\n')
+ ... print(f'label: {label}')
+ ... print(f'content: {content}', sep='\n')
...
label: species
content:
diff --git a/pandas/io/excel/_pyxlsb.py b/pandas/io/excel/_pyxlsb.py
index df6a38000452d..0d96c8c4acdb8 100644
--- a/pandas/io/excel/_pyxlsb.py
+++ b/pandas/io/excel/_pyxlsb.py
@@ -8,11 +8,12 @@
class _PyxlsbReader(_BaseExcelReader):
def __init__(self, filepath_or_buffer: FilePathOrBuffer):
- """Reader using pyxlsb engine.
+ """
+ Reader using pyxlsb engine.
Parameters
- __________
- filepath_or_buffer: string, path object, or Workbook
+ ----------
+ filepath_or_buffer: str, path object, or Workbook
Object to be parsed.
"""
import_optional_dependency("pyxlsb")
@@ -29,7 +30,7 @@ def _workbook_class(self):
def load_workbook(self, filepath_or_buffer: FilePathOrBuffer):
from pyxlsb import open_workbook
- # Todo: hack in buffer capability
+ # TODO: hack in buffer capability
# This might need some modifications to the Pyxlsb library
# Actual work for opening it is in xlsbpackage.py, line 20-ish
@@ -48,7 +49,7 @@ def get_sheet_by_index(self, index: int):
return self.book.get_sheet(index + 1)
def _convert_cell(self, cell, convert_float: bool) -> Scalar:
- # Todo: there is no way to distinguish between floats and datetimes in pyxlsb
+ # TODO: there is no way to distinguish between floats and datetimes in pyxlsb
# This means that there is no way to read datetime types from an xlsb file yet
if cell.v is None:
return "" # Prevents non-named columns from not showing up as Unnamed: i
diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py
index d8804994af426..cd7fdd55a4d2c 100644
--- a/pandas/util/_test_decorators.py
+++ b/pandas/util/_test_decorators.py
@@ -77,8 +77,8 @@ def safe_import(mod_name: str, min_version: Optional[str] = None):
# TODO:
-# remove when gh-24839 is fixed; this affects numpy 1.16
-# and pytables 3.4.4
+# remove when gh-24839 is fixed.
+# this affects numpy 1.16 and pytables 3.4.4
tables = safe_import("tables")
xfail_non_writeable = pytest.mark.xfail(
tables
@@ -86,7 +86,7 @@ def safe_import(mod_name: str, min_version: Optional[str] = None):
and LooseVersion(tables.__version__) < LooseVersion("3.5.1"),
reason=(
"gh-25511, gh-24839. pytables needs a "
- "release beyong 3.4.4 to support numpy 1.16x"
+ "release beyond 3.4.4 to support numpy 1.16.x"
),
)
| - [ ] 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/31462 | 2020-01-30T16:30:24Z | 2020-01-31T03:12:02Z | 2020-01-31T03:12:02Z | 2020-01-31T16:26:35Z |
DOC: Fix DataFrame.to_csv example | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index a2e348bf98e33..af3c3cce8fec4 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -3077,10 +3077,10 @@ def to_csv(
>>> df.to_csv(index=False)
'name,mask,weapon\nRaphael,red,sai\nDonatello,purple,bo staff\n'
- # create 'out.zip' containing 'out.csv'
+ Create 'out.zip' containing 'out.csv'
+
>>> compression_opts = dict(method='zip',
... archive_name='out.csv') # doctest: +SKIP
-
>>> df.to_csv('out.zip', index=False,
... compression=compression_opts) # doctest: +SKIP
"""
| - [x] closes #31460
- [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/31461 | 2020-01-30T16:11:16Z | 2020-01-31T07:19:58Z | 2020-01-31T07:19:57Z | 2020-01-31T07:19:58Z |
Fix to_csv and to_excel links on read_csv, read_table and read_excel See Also docs | diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py
index 2a91381b7fbeb..5ad56e30eeb39 100644
--- a/pandas/io/excel/_base.py
+++ b/pandas/io/excel/_base.py
@@ -205,8 +205,8 @@
See Also
--------
-to_excel : Write DataFrame to an Excel file.
-to_csv : Write DataFrame to a comma-separated values (csv) file.
+DataFrame.to_excel : Write DataFrame to an Excel file.
+DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file.
read_csv : Read a comma-separated values (csv) file into DataFrame.
read_fwf : Read a table of fixed-width formatted lines into DataFrame.
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index 84a8b5b2a94fe..a33d81ff437bf 100755
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -353,7 +353,7 @@
See Also
--------
-to_csv : Write DataFrame to a comma-separated values (csv) file.
+DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file.
read_csv : Read a comma-separated values (csv) file into DataFrame.
read_fwf : Read a table of fixed-width formatted lines into DataFrame.
@@ -754,7 +754,7 @@ def read_fwf(
See Also
--------
- to_csv : Write DataFrame to a comma-separated values (csv) file.
+ DataFrame.to_csv : Write DataFrame to a comma-separated values (csv) file.
read_csv : Read a comma-separated values (csv) file into DataFrame.
Examples
| - [x] closes #31448
- [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/31458 | 2020-01-30T15:33:43Z | 2020-01-31T12:08:38Z | 2020-01-31T12:08:37Z | 2020-01-31T12:08:47Z |
BUG: Groupby.apply wasn't allowing for functions which return lists | diff --git a/doc/source/whatsnew/v1.0.1.rst b/doc/source/whatsnew/v1.0.1.rst
index ff8433c7cafd9..ce0634c879b93 100644
--- a/doc/source/whatsnew/v1.0.1.rst
+++ b/doc/source/whatsnew/v1.0.1.rst
@@ -15,7 +15,7 @@ including other versions of pandas.
Bug fixes
~~~~~~~~~
-
+- Bug in :meth:`GroupBy.apply` was raising ``TypeError`` if called with function which returned a non-pandas non-scalar object (e.g. a list) (:issue:`31441`)
Categorical
^^^^^^^^^^^
diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx
index 8571761f77265..89164c527002a 100644
--- a/pandas/_libs/reduction.pyx
+++ b/pandas/_libs/reduction.pyx
@@ -501,9 +501,9 @@ def apply_frame_axis0(object frame, object f, object names,
if not is_scalar(piece):
# Need to copy data to avoid appending references
- if hasattr(piece, "copy"):
+ try:
piece = piece.copy(deep="all")
- else:
+ except (TypeError, AttributeError):
piece = copy(piece)
results.append(piece)
diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py
index c18ef73203914..9c2b045079622 100644
--- a/pandas/tests/groupby/test_apply.py
+++ b/pandas/tests/groupby/test_apply.py
@@ -827,3 +827,27 @@ def test_apply_index_has_complex_internals(index):
df = DataFrame({"group": [1, 1, 2], "value": [0, 1, 0]}, index=index)
result = df.groupby("group").apply(lambda x: x)
tm.assert_frame_equal(result, df)
+
+
+@pytest.mark.parametrize(
+ "function, expected_values",
+ [
+ (lambda x: x.index.to_list(), [[0, 1], [2, 3]]),
+ (lambda x: set(x.index.to_list()), [{0, 1}, {2, 3}]),
+ (lambda x: tuple(x.index.to_list()), [(0, 1), (2, 3)]),
+ (
+ lambda x: {n: i for (n, i) in enumerate(x.index.to_list())},
+ [{0: 0, 1: 1}, {0: 2, 1: 3}],
+ ),
+ (
+ lambda x: [{n: i} for (n, i) in enumerate(x.index.to_list())],
+ [[{0: 0}, {1: 1}], [{0: 2}, {1: 3}]],
+ ),
+ ],
+)
+def test_apply_function_returns_non_pandas_non_scalar(function, expected_values):
+ # GH 31441
+ df = pd.DataFrame(["A", "A", "B", "B"], columns=["groups"])
+ result = df.groupby("groups").apply(function)
+ expected = pd.Series(expected_values, index=pd.Index(["A", "B"], name="groups"))
+ tm.assert_series_equal(result, expected)
| - [ ] closes #31441
- [ ] 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/31456 | 2020-01-30T15:07:16Z | 2020-02-01T15:14:52Z | 2020-02-01T15:14:52Z | 2020-02-25T17:12:23Z |
DOC: Fixed example section in pandas/core/dtypes/*.py | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index b46989894ae12..fdc9fef5d7f77 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -305,6 +305,10 @@ if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then
pandas/core/arrays/boolean.py
RET=$(($RET + $?)) ; echo $MSG "DONE"
+ MSG='Doctests dtypes'; echo $MSG
+ pytest -q --doctest-modules pandas/core/dtypes/
+ RET=$(($RET + $?)) ; echo $MSG "DONE"
+
MSG='Doctests arrays/boolean.py' ; echo $MSG
pytest -q --doctest-modules pandas/core/arrays/boolean.py
RET=$(($RET + $?)) ; echo $MSG "DONE"
diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py
index eddf46ee362d6..618a35886a905 100644
--- a/pandas/core/dtypes/base.py
+++ b/pandas/core/dtypes/base.py
@@ -1,4 +1,7 @@
-"""Extend pandas with custom array types"""
+"""
+Extend pandas with custom array types.
+"""
+
from typing import Any, List, Optional, Tuple, Type
import numpy as np
@@ -231,8 +234,9 @@ def construct_from_string(cls, string: str):
... if match:
... return cls(**match.groupdict())
... else:
- ... raise TypeError(f"Cannot construct a '{cls.__name__}' from
- ... " "'{string}'")
+ ... raise TypeError(
+ ... f"Cannot construct a '{cls.__name__}' from '{string}'"
+ ... )
"""
if not isinstance(string, str):
raise TypeError(
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 0719b8ce6010b..6120bc92adbfc 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -1,4 +1,6 @@
-""" routings for casting """
+"""
+Routines for casting.
+"""
from datetime import date, datetime, timedelta
@@ -269,12 +271,12 @@ def maybe_upcast_putmask(result: np.ndarray, mask: np.ndarray, other):
Examples
--------
- >>> result, _ = maybe_upcast_putmask(np.arange(1,6),
- np.array([False, True, False, True, True]), np.arange(21,23))
+ >>> arr = np.arange(1, 6)
+ >>> mask = np.array([False, True, False, True, True])
+ >>> result, _ = maybe_upcast_putmask(arr, mask, False)
>>> result
- array([1, 21, 3, 22, 21])
+ array([1, 0, 3, 0, 0])
"""
-
if not isinstance(result, np.ndarray):
raise ValueError("The result input must be a ndarray.")
if not is_scalar(other):
@@ -662,9 +664,8 @@ def infer_dtype_from_array(arr, pandas_dtype: bool = False):
array(['1', '1'], dtype='<U21')
>>> infer_dtype_from_array([1, '1'])
- (numpy.object_, [1, '1'])
+ (<class 'numpy.object_'>, [1, '1'])
"""
-
if isinstance(arr, np.ndarray):
return arr.dtype, arr
@@ -709,7 +710,7 @@ def maybe_infer_dtype_type(element):
>>> from collections import namedtuple
>>> Foo = namedtuple("Foo", "dtype")
>>> maybe_infer_dtype_type(Foo(np.dtype("i8")))
- numpy.int64
+ dtype('int64')
"""
tipo = None
if hasattr(element, "dtype"):
@@ -1555,8 +1556,8 @@ def maybe_cast_to_integer_array(arr, dtype, copy: bool = False):
Returns
-------
- int_arr : ndarray
- An array of integer or unsigned integer dtype
+ ndarray
+ Array of integer or unsigned integer dtype.
Raises
------
@@ -1567,19 +1568,18 @@ def maybe_cast_to_integer_array(arr, dtype, copy: bool = False):
--------
If you try to coerce negative values to unsigned integers, it raises:
- >>> Series([-1], dtype="uint64")
+ >>> pd.Series([-1], dtype="uint64")
Traceback (most recent call last):
...
OverflowError: Trying to coerce negative values to unsigned integers
Also, if you try to coerce float values to integers, it raises:
- >>> Series([1, 2, 3.5], dtype="int64")
+ >>> pd.Series([1, 2, 3.5], dtype="int64")
Traceback (most recent call last):
...
ValueError: Trying to coerce float values to integers
"""
-
try:
if not hasattr(arr, "astype"):
casted = np.array(arr, dtype=dtype, copy=copy)
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index eb9b880cd10d9..f8e14d1cbc9e9 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -1,4 +1,7 @@
-""" common type operations """
+"""
+Common type operations.
+"""
+
from typing import Any, Callable, Union
import warnings
@@ -705,7 +708,7 @@ def is_dtype_equal(source, target) -> bool:
False
>>> is_dtype_equal(CategoricalDtype(), "category")
True
- >>> is_dtype_equal(DatetimeTZDtype(), "datetime64")
+ >>> is_dtype_equal(DatetimeTZDtype(tz="UTC"), "datetime64")
False
"""
@@ -862,7 +865,7 @@ def is_signed_integer_dtype(arr_or_dtype) -> bool:
True
>>> is_signed_integer_dtype('Int8')
True
- >>> is_signed_dtype(pd.Int8Dtype)
+ >>> is_signed_integer_dtype(pd.Int8Dtype)
True
>>> is_signed_integer_dtype(np.datetime64)
False
@@ -994,7 +997,7 @@ def is_datetime64_any_dtype(arr_or_dtype) -> bool:
Returns
-------
- boolean
+ bool
Whether or not the array or dtype is of the datetime64 dtype.
Examples
@@ -1011,13 +1014,11 @@ def is_datetime64_any_dtype(arr_or_dtype) -> bool:
False
>>> is_datetime64_any_dtype(np.array([1, 2]))
False
- >>> is_datetime64_any_dtype(np.array([], dtype=np.datetime64))
+ >>> is_datetime64_any_dtype(np.array([], dtype="datetime64[ns]"))
True
- >>> is_datetime64_any_dtype(pd.DatetimeIndex([1, 2, 3],
- dtype=np.datetime64))
+ >>> is_datetime64_any_dtype(pd.DatetimeIndex([1, 2, 3], dtype="datetime64[ns]"))
True
"""
-
if arr_or_dtype is None:
return False
return is_datetime64_dtype(arr_or_dtype) or is_datetime64tz_dtype(arr_or_dtype)
@@ -1034,7 +1035,7 @@ def is_datetime64_ns_dtype(arr_or_dtype) -> bool:
Returns
-------
- boolean
+ bool
Whether or not the array or dtype is of the datetime64[ns] dtype.
Examples
@@ -1051,16 +1052,13 @@ def is_datetime64_ns_dtype(arr_or_dtype) -> bool:
False
>>> is_datetime64_ns_dtype(np.array([1, 2]))
False
- >>> is_datetime64_ns_dtype(np.array([], dtype=np.datetime64)) # no unit
+ >>> is_datetime64_ns_dtype(np.array([], dtype="datetime64")) # no unit
False
- >>> is_datetime64_ns_dtype(np.array([],
- dtype="datetime64[ps]")) # wrong unit
+ >>> is_datetime64_ns_dtype(np.array([], dtype="datetime64[ps]")) # wrong unit
False
- >>> is_datetime64_ns_dtype(pd.DatetimeIndex([1, 2, 3],
- dtype=np.datetime64)) # has 'ns' unit
+ >>> is_datetime64_ns_dtype(pd.DatetimeIndex([1, 2, 3], dtype="datetime64[ns]"))
True
"""
-
if arr_or_dtype is None:
return False
try:
@@ -1240,7 +1238,8 @@ def is_datetimelike_v_numeric(a, b):
Examples
--------
- >>> dt = np.datetime64(pd.datetime(2017, 1, 1))
+ >>> from datetime import datetime
+ >>> dt = np.datetime64(datetime(2017, 1, 1))
>>>
>>> is_datetimelike_v_numeric(1, 1)
False
diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py
index cd4b5af4588e5..fdc2eeb34b4ed 100644
--- a/pandas/core/dtypes/concat.py
+++ b/pandas/core/dtypes/concat.py
@@ -1,5 +1,5 @@
"""
-Utility functions related to concat
+Utility functions related to concat.
"""
import numpy as np
@@ -261,6 +261,8 @@ def union_categoricals(
>>> a = pd.Categorical(["a", "b"], ordered=True)
>>> b = pd.Categorical(["a", "b", "c"], ordered=True)
>>> union_categoricals([a, b])
+ Traceback (most recent call last):
+ ...
TypeError: to union ordered Categoricals, all categories must be the same
New in version 0.20.0
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index d00b46700981c..8aaebe89871b6 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -1,4 +1,7 @@
-""" define extension dtypes """
+"""
+Define extension dtypes.
+"""
+
import re
from typing import Any, Dict, List, MutableMapping, Optional, Tuple, Type, Union, cast
@@ -286,23 +289,27 @@ def _from_values_or_dtype(
Examples
--------
- >>> CategoricalDtype._from_values_or_dtype()
+ >>> pd.CategoricalDtype._from_values_or_dtype()
CategoricalDtype(categories=None, ordered=None)
- >>> CategoricalDtype._from_values_or_dtype(categories=['a', 'b'],
- ... ordered=True)
+ >>> pd.CategoricalDtype._from_values_or_dtype(
+ ... categories=['a', 'b'], ordered=True
+ ... )
CategoricalDtype(categories=['a', 'b'], ordered=True)
- >>> dtype1 = CategoricalDtype(['a', 'b'], ordered=True)
- >>> dtype2 = CategoricalDtype(['x', 'y'], ordered=False)
- >>> c = Categorical([0, 1], dtype=dtype1, fastpath=True)
- >>> CategoricalDtype._from_values_or_dtype(c, ['x', 'y'], ordered=True,
- ... dtype=dtype2)
+ >>> dtype1 = pd.CategoricalDtype(['a', 'b'], ordered=True)
+ >>> dtype2 = pd.CategoricalDtype(['x', 'y'], ordered=False)
+ >>> c = pd.Categorical([0, 1], dtype=dtype1, fastpath=True)
+ >>> pd.CategoricalDtype._from_values_or_dtype(
+ ... c, ['x', 'y'], ordered=True, dtype=dtype2
+ ... )
+ Traceback (most recent call last):
+ ...
ValueError: Cannot specify `categories` or `ordered` together with
`dtype`.
The supplied dtype takes precedence over values' dtype:
- >>> CategoricalDtype._from_values_or_dtype(c, dtype=dtype2)
- CategoricalDtype(['x', 'y'], ordered=False)
+ >>> pd.CategoricalDtype._from_values_or_dtype(c, dtype=dtype2)
+ CategoricalDtype(categories=['x', 'y'], ordered=False)
"""
from pandas.core.dtypes.common import is_categorical
diff --git a/pandas/core/dtypes/inference.py b/pandas/core/dtypes/inference.py
index 37bca76802843..a9cd696633273 100644
--- a/pandas/core/dtypes/inference.py
+++ b/pandas/core/dtypes/inference.py
@@ -117,7 +117,8 @@ def is_file_like(obj) -> bool:
Examples
--------
- >>> buffer(StringIO("data"))
+ >>> import io
+ >>> buffer = io.StringIO("data")
>>> is_file_like(buffer)
True
>>> is_file_like([1, 2, 3])
@@ -311,6 +312,7 @@ def is_named_tuple(obj) -> bool:
Examples
--------
+ >>> from collections import namedtuple
>>> Point = namedtuple("Point", ["x", "y"])
>>> p = Point(1, 2)
>>>
@@ -339,6 +341,7 @@ def is_hashable(obj) -> bool:
Examples
--------
+ >>> import collections
>>> a = ([],)
>>> isinstance(a, collections.abc.Hashable)
True
| - [ ] 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/31451 | 2020-01-30T13:36:49Z | 2020-02-10T09:13:13Z | 2020-02-10T09:13:12Z | 2020-03-19T23:29:34Z |
Backport PR #30907 on branch 1.0.x (DOC: add 1.0.1 whatsnew file) | diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst
index 05c7f72882088..c9495d5b137fd 100644
--- a/doc/source/whatsnew/index.rst
+++ b/doc/source/whatsnew/index.rst
@@ -17,6 +17,7 @@ Version 1.0
:maxdepth: 2
v1.0.0
+ v1.0.1
Version 0.25
------------
diff --git a/doc/source/whatsnew/v1.0.1.rst b/doc/source/whatsnew/v1.0.1.rst
new file mode 100644
index 0000000000000..b84448e3bf896
--- /dev/null
+++ b/doc/source/whatsnew/v1.0.1.rst
@@ -0,0 +1,134 @@
+.. _whatsnew_101:
+
+What's new in 1.0.1 (??)
+------------------------
+
+These are the changes in pandas 1.0.1. See :ref:`release` for a full changelog
+including other versions of pandas.
+
+{{ header }}
+
+.. ---------------------------------------------------------------------------
+
+
+.. _whatsnew_101.bug_fixes:
+
+Bug fixes
+~~~~~~~~~
+
+
+Categorical
+^^^^^^^^^^^
+
+-
+-
+
+Datetimelike
+^^^^^^^^^^^^
+-
+-
+
+Timedelta
+^^^^^^^^^
+
+-
+-
+
+Timezones
+^^^^^^^^^
+
+-
+-
+
+
+Numeric
+^^^^^^^
+-
+-
+
+Conversion
+^^^^^^^^^^
+
+-
+-
+
+Strings
+^^^^^^^
+
+-
+-
+
+
+Interval
+^^^^^^^^
+
+-
+-
+
+Indexing
+^^^^^^^^
+
+-
+-
+
+Missing
+^^^^^^^
+
+-
+-
+
+MultiIndex
+^^^^^^^^^^
+
+-
+-
+
+I/O
+^^^
+
+-
+-
+
+Plotting
+^^^^^^^^
+
+-
+-
+
+Groupby/resample/rolling
+^^^^^^^^^^^^^^^^^^^^^^^^
+
+-
+-
+
+
+Reshaping
+^^^^^^^^^
+
+-
+-
+
+Sparse
+^^^^^^
+
+-
+-
+
+ExtensionArray
+^^^^^^^^^^^^^^
+
+-
+-
+
+
+Other
+^^^^^
+-
+-
+
+.. ---------------------------------------------------------------------------
+
+.. _whatsnew_101.contributors:
+
+Contributors
+~~~~~~~~~~~~
| Backport PR #30907: DOC: add 1.0.1 whatsnew file | https://api.github.com/repos/pandas-dev/pandas/pulls/31443 | 2020-01-30T08:32:16Z | 2020-01-30T10:22:24Z | 2020-01-30T10:22:24Z | 2020-01-30T10:22:25Z |
Backport PR #31438 on branch 1.0.x (DOC: Fix 1.0.0 contributors) | diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index ce078bfd4a6a9..989cc9b5d78c2 100755
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -1292,4 +1292,4 @@ Other
Contributors
~~~~~~~~~~~~
-.. contributors:: v0.25.3..v1.0.0rc0
+.. contributors:: v0.25.3..v1.0.0
| Backport PR #31438: DOC: Fix 1.0.0 contributors | https://api.github.com/repos/pandas-dev/pandas/pulls/31442 | 2020-01-30T08:31:13Z | 2020-01-30T10:21:46Z | 2020-01-30T10:21:46Z | 2020-01-30T10:21:46Z |
BUG: Fix qcut for nullable integers | diff --git a/doc/source/whatsnew/v1.0.1.rst b/doc/source/whatsnew/v1.0.1.rst
index 305de5bbd57eb..56b11cdae15ae 100644
--- a/doc/source/whatsnew/v1.0.1.rst
+++ b/doc/source/whatsnew/v1.0.1.rst
@@ -131,6 +131,7 @@ ExtensionArray
^^^^^^^^^^^^^^
- Bug in dtype being lost in ``__invert__`` (``~`` operator) for extension-array backed ``Series`` and ``DataFrame`` (:issue:`23087`)
+- Bug where :meth:`qcut` would raise when passed a nullable integer. (:issue:`31389`)
-
diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py
index 00a7645d0c7a5..a18b45a077be0 100644
--- a/pandas/core/reshape/tile.py
+++ b/pandas/core/reshape/tile.py
@@ -202,17 +202,10 @@ def cut(
"""
# NOTE: this binning code is changed a bit from histogram for var(x) == 0
- # for handling the cut for datetime and timedelta objects
original = x
x = _preprocess_for_cut(x)
x, dtype = _coerce_to_type(x)
- # To support cut(IntegerArray), we convert to object dtype with NaN
- # Will properly support in the future.
- # https://github.com/pandas-dev/pandas/pull/31290
- if is_extension_array_dtype(x.dtype) and is_integer_dtype(x.dtype):
- x = x.to_numpy(dtype=object, na_value=np.nan)
-
if not np.iterable(bins):
if is_scalar(bins) and bins < 1:
raise ValueError("`bins` should be a positive integer.")
@@ -434,7 +427,7 @@ def _bins_to_cuts(
def _coerce_to_type(x):
"""
- if the passed data is of datetime/timedelta or bool type,
+ if the passed data is of datetime/timedelta, bool or nullable int type,
this method converts it to numeric so that cut or qcut method can
handle it
"""
@@ -451,6 +444,12 @@ def _coerce_to_type(x):
elif is_bool_dtype(x):
# GH 20303
x = x.astype(np.int64)
+ # To support cut and qcut for IntegerArray we convert to float dtype.
+ # Will properly support in the future.
+ # https://github.com/pandas-dev/pandas/pull/31290
+ # https://github.com/pandas-dev/pandas/issues/31389
+ elif is_extension_array_dtype(x) and is_integer_dtype(x):
+ x = x.to_numpy(dtype=np.float64, na_value=np.nan)
if dtype is not None:
# GH 19768: force NaT to NaN during integer conversion
diff --git a/pandas/tests/arrays/test_integer.py b/pandas/tests/arrays/test_integer.py
index cc81ae4504dd8..7a0c9300a43a2 100644
--- a/pandas/tests/arrays/test_integer.py
+++ b/pandas/tests/arrays/test_integer.py
@@ -1061,19 +1061,6 @@ def test_value_counts_na():
tm.assert_series_equal(result, expected)
-@pytest.mark.parametrize("bins", [3, [0, 5, 15]])
-@pytest.mark.parametrize("right", [True, False])
-@pytest.mark.parametrize("include_lowest", [True, False])
-def test_cut(bins, right, include_lowest):
- a = np.random.randint(0, 10, size=50).astype(object)
- a[::2] = np.nan
- result = pd.cut(
- pd.array(a, dtype="Int64"), bins, right=right, include_lowest=include_lowest
- )
- expected = pd.cut(a, bins, right=right, include_lowest=include_lowest)
- tm.assert_categorical_equal(result, expected)
-
-
def test_array_setitem_nullable_boolean_mask():
# GH 31446
ser = pd.Series([1, 2], dtype="Int64")
diff --git a/pandas/tests/reshape/test_cut.py b/pandas/tests/reshape/test_cut.py
index 13b6f05ed304a..830e786fd1c6d 100644
--- a/pandas/tests/reshape/test_cut.py
+++ b/pandas/tests/reshape/test_cut.py
@@ -612,3 +612,16 @@ def test_cut_incorrect_labels(labels):
msg = "Bin labels must either be False, None or passed in as a list-like argument"
with pytest.raises(ValueError, match=msg):
cut(values, 4, labels=labels)
+
+
+@pytest.mark.parametrize("bins", [3, [0, 5, 15]])
+@pytest.mark.parametrize("right", [True, False])
+@pytest.mark.parametrize("include_lowest", [True, False])
+def test_cut_nullable_integer(bins, right, include_lowest):
+ a = np.random.randint(0, 10, size=50).astype(float)
+ a[::2] = np.nan
+ result = cut(
+ pd.array(a, dtype="Int64"), bins, right=right, include_lowest=include_lowest
+ )
+ expected = cut(a, bins, right=right, include_lowest=include_lowest)
+ tm.assert_categorical_equal(result, expected)
diff --git a/pandas/tests/reshape/test_qcut.py b/pandas/tests/reshape/test_qcut.py
index 95406a5ebf4f7..c436ab5d90578 100644
--- a/pandas/tests/reshape/test_qcut.py
+++ b/pandas/tests/reshape/test_qcut.py
@@ -3,6 +3,7 @@
import numpy as np
import pytest
+import pandas as pd
from pandas import (
Categorical,
DatetimeIndex,
@@ -286,3 +287,14 @@ def test_qcut_bool_coercion_to_int(bins, box, compare):
expected = qcut(data_expected, bins, duplicates="drop")
result = qcut(data_result, bins, duplicates="drop")
compare(result, expected)
+
+
+@pytest.mark.parametrize("q", [2, 5, 10])
+def test_qcut_nullable_integer(q, any_nullable_int_dtype):
+ arr = pd.array(np.arange(100), dtype=any_nullable_int_dtype)
+ arr[::2] = pd.NA
+
+ result = qcut(arr, q)
+ expected = qcut(arr.astype(float), q)
+
+ tm.assert_categorical_equal(result, expected)
| - [x] tests added / passed
- [x] passes `black pandas`
- [x] whatsnew entry
Related to #31389 but doesn't close any issues that I'm aware of. Seems the problems were indexing into a numpy array with a BooleanArray and using searchsorted in the presence of pd.NA. | https://api.github.com/repos/pandas-dev/pandas/pulls/31440 | 2020-01-30T04:34:24Z | 2020-02-02T22:19:06Z | 2020-02-02T22:19:06Z | 2020-02-02T22:22:40Z |
DOC: Fix 1.0.0 contributors | diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index d0ea8a633bed5..c4414faefef01 100755
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -1293,4 +1293,4 @@ Other
Contributors
~~~~~~~~~~~~
-.. contributors:: v0.25.3..v1.0.0rc0
+.. contributors:: v0.25.3..v1.0.0
| I've also applied this locally in the doc build env. | https://api.github.com/repos/pandas-dev/pandas/pulls/31438 | 2020-01-30T02:24:22Z | 2020-01-30T08:29:56Z | 2020-01-30T08:29:56Z | 2020-01-31T22:50:56Z |
BUG: PeriodIndex.is_monotonic with leading NaT | diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst
index 54175fada6e56..e07a8fa0469f4 100644
--- a/doc/source/whatsnew/v1.1.0.rst
+++ b/doc/source/whatsnew/v1.1.0.rst
@@ -149,6 +149,8 @@ Indexing
- Bug in slicing on a :class:`DatetimeIndex` with a partial-timestamp dropping high-resolution indices near the end of a year, quarter, or month (:issue:`31064`)
- Bug in :meth:`PeriodIndex.get_loc` treating higher-resolution strings differently from :meth:`PeriodIndex.get_value` (:issue:`31172`)
- Bug in :meth:`Series.at` and :meth:`DataFrame.at` not matching ``.loc`` behavior when looking up an integer in a :class:`Float64Index` (:issue:`31329`)
+- Bug in :meth:`PeriodIndex.is_monotonic` incorrectly returning ``True`` when containing leading ``NaT`` entries (:issue:`31437`)
+-
Missing
^^^^^^^
diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx
index 2dfc14378baf6..1915eaf6e07dd 100644
--- a/pandas/_libs/index.pyx
+++ b/pandas/_libs/index.pyx
@@ -514,8 +514,7 @@ cdef class PeriodEngine(Int64Engine):
return super(PeriodEngine, self).vgetter().view("i8")
cdef _call_monotonic(self, values):
- # super(...) pattern doesn't seem to work with `cdef`
- return Int64Engine._call_monotonic(self, values.view('i8'))
+ return algos.is_monotonic(values, timelike=True)
def get_indexer(self, values):
cdef:
diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py
index 16fa0b0c25925..248df3291f040 100644
--- a/pandas/tests/indexes/period/test_period.py
+++ b/pandas/tests/indexes/period/test_period.py
@@ -662,3 +662,44 @@ def test_maybe_convert_timedelta():
msg = r"Input has different freq=B from PeriodIndex\(freq=D\)"
with pytest.raises(ValueError, match=msg):
pi._maybe_convert_timedelta(offset)
+
+
+def test_is_monotonic_with_nat():
+ # GH#31437
+ # PeriodIndex.is_monotonic should behave analogously to DatetimeIndex,
+ # in particular never be monotonic when we have NaT
+ dti = pd.date_range("2016-01-01", periods=3)
+ pi = dti.to_period("D")
+ tdi = pd.Index(dti.view("timedelta64[ns]"))
+
+ for obj in [pi, pi._engine, dti, dti._engine, tdi, tdi._engine]:
+ if isinstance(obj, pd.Index):
+ # i.e. not Engines
+ assert obj.is_monotonic
+ assert obj.is_monotonic_increasing
+ assert not obj.is_monotonic_decreasing
+ assert obj.is_unique
+
+ dti1 = dti.insert(0, pd.NaT)
+ pi1 = dti1.to_period("D")
+ tdi1 = pd.Index(dti1.view("timedelta64[ns]"))
+
+ for obj in [pi1, pi1._engine, dti1, dti1._engine, tdi1, tdi1._engine]:
+ if isinstance(obj, pd.Index):
+ # i.e. not Engines
+ assert not obj.is_monotonic
+ assert not obj.is_monotonic_increasing
+ assert not obj.is_monotonic_decreasing
+ assert obj.is_unique
+
+ dti2 = dti.insert(3, pd.NaT)
+ pi2 = dti2.to_period("H")
+ tdi2 = pd.Index(dti2.view("timedelta64[ns]"))
+
+ for obj in [pi2, pi2._engine, dti2, dti2._engine, tdi2, tdi2._engine]:
+ if isinstance(obj, pd.Index):
+ # i.e. not Engines
+ assert not obj.is_monotonic
+ assert not obj.is_monotonic_increasing
+ assert not obj.is_monotonic_decreasing
+ assert obj.is_unique
diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py
index 8d2058ffab643..0b312fe2f8990 100644
--- a/pandas/tests/reductions/test_reductions.py
+++ b/pandas/tests/reductions/test_reductions.py
@@ -440,7 +440,8 @@ def test_minmax_period(self):
# monotonic
idx1 = pd.PeriodIndex([NaT, "2011-01-01", "2011-01-02", "2011-01-03"], freq="D")
- assert idx1.is_monotonic
+ assert not idx1.is_monotonic
+ assert idx1[1:].is_monotonic
# non-monotonic
idx2 = pd.PeriodIndex(
| Before long I expect to just have PeriodEngine subclass DatetimeEngine. | https://api.github.com/repos/pandas-dev/pandas/pulls/31437 | 2020-01-30T02:09:48Z | 2020-01-31T14:27:38Z | 2020-01-31T14:27:37Z | 2020-01-31T15:53:04Z |
TST: make sure fixture params are sorted list | diff --git a/pandas/tests/groupby/conftest.py b/pandas/tests/groupby/conftest.py
index 8901af7a90acc..ebac36c5f8c78 100644
--- a/pandas/tests/groupby/conftest.py
+++ b/pandas/tests/groupby/conftest.py
@@ -112,7 +112,7 @@ def reduction_func(request):
return request.param
-@pytest.fixture(params=transformation_kernels)
+@pytest.fixture(params=sorted(transformation_kernels))
def transformation_func(request):
"""yields the string names of all groupby transformation functions."""
return request.param
| ATM running tests with --n 4 breaks locally because the tests that get collected dont match across processes. | https://api.github.com/repos/pandas-dev/pandas/pulls/31436 | 2020-01-30T01:14:52Z | 2020-01-30T19:15:24Z | 2020-01-30T19:15:24Z | 2020-01-30T19:21:33Z |
ENH: Added index to testing assert message when series values differ | diff --git a/pandas/_libs/testing.pyx b/pandas/_libs/testing.pyx
index 0e57b563d4d25..c6b8c3e876390 100644
--- a/pandas/_libs/testing.pyx
+++ b/pandas/_libs/testing.pyx
@@ -65,7 +65,7 @@ cpdef assert_dict_equal(a, b, bint compare_keys=True):
cpdef assert_almost_equal(a, b,
check_less_precise=False,
bint check_dtype=True,
- obj=None, lobj=None, robj=None):
+ obj=None, lobj=None, robj=None, index_values=None):
"""
Check that left and right objects are almost equal.
@@ -89,6 +89,12 @@ cpdef assert_almost_equal(a, b,
robj : str, default None
Specify right object name being compared, internally used to show
appropriate assertion message
+ index_values : ndarray, default None
+ Specify shared index values of objects being compared, internally used
+ to show appropriate assertion message
+
+ .. versionadded:: 1.1.0
+
"""
cdef:
int decimal
@@ -171,7 +177,7 @@ cpdef assert_almost_equal(a, b,
from pandas._testing import raise_assert_detail
msg = (f"{obj} values are different "
f"({np.round(diff * 100.0 / na, 5)} %)")
- raise_assert_detail(obj, msg, lobj, robj)
+ raise_assert_detail(obj, msg, lobj, robj, index_values=index_values)
return True
diff --git a/pandas/_testing.py b/pandas/_testing.py
index dff15c66750ac..db5d141cc0051 100644
--- a/pandas/_testing.py
+++ b/pandas/_testing.py
@@ -888,9 +888,16 @@ def assert_timedelta_array_equal(left, right, obj="TimedeltaArray"):
assert_attr_equal("freq", left, right, obj=obj)
-def raise_assert_detail(obj, message, left, right, diff=None):
+def raise_assert_detail(obj, message, left, right, diff=None, index_values=None):
__tracebackhide__ = True
+ msg = f"""{obj} are different
+
+{message}"""
+
+ if isinstance(index_values, np.ndarray):
+ msg += f"\n[index]: {pprint_thing(index_values)}"
+
if isinstance(left, np.ndarray):
left = pprint_thing(left)
elif is_categorical_dtype(left):
@@ -901,9 +908,7 @@ def raise_assert_detail(obj, message, left, right, diff=None):
elif is_categorical_dtype(right):
right = repr(right)
- msg = f"""{obj} are different
-
-{message}
+ msg += f"""
[left]: {left}
[right]: {right}"""
@@ -921,6 +926,7 @@ def assert_numpy_array_equal(
err_msg=None,
check_same=None,
obj="numpy array",
+ index_values=None,
):
"""
Check that 'np.ndarray' is equivalent.
@@ -940,6 +946,8 @@ def assert_numpy_array_equal(
obj : str, default 'numpy array'
Specify object name being compared, internally used to show appropriate
assertion message.
+ index_values : numpy.ndarray, default None
+ optional index (shared by both left and right), used in output.
"""
__tracebackhide__ = True
@@ -977,7 +985,7 @@ def _raise(left, right, err_msg):
diff = diff * 100.0 / left.size
msg = f"{obj} values are different ({np.round(diff, 5)} %)"
- raise_assert_detail(obj, msg, left, right)
+ raise_assert_detail(obj, msg, left, right, index_values=index_values)
raise AssertionError(err_msg)
@@ -1142,7 +1150,11 @@ def assert_series_equal(
raise AssertionError("check_exact may only be used with numeric Series")
assert_numpy_array_equal(
- left._values, right._values, check_dtype=check_dtype, obj=str(obj)
+ left._values,
+ right._values,
+ check_dtype=check_dtype,
+ obj=str(obj),
+ index_values=np.asarray(left.index),
)
elif check_datetimelike_compat and (
needs_i8_conversion(left.dtype) or needs_i8_conversion(right.dtype)
@@ -1181,6 +1193,7 @@ def assert_series_equal(
check_less_precise=check_less_precise,
check_dtype=check_dtype,
obj=str(obj),
+ index_values=np.asarray(left.index),
)
# metadata comparison
diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py
index 3090343ba2fd9..b6b0ca53d1fdb 100644
--- a/pandas/tests/util/test_assert_frame_equal.py
+++ b/pandas/tests/util/test_assert_frame_equal.py
@@ -177,6 +177,7 @@ def test_frame_equal_block_mismatch(by_blocks_fixture, obj_fixture):
msg = f"""{obj}\\.iloc\\[:, 1\\] \\(column name="B"\\) are different
{obj}\\.iloc\\[:, 1\\] \\(column name="B"\\) values are different \\(33\\.33333 %\\)
+\\[index\\]: \\[0, 1, 2\\]
\\[left\\]: \\[4, 5, 6\\]
\\[right\\]: \\[4, 5, 7\\]"""
@@ -196,6 +197,7 @@ def test_frame_equal_block_mismatch(by_blocks_fixture, obj_fixture):
"""{obj}\\.iloc\\[:, 1\\] \\(column name="E"\\) are different
{obj}\\.iloc\\[:, 1\\] \\(column name="E"\\) values are different \\(33\\.33333 %\\)
+\\[index\\]: \\[0, 1, 2\\]
\\[left\\]: \\[é, è, ë\\]
\\[right\\]: \\[é, è, e̊\\]""",
),
@@ -205,6 +207,7 @@ def test_frame_equal_block_mismatch(by_blocks_fixture, obj_fixture):
"""{obj}\\.iloc\\[:, 0\\] \\(column name="A"\\) are different
{obj}\\.iloc\\[:, 0\\] \\(column name="A"\\) values are different \\(100\\.0 %\\)
+\\[index\\]: \\[0, 1, 2\\]
\\[left\\]: \\[á, à, ä\\]
\\[right\\]: \\[a, a, a\\]""",
),
diff --git a/pandas/tests/util/test_assert_series_equal.py b/pandas/tests/util/test_assert_series_equal.py
index eaf0824f52927..a77c57fb5411c 100644
--- a/pandas/tests/util/test_assert_series_equal.py
+++ b/pandas/tests/util/test_assert_series_equal.py
@@ -168,6 +168,7 @@ def test_series_equal_values_mismatch(check_less_precise):
msg = """Series are different
Series values are different \\(33\\.33333 %\\)
+\\[index\\]: \\[0, 1, 2\\]
\\[left\\]: \\[1, 2, 3\\]
\\[right\\]: \\[1, 2, 4\\]"""
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x] passes `black pandas`
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
This implements the suggestion made in #31190
In short, where the values in 2 series differ, the assert exception message includes the index as well as the values. This helps when using assert_frame_equal with check_like=True, since the index may be reordered, making the output hard to understand. | https://api.github.com/repos/pandas-dev/pandas/pulls/31435 | 2020-01-29T23:44:41Z | 2020-03-22T20:42:35Z | 2020-03-22T20:42:35Z | 2020-03-22T20:42:42Z |
REF: use inherit_names for PeriodIndex | diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py
index 1e18c16d02784..4c0121d50e84f 100644
--- a/pandas/core/indexes/period.py
+++ b/pandas/core/indexes/period.py
@@ -24,7 +24,6 @@
pandas_dtype,
)
-from pandas.core.accessor import delegate_names
from pandas.core.arrays.period import (
PeriodArray,
period_array,
@@ -39,11 +38,9 @@
ensure_index,
maybe_extract_name,
)
-from pandas.core.indexes.datetimelike import (
- DatetimeIndexOpsMixin,
- DatetimelikeDelegateMixin,
-)
+from pandas.core.indexes.datetimelike import DatetimeIndexOpsMixin
from pandas.core.indexes.datetimes import DatetimeIndex, Index
+from pandas.core.indexes.extension import inherit_names
from pandas.core.indexes.numeric import Int64Index
from pandas.core.ops import get_op_result_name
from pandas.core.tools.datetimes import DateParseError
@@ -71,23 +68,14 @@ def _new_PeriodIndex(cls, **d):
return cls(values, **d)
-class PeriodDelegateMixin(DatetimelikeDelegateMixin):
- """
- Delegate from PeriodIndex to PeriodArray.
- """
-
- _raw_methods = {"_format_native_types"}
- _raw_properties = {"is_leap_year", "freq"}
-
- _delegated_properties = PeriodArray._datetimelike_ops + list(_raw_properties)
- _delegated_methods = set(PeriodArray._datetimelike_methods) | _raw_methods
-
-
-@delegate_names(PeriodArray, PeriodDelegateMixin._delegated_properties, typ="property")
-@delegate_names(
- PeriodArray, PeriodDelegateMixin._delegated_methods, typ="method", overwrite=True
+@inherit_names(
+ ["strftime", "to_timestamp", "asfreq", "start_time", "end_time"]
+ + PeriodArray._field_ops,
+ PeriodArray,
+ wrap=True,
)
-class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
+@inherit_names(["is_leap_year", "freq", "_format_native_types"], PeriodArray)
+class PeriodIndex(DatetimeIndexOpsMixin, Int64Index):
"""
Immutable ndarray holding ordinal values indicating regular periods in time.
| analogous to #31427. | https://api.github.com/repos/pandas-dev/pandas/pulls/31433 | 2020-01-29T22:42:03Z | 2020-01-31T03:21:24Z | 2020-01-31T03:21:24Z | 2020-01-31T04:19:53Z |
Backport PR #31430 on branch 1.0.x (release date) | diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index 22e6da39550b3..ce078bfd4a6a9 100755
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -1,7 +1,7 @@
.. _whatsnew_100:
-What's new in 1.0.0 (??)
-------------------------
+What's new in 1.0.0 (January 29, 2020)
+--------------------------------------
These are the changes in pandas 1.0.0. See :ref:`release` for a full changelog
including other versions of pandas.
| Backport PR #31430: release date | https://api.github.com/repos/pandas-dev/pandas/pulls/31432 | 2020-01-29T21:43:26Z | 2020-01-29T21:43:38Z | 2020-01-29T21:43:38Z | 2020-01-30T09:53:27Z |
DOC: separate section with experimental features in 1.0.0 whatsnew (#… | diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index 3295241f2e8a3..22e6da39550b3 100755
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -37,6 +37,43 @@ See :ref:`policies.version` for more.
Enhancements
~~~~~~~~~~~~
+.. _whatsnew_100.numba_rolling_apply:
+
+Using Numba in ``rolling.apply`` and ``expanding.apply``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+We've added an ``engine`` keyword to :meth:`~core.window.rolling.Rolling.apply` and :meth:`~core.window.expanding.Expanding.apply`
+that allows the user to execute the routine using `Numba <https://numba.pydata.org/>`__ instead of Cython.
+Using the Numba engine can yield significant performance gains if the apply function can operate on numpy arrays and
+the data set is larger (1 million rows or greater). For more details, see
+:ref:`rolling apply documentation <stats.rolling_apply>` (:issue:`28987`, :issue:`30936`)
+
+.. _whatsnew_100.custom_window:
+
+Defining custom windows for rolling operations
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+We've added a :func:`pandas.api.indexers.BaseIndexer` class that allows users to define how
+window bounds are created during ``rolling`` operations. Users can define their own ``get_window_bounds``
+method on a :func:`pandas.api.indexers.BaseIndexer` subclass that will generate the start and end
+indices used for each window during the rolling aggregation. For more details and example usage, see
+the :ref:`custom window rolling documentation <stats.custom_rolling_window>`
+
+.. _whatsnew_100.to_markdown:
+
+Converting to Markdown
+^^^^^^^^^^^^^^^^^^^^^^
+
+We've added :meth:`~DataFrame.to_markdown` for creating a markdown table (:issue:`11052`)
+
+.. ipython:: python
+
+ df = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]}, index=['a', 'a', 'b'])
+ print(df.to_markdown())
+
+Experimental new features
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
.. _whatsnew_100.NA:
Experimental ``NA`` scalar to denote missing values
@@ -187,44 +224,11 @@ This is especially useful after reading in data using readers such as :func:`rea
and :func:`read_excel`.
See :ref:`here <missing_data.NA.conversion>` for a description.
-.. _whatsnew_100.numba_rolling_apply:
-
-Using Numba in ``rolling.apply``
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-We've added an ``engine`` keyword to :meth:`~core.window.rolling.Rolling.apply` that allows the user to execute the
-routine using `Numba <https://numba.pydata.org/>`__ instead of Cython. Using the Numba engine
-can yield significant performance gains if the apply function can operate on numpy arrays and
-the data set is larger (1 million rows or greater). For more details, see
-:ref:`rolling apply documentation <stats.rolling_apply>` (:issue:`28987`)
-
-.. _whatsnew_100.custom_window:
-
-Defining custom windows for rolling operations
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-We've added a :func:`pandas.api.indexers.BaseIndexer` class that allows users to define how
-window bounds are created during ``rolling`` operations. Users can define their own ``get_window_bounds``
-method on a :func:`pandas.api.indexers.BaseIndexer` subclass that will generate the start and end
-indices used for each window during the rolling aggregation. For more details and example usage, see
-the :ref:`custom window rolling documentation <stats.custom_rolling_window>`
-
-.. _whatsnew_100.to_markdown:
-
-Converting to Markdown
-^^^^^^^^^^^^^^^^^^^^^^
-
-We've added :meth:`~DataFrame.to_markdown` for creating a markdown table (:issue:`11052`)
-
-.. ipython:: python
-
- df = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]}, index=['a', 'a', 'b'])
- print(df.to_markdown())
.. _whatsnew_100.enhancements.other:
Other enhancements
-^^^^^^^^^^^^^^^^^^
+~~~~~~~~~~~~~~~~~~
- :meth:`DataFrame.to_string` added the ``max_colwidth`` parameter to control when wide columns are truncated (:issue:`9784`)
- Added the ``na_value`` argument to :meth:`Series.to_numpy`, :meth:`Index.to_numpy` and :meth:`DataFrame.to_numpy` to control the value used for missing data (:issue:`30322`)
@@ -257,13 +261,6 @@ Other enhancements
- :meth:`DataFrame.to_pickle` and :func:`read_pickle` now accept URL (:issue:`30163`)
-Build Changes
-^^^^^^^^^^^^^
-
-Pandas has added a `pyproject.toml <https://www.python.org/dev/peps/pep-0517/>`_ file and will no longer include
-cythonized files in the source distribution uploaded to PyPI (:issue:`28341`, :issue:`20775`). If you're installing
-a built distribution (wheel) or via conda, this shouldn't have any effect on you. If you're building pandas from
-source, you should no longer need to install Cython into your build environment before calling ``pip install pandas``.
.. ---------------------------------------------------------------------------
@@ -749,6 +746,15 @@ Optional libraries below the lowest tested version may still work, but are not c
See :ref:`install.dependencies` and :ref:`install.optional_dependencies` for more.
+Build Changes
+^^^^^^^^^^^^^
+
+Pandas has added a `pyproject.toml <https://www.python.org/dev/peps/pep-0517/>`_ file and will no longer include
+cythonized files in the source distribution uploaded to PyPI (:issue:`28341`, :issue:`20775`). If you're installing
+a built distribution (wheel) or via conda, this shouldn't have any effect on you. If you're building pandas from
+source, you should no longer need to install Cython into your build environment before calling ``pip install pandas``.
+
+
.. _whatsnew_100.api.other:
Other API changes
| …31429)
Backport https://github.com/pandas-dev/pandas/pull/3142 | https://api.github.com/repos/pandas-dev/pandas/pulls/31431 | 2020-01-29T21:13:04Z | 2020-01-29T21:42:21Z | 2020-01-29T21:42:21Z | 2020-01-30T09:54:02Z |
release date | diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index d0ea8a633bed5..8d2c99e3b35c8 100755
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -1,7 +1,7 @@
.. _whatsnew_100:
-What's new in 1.0.0 (??)
-------------------------
+What's new in 1.0.0 (January 29, 2020)
+--------------------------------------
These are the changes in pandas 1.0.0. See :ref:`release` for a full changelog
including other versions of pandas.
| https://api.github.com/repos/pandas-dev/pandas/pulls/31430 | 2020-01-29T21:06:32Z | 2020-01-29T21:42:30Z | 2020-01-29T21:42:30Z | 2020-01-29T21:43:38Z | |
DOC: separate section with experimental features in 1.0.0 whatsnew | diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index 2abe85f042af1..6586c19ee3426 100755
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -37,6 +37,43 @@ See :ref:`policies.version` for more.
Enhancements
~~~~~~~~~~~~
+.. _whatsnew_100.numba_rolling_apply:
+
+Using Numba in ``rolling.apply`` and ``expanding.apply``
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+We've added an ``engine`` keyword to :meth:`~core.window.rolling.Rolling.apply` and :meth:`~core.window.expanding.Expanding.apply`
+that allows the user to execute the routine using `Numba <https://numba.pydata.org/>`__ instead of Cython.
+Using the Numba engine can yield significant performance gains if the apply function can operate on numpy arrays and
+the data set is larger (1 million rows or greater). For more details, see
+:ref:`rolling apply documentation <stats.rolling_apply>` (:issue:`28987`, :issue:`30936`)
+
+.. _whatsnew_100.custom_window:
+
+Defining custom windows for rolling operations
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+We've added a :func:`pandas.api.indexers.BaseIndexer` class that allows users to define how
+window bounds are created during ``rolling`` operations. Users can define their own ``get_window_bounds``
+method on a :func:`pandas.api.indexers.BaseIndexer` subclass that will generate the start and end
+indices used for each window during the rolling aggregation. For more details and example usage, see
+the :ref:`custom window rolling documentation <stats.custom_rolling_window>`
+
+.. _whatsnew_100.to_markdown:
+
+Converting to Markdown
+^^^^^^^^^^^^^^^^^^^^^^
+
+We've added :meth:`~DataFrame.to_markdown` for creating a markdown table (:issue:`11052`)
+
+.. ipython:: python
+
+ df = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]}, index=['a', 'a', 'b'])
+ print(df.to_markdown())
+
+Experimental new features
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
.. _whatsnew_100.NA:
Experimental ``NA`` scalar to denote missing values
@@ -187,44 +224,11 @@ This is especially useful after reading in data using readers such as :func:`rea
and :func:`read_excel`.
See :ref:`here <missing_data.NA.conversion>` for a description.
-.. _whatsnew_100.numba_rolling_apply:
-
-Using Numba in ``rolling.apply`` and ``expanding.apply``
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-We've added an ``engine`` keyword to :meth:`~core.window.rolling.Rolling.apply` and :meth:`~core.window.expanding.Expanding.apply`
-that allows the user to execute the routine using `Numba <https://numba.pydata.org/>`__ instead of Cython.
-Using the Numba engine can yield significant performance gains if the apply function can operate on numpy arrays and
-the data set is larger (1 million rows or greater). For more details, see
-:ref:`rolling apply documentation <stats.rolling_apply>` (:issue:`28987`, :issue:`30936`)
-
-.. _whatsnew_100.custom_window:
-
-Defining custom windows for rolling operations
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-We've added a :func:`pandas.api.indexers.BaseIndexer` class that allows users to define how
-window bounds are created during ``rolling`` operations. Users can define their own ``get_window_bounds``
-method on a :func:`pandas.api.indexers.BaseIndexer` subclass that will generate the start and end
-indices used for each window during the rolling aggregation. For more details and example usage, see
-the :ref:`custom window rolling documentation <stats.custom_rolling_window>`
-
-.. _whatsnew_100.to_markdown:
-
-Converting to Markdown
-^^^^^^^^^^^^^^^^^^^^^^
-
-We've added :meth:`~DataFrame.to_markdown` for creating a markdown table (:issue:`11052`)
-
-.. ipython:: python
-
- df = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]}, index=['a', 'a', 'b'])
- print(df.to_markdown())
.. _whatsnew_100.enhancements.other:
Other enhancements
-^^^^^^^^^^^^^^^^^^
+~~~~~~~~~~~~~~~~~~
- :meth:`DataFrame.to_string` added the ``max_colwidth`` parameter to control when wide columns are truncated (:issue:`9784`)
- Added the ``na_value`` argument to :meth:`Series.to_numpy`, :meth:`Index.to_numpy` and :meth:`DataFrame.to_numpy` to control the value used for missing data (:issue:`30322`)
@@ -257,13 +261,6 @@ Other enhancements
- :meth:`DataFrame.to_pickle` and :func:`read_pickle` now accept URL (:issue:`30163`)
-Build Changes
-^^^^^^^^^^^^^
-
-Pandas has added a `pyproject.toml <https://www.python.org/dev/peps/pep-0517/>`_ file and will no longer include
-cythonized files in the source distribution uploaded to PyPI (:issue:`28341`, :issue:`20775`). If you're installing
-a built distribution (wheel) or via conda, this shouldn't have any effect on you. If you're building pandas from
-source, you should no longer need to install Cython into your build environment before calling ``pip install pandas``.
.. ---------------------------------------------------------------------------
@@ -701,6 +698,15 @@ Optional libraries below the lowest tested version may still work, but are not c
See :ref:`install.dependencies` and :ref:`install.optional_dependencies` for more.
+Build Changes
+^^^^^^^^^^^^^
+
+Pandas has added a `pyproject.toml <https://www.python.org/dev/peps/pep-0517/>`_ file and will no longer include
+cythonized files in the source distribution uploaded to PyPI (:issue:`28341`, :issue:`20775`). If you're installing
+a built distribution (wheel) or via conda, this shouldn't have any effect on you. If you're building pandas from
+source, you should no longer need to install Cython into your build environment before calling ``pip install pandas``.
+
+
.. _whatsnew_100.api.other:
Other API changes
| Just a thought I had, to put the experimental features (pd.NA, string, boolean dtypes) in a separate section, better highlighting that those are experimental.
Since @TomAugspurger basically wants to release now, this is certainly not a blocker :) | https://api.github.com/repos/pandas-dev/pandas/pulls/31429 | 2020-01-29T20:30:27Z | 2020-01-29T21:05:04Z | 2020-01-29T21:05:04Z | 2020-01-30T09:55:56Z |
BUG: regression when applying groupby aggregation on categorical colu… | diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst
index 14a46e7e9b909..3295241f2e8a3 100755
--- a/doc/source/whatsnew/v1.0.0.rst
+++ b/doc/source/whatsnew/v1.0.0.rst
@@ -626,6 +626,54 @@ consistent with the behaviour of :class:`DataFrame` and :class:`Index`.
DeprecationWarning: The default dtype for empty Series will be 'object' instead of 'float64' in a future version. Specify a dtype explicitly to silence this warning.
Series([], dtype: float64)
+Result dtype inference changes for resample operations
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The rules for the result dtype in :meth:`DataFrame.resample` aggregations have changed for extension types (:issue:`31359`).
+Previously, pandas would attempt to convert the result back to the original dtype, falling back to the usual
+inference rules if that was not possible. Now, pandas will only return a result of the original dtype if the
+scalar values in the result are instances of the extension dtype's scalar type.
+
+.. ipython:: python
+
+ df = pd.DataFrame({"A": ['a', 'b']}, dtype='category',
+ index=pd.date_range('2000', periods=2))
+ df
+
+
+*pandas 0.25.x*
+
+.. code-block:: python
+
+ >>> df.resample("2D").agg(lambda x: 'a').A.dtype
+ CategoricalDtype(categories=['a', 'b'], ordered=False)
+
+*pandas 1.0.0*
+
+.. ipython:: python
+
+ df.resample("2D").agg(lambda x: 'a').A.dtype
+
+This fixes an inconsistency between ``resample`` and ``groupby``.
+This also fixes a potential bug, where the **values** of the result might change
+depending on how the results are cast back to the original dtype.
+
+*pandas 0.25.x*
+
+.. code-block:: python
+
+ >>> df.resample("2D").agg(lambda x: 'c')
+
+ A
+ 0 NaN
+
+*pandas 1.0.0*
+
+.. ipython:: python
+
+ df.resample("2D").agg(lambda x: 'c')
+
+
.. _whatsnew_100.api_breaking.python:
Increased minimum version for Python
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index 03f7b8895bcf1..a1e5692af9b2e 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -813,9 +813,10 @@ def _try_cast(self, result, obj, numeric_only: bool = False):
# datetime64tz is handled correctly in agg_series,
# so is excluded here.
- # return the same type (Series) as our caller
- cls = dtype.construct_array_type()
- result = try_cast_to_ea(cls, result, dtype=dtype)
+ if len(result) and isinstance(result[0], dtype.type):
+ cls = dtype.construct_array_type()
+ result = try_cast_to_ea(cls, result, dtype=dtype)
+
elif numeric_only and is_numeric_dtype(dtype) or not numeric_only:
result = maybe_downcast_to_dtype(result, dtype)
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 679d3668523c2..2e95daa392976 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -543,6 +543,17 @@ def _cython_operation(
if mask.any():
result = result.astype("float64")
result[mask] = np.nan
+ elif (
+ how == "add"
+ and is_integer_dtype(orig_values.dtype)
+ and is_extension_array_dtype(orig_values.dtype)
+ ):
+ # We need this to ensure that Series[Int64Dtype].resample().sum()
+ # remains int64 dtype.
+ # Two options for avoiding this special case
+ # 1. mask-aware ops and avoid casting to float with NaN above
+ # 2. specify the result dtype when calling this method
+ result = result.astype("int64")
if kind == "aggregate" and self._filter_empty_groups and not counts.all():
assert result.ndim != 2
diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py
index 056d457e76d81..723aec15d14bc 100644
--- a/pandas/tests/groupby/aggregate/test_aggregate.py
+++ b/pandas/tests/groupby/aggregate/test_aggregate.py
@@ -648,6 +648,43 @@ def test_lambda_named_agg(func):
tm.assert_frame_equal(result, expected)
+def test_aggregate_mixed_types():
+ # GH 16916
+ df = pd.DataFrame(
+ data=np.array([0] * 9).reshape(3, 3), columns=list("XYZ"), index=list("abc")
+ )
+ df["grouping"] = ["group 1", "group 1", 2]
+ result = df.groupby("grouping").aggregate(lambda x: x.tolist())
+ expected_data = [[[0], [0], [0]], [[0, 0], [0, 0], [0, 0]]]
+ expected = pd.DataFrame(
+ expected_data,
+ index=Index([2, "group 1"], dtype="object", name="grouping"),
+ columns=Index(["X", "Y", "Z"], dtype="object"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.xfail(reason="Not implemented.")
+def test_aggregate_udf_na_extension_type():
+ # https://github.com/pandas-dev/pandas/pull/31359
+ # This is currently failing to cast back to Int64Dtype.
+ # The presence of the NA causes two problems
+ # 1. NA is not an instance of Int64Dtype.type (numpy.int64)
+ # 2. The presence of an NA forces object type, so the non-NA values is
+ # a Python int rather than a NumPy int64. Python ints aren't
+ # instances of numpy.int64.
+ def aggfunc(x):
+ if all(x > 2):
+ return 1
+ else:
+ return pd.NA
+
+ df = pd.DataFrame({"A": pd.array([1, 2, 3])})
+ result = df.groupby([1, 1, 2]).agg(aggfunc)
+ expected = pd.DataFrame({"A": pd.array([1, pd.NA], dtype="Int64")}, index=[1, 2])
+ tm.assert_frame_equal(result, expected)
+
+
class TestLambdaMangling:
def test_maybe_mangle_lambdas_passthrough(self):
assert _maybe_mangle_lambdas("mean") == "mean"
diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py
index 9323946581a0d..1c2de8c8c223f 100644
--- a/pandas/tests/groupby/test_categorical.py
+++ b/pandas/tests/groupby/test_categorical.py
@@ -1342,3 +1342,37 @@ def test_series_groupby_categorical_aggregation_getitem():
result = groups["foo"].agg("mean")
expected = groups.agg("mean")["foo"]
tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "func, expected_values",
+ [(pd.Series.nunique, [1, 1, 2]), (pd.Series.count, [1, 2, 2])],
+)
+def test_groupby_agg_categorical_columns(func, expected_values):
+ # 31256
+ df = pd.DataFrame(
+ {
+ "id": [0, 1, 2, 3, 4],
+ "groups": [0, 1, 1, 2, 2],
+ "value": pd.Categorical([0, 0, 0, 0, 1]),
+ }
+ ).set_index("id")
+ result = df.groupby("groups").agg(func)
+
+ expected = pd.DataFrame(
+ {"value": expected_values}, index=pd.Index([0, 1, 2], name="groups"),
+ )
+ tm.assert_frame_equal(result, expected)
+
+
+def test_groupby_agg_non_numeric():
+ df = pd.DataFrame(
+ {"A": pd.Categorical(["a", "a", "b"], categories=["a", "b", "c"])}
+ )
+ expected = pd.DataFrame({"A": [2, 1]}, index=[1, 2])
+
+ result = df.groupby([1, 2, 1]).agg(pd.Series.nunique)
+ tm.assert_frame_equal(result, expected)
+
+ result = df.groupby([1, 2, 1]).nunique()
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py
index 4860329718f54..3ad82b9e075a8 100644
--- a/pandas/tests/resample/test_datetime_index.py
+++ b/pandas/tests/resample/test_datetime_index.py
@@ -122,7 +122,9 @@ def test_resample_integerarray():
result = ts.resample("3T").mean()
expected = Series(
- [1, 4, 7], index=pd.date_range("1/1/2000", periods=3, freq="3T"), dtype="Int64"
+ [1, 4, 7],
+ index=pd.date_range("1/1/2000", periods=3, freq="3T"),
+ dtype="float64",
)
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/resample/test_timedelta.py b/pandas/tests/resample/test_timedelta.py
index d1bcdc55cb509..a4d14f127b80e 100644
--- a/pandas/tests/resample/test_timedelta.py
+++ b/pandas/tests/resample/test_timedelta.py
@@ -105,7 +105,7 @@ def test_resample_categorical_data_with_timedeltaindex():
index=pd.to_timedelta([0, 10], unit="s"),
)
expected = expected.reindex(["Group_obj", "Group"], axis=1)
- expected["Group"] = expected["Group_obj"].astype("category")
+ expected["Group"] = expected["Group_obj"]
tm.assert_frame_equal(result, expected)
| Backport of https://github.com/pandas-dev/pandas/pull/31359 | https://api.github.com/repos/pandas-dev/pandas/pulls/31428 | 2020-01-29T20:26:12Z | 2020-01-29T20:54:37Z | 2020-01-29T20:54:37Z | 2020-01-30T10:18:05Z |
REF: use inherit_names for TimedeltaIndex | diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py
index 1257e410b4125..cd4b2cbc780a7 100644
--- a/pandas/core/indexes/timedeltas.py
+++ b/pandas/core/indexes/timedeltas.py
@@ -16,7 +16,6 @@
)
from pandas.core.dtypes.missing import is_valid_nat_for_dtype
-from pandas.core.accessor import delegate_names
from pandas.core.arrays import datetimelike as dtl
from pandas.core.arrays.timedeltas import TimedeltaArray
import pandas.core.common as com
@@ -28,7 +27,6 @@
)
from pandas.core.indexes.datetimelike import (
DatetimeIndexOpsMixin,
- DatetimelikeDelegateMixin,
DatetimeTimedeltaMixin,
)
from pandas.core.indexes.extension import inherit_names
@@ -36,20 +34,20 @@
from pandas.tseries.frequencies import to_offset
-class TimedeltaDelegateMixin(DatetimelikeDelegateMixin):
- # Most attrs are dispatched via datetimelike_{ops,methods}
- # Some are "raw" methods, the result is not re-boxed in an Index
- # We also have a few "extra" attrs, which may or may not be raw,
- # which we don't want to expose in the .dt accessor.
- _raw_properties = {"components", "_box_func"}
- _raw_methods = {"to_pytimedelta", "sum", "std", "median", "_format_native_types"}
-
- _delegated_properties = TimedeltaArray._datetimelike_ops + list(_raw_properties)
- _delegated_methods = TimedeltaArray._datetimelike_methods + list(_raw_methods)
-
-
@inherit_names(
- ["_box_values", "__neg__", "__pos__", "__abs__"], TimedeltaArray, wrap=True
+ [
+ "_box_values",
+ "__neg__",
+ "__pos__",
+ "__abs__",
+ "total_seconds",
+ "round",
+ "floor",
+ "ceil",
+ ]
+ + TimedeltaArray._field_ops,
+ TimedeltaArray,
+ wrap=True,
)
@inherit_names(
[
@@ -59,21 +57,18 @@ class TimedeltaDelegateMixin(DatetimelikeDelegateMixin):
"_datetimelike_ops",
"_datetimelike_methods",
"_other_ops",
+ "components",
+ "_box_func",
+ "to_pytimedelta",
+ "sum",
+ "std",
+ "median",
+ "_format_native_types",
+ "freq",
],
TimedeltaArray,
)
-@delegate_names(
- TimedeltaArray, TimedeltaDelegateMixin._delegated_properties, typ="property"
-)
-@delegate_names(
- TimedeltaArray,
- TimedeltaDelegateMixin._delegated_methods,
- typ="method",
- overwrite=True,
-)
-class TimedeltaIndex(
- DatetimeTimedeltaMixin, dtl.TimelikeOps, TimedeltaDelegateMixin,
-):
+class TimedeltaIndex(DatetimeTimedeltaMixin, dtl.TimelikeOps):
"""
Immutable ndarray of timedelta64 data, represented internally as int64, and
which can be boxed to timedelta objects.
| ATM we have two separate ways of doing inheritance/pass-through for our EA-backed Indexes. This moves TDI over to all-inherit_names, Will do the same for other EA-Indexes in their own PRs. | https://api.github.com/repos/pandas-dev/pandas/pulls/31427 | 2020-01-29T19:34:52Z | 2020-01-31T03:13:40Z | 2020-01-31T03:13:40Z | 2020-01-31T16:04:55Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.