title stringlengths 1 185 | diff stringlengths 0 32.2M | body stringlengths 0 123k ⌀ | url stringlengths 57 58 | created_at stringlengths 20 20 | closed_at stringlengths 20 20 | merged_at stringlengths 20 20 ⌀ | updated_at stringlengths 20 20 |
|---|---|---|---|---|---|---|---|
BUG: Perform i8 conversion for datetimelike IntervalTree queries | diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt
index f246ebad3aa2c..42c4134437ff6 100644
--- a/doc/source/whatsnew/v0.24.0.txt
+++ b/doc/source/whatsnew/v0.24.0.txt
@@ -755,7 +755,7 @@ Interval
- Bug in the :class:`IntervalIndex` constructor where the ``closed`` parameter did not always override the inferred ``closed`` (:issue:`19370`)
- Bug in the ``IntervalIndex`` repr where a trailing comma was missing after the list of intervals (:issue:`20611`)
- Bug in :class:`Interval` where scalar arithmetic operations did not retain the ``closed`` value (:issue:`22313`)
--
+- Bug in :class:`IntervalIndex` where indexing with datetime-like values raised a ``KeyError`` (:issue:`20636`)
Indexing
^^^^^^^^
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index f72f87aeb2af6..25d4dd0cbcc81 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -6,12 +6,14 @@
from pandas.compat import add_metaclass
from pandas.core.dtypes.missing import isna
-from pandas.core.dtypes.cast import find_common_type, maybe_downcast_to_dtype
+from pandas.core.dtypes.cast import (
+ find_common_type, maybe_downcast_to_dtype, infer_dtype_from_scalar)
from pandas.core.dtypes.common import (
ensure_platform_int,
is_list_like,
is_datetime_or_timedelta_dtype,
is_datetime64tz_dtype,
+ is_dtype_equal,
is_integer_dtype,
is_float_dtype,
is_interval_dtype,
@@ -29,8 +31,8 @@
Interval, IntervalMixin, IntervalTree,
)
-from pandas.core.indexes.datetimes import date_range
-from pandas.core.indexes.timedeltas import timedelta_range
+from pandas.core.indexes.datetimes import date_range, DatetimeIndex
+from pandas.core.indexes.timedeltas import timedelta_range, TimedeltaIndex
from pandas.core.indexes.multi import MultiIndex
import pandas.core.common as com
from pandas.util._decorators import cache_readonly, Appender
@@ -192,7 +194,9 @@ def _isnan(self):
@cache_readonly
def _engine(self):
- return IntervalTree(self.left, self.right, closed=self.closed)
+ left = self._maybe_convert_i8(self.left)
+ right = self._maybe_convert_i8(self.right)
+ return IntervalTree(left, right, closed=self.closed)
def __contains__(self, key):
"""
@@ -514,6 +518,78 @@ def _maybe_cast_indexed(self, key):
return key
+ def _needs_i8_conversion(self, key):
+ """
+ Check if a given key needs i8 conversion. Conversion is necessary for
+ Timestamp, Timedelta, DatetimeIndex, and TimedeltaIndex keys. An
+ Interval-like requires conversion if it's endpoints are one of the
+ aforementioned types.
+
+ Assumes that any list-like data has already been cast to an Index.
+
+ Parameters
+ ----------
+ key : scalar or Index-like
+ The key that should be checked for i8 conversion
+
+ Returns
+ -------
+ boolean
+ """
+ if is_interval_dtype(key) or isinstance(key, Interval):
+ return self._needs_i8_conversion(key.left)
+
+ i8_types = (Timestamp, Timedelta, DatetimeIndex, TimedeltaIndex)
+ return isinstance(key, i8_types)
+
+ def _maybe_convert_i8(self, key):
+ """
+ Maybe convert a given key to it's equivalent i8 value(s). Used as a
+ preprocessing step prior to IntervalTree queries (self._engine), which
+ expects numeric data.
+
+ Parameters
+ ----------
+ key : scalar or list-like
+ The key that should maybe be converted to i8.
+
+ Returns
+ -------
+ key: scalar or list-like
+ The original key if no conversion occured, int if converted scalar,
+ Int64Index if converted list-like.
+ """
+ original = key
+ if is_list_like(key):
+ key = ensure_index(key)
+
+ if not self._needs_i8_conversion(key):
+ return original
+
+ scalar = is_scalar(key)
+ if is_interval_dtype(key) or isinstance(key, Interval):
+ # convert left/right and reconstruct
+ left = self._maybe_convert_i8(key.left)
+ right = self._maybe_convert_i8(key.right)
+ constructor = Interval if scalar else IntervalIndex.from_arrays
+ return constructor(left, right, closed=self.closed)
+
+ if scalar:
+ # Timestamp/Timedelta
+ key_dtype, key_i8 = infer_dtype_from_scalar(key, pandas_dtype=True)
+ else:
+ # DatetimeIndex/TimedeltaIndex
+ key_dtype, key_i8 = key.dtype, Index(key.asi8)
+
+ # ensure consistency with IntervalIndex subtype
+ subtype = self.dtype.subtype
+ msg = ('Cannot index an IntervalIndex of subtype {subtype} with '
+ 'values of dtype {other}')
+ if not is_dtype_equal(subtype, key_dtype):
+ raise ValueError(msg.format(subtype=subtype, other=key_dtype))
+
+ return key_i8
+
def _check_method(self, method):
if method is None:
return
@@ -648,6 +724,7 @@ def get_loc(self, key, method=None):
else:
# use the interval tree
+ key = self._maybe_convert_i8(key)
if isinstance(key, Interval):
left, right = _get_interval_closed_bounds(key)
return self._engine.get_loc_interval(left, right)
@@ -711,8 +788,10 @@ def _get_reindexer(self, target):
"""
# find the left and right indexers
- lindexer = self._engine.get_indexer(target.left.values)
- rindexer = self._engine.get_indexer(target.right.values)
+ left = self._maybe_convert_i8(target.left)
+ right = self._maybe_convert_i8(target.right)
+ lindexer = self._engine.get_indexer(left.values)
+ rindexer = self._engine.get_indexer(right.values)
# we want to return an indexer on the intervals
# however, our keys could provide overlapping of multiple
diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py
index 71f56c5bc1164..0ff5ab232d670 100644
--- a/pandas/tests/indexes/interval/test_interval.py
+++ b/pandas/tests/indexes/interval/test_interval.py
@@ -1,7 +1,9 @@
from __future__ import division
+from itertools import permutations
import pytest
import numpy as np
+import re
from pandas import (
Interval, IntervalIndex, Index, isna, notna, interval_range, Timestamp,
Timedelta, date_range, timedelta_range)
@@ -498,6 +500,48 @@ def test_get_loc_length_one(self, item, closed):
result = index.get_loc(item)
assert result == 0
+ # Make consistent with test_interval_new.py (see #16316, #16386)
+ @pytest.mark.parametrize('breaks', [
+ date_range('20180101', periods=4),
+ date_range('20180101', periods=4, tz='US/Eastern'),
+ timedelta_range('0 days', periods=4)], ids=lambda x: str(x.dtype))
+ def test_get_loc_datetimelike_nonoverlapping(self, breaks):
+ # GH 20636
+ # nonoverlapping = IntervalIndex method and no i8 conversion
+ index = IntervalIndex.from_breaks(breaks)
+
+ value = index[0].mid
+ result = index.get_loc(value)
+ expected = 0
+ assert result == expected
+
+ interval = Interval(index[0].left, index[1].right)
+ result = index.get_loc(interval)
+ expected = slice(0, 2)
+ assert result == expected
+
+ # Make consistent with test_interval_new.py (see #16316, #16386)
+ @pytest.mark.parametrize('arrays', [
+ (date_range('20180101', periods=4), date_range('20180103', periods=4)),
+ (date_range('20180101', periods=4, tz='US/Eastern'),
+ date_range('20180103', periods=4, tz='US/Eastern')),
+ (timedelta_range('0 days', periods=4),
+ timedelta_range('2 days', periods=4))], ids=lambda x: str(x[0].dtype))
+ def test_get_loc_datetimelike_overlapping(self, arrays):
+ # GH 20636
+ # overlapping = IntervalTree method with i8 conversion
+ index = IntervalIndex.from_arrays(*arrays)
+
+ value = index[0].mid + Timedelta('12 hours')
+ result = np.sort(index.get_loc(value))
+ expected = np.array([0, 1], dtype='int64')
+ assert tm.assert_numpy_array_equal(result, expected)
+
+ interval = Interval(index[0].left, index[1].right)
+ result = np.sort(index.get_loc(interval))
+ expected = np.array([0, 1, 2], dtype='int64')
+ assert tm.assert_numpy_array_equal(result, expected)
+
# To be removed, replaced by test_interval_new.py (see #16316, #16386)
def test_get_indexer(self):
actual = self.index.get_indexer([-1, 0, 0.5, 1, 1.5, 2, 3])
@@ -555,6 +599,97 @@ def test_get_indexer_length_one(self, item, closed):
expected = np.array([0] * len(item), dtype='intp')
tm.assert_numpy_array_equal(result, expected)
+ # Make consistent with test_interval_new.py (see #16316, #16386)
+ @pytest.mark.parametrize('arrays', [
+ (date_range('20180101', periods=4), date_range('20180103', periods=4)),
+ (date_range('20180101', periods=4, tz='US/Eastern'),
+ date_range('20180103', periods=4, tz='US/Eastern')),
+ (timedelta_range('0 days', periods=4),
+ timedelta_range('2 days', periods=4))], ids=lambda x: str(x[0].dtype))
+ def test_get_reindexer_datetimelike(self, arrays):
+ # GH 20636
+ index = IntervalIndex.from_arrays(*arrays)
+ tuples = [(index[0].left, index[0].left + pd.Timedelta('12H')),
+ (index[-1].right - pd.Timedelta('12H'), index[-1].right)]
+ target = IntervalIndex.from_tuples(tuples)
+
+ result = index._get_reindexer(target)
+ expected = np.array([0, 3], dtype='int64')
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize('breaks', [
+ date_range('20180101', periods=4),
+ date_range('20180101', periods=4, tz='US/Eastern'),
+ timedelta_range('0 days', periods=4)], ids=lambda x: str(x.dtype))
+ def test_maybe_convert_i8(self, breaks):
+ # GH 20636
+ index = IntervalIndex.from_breaks(breaks)
+
+ # intervalindex
+ result = index._maybe_convert_i8(index)
+ expected = IntervalIndex.from_breaks(breaks.asi8)
+ tm.assert_index_equal(result, expected)
+
+ # interval
+ interval = Interval(breaks[0], breaks[1])
+ result = index._maybe_convert_i8(interval)
+ expected = Interval(breaks[0].value, breaks[1].value)
+ assert result == expected
+
+ # datetimelike index
+ result = index._maybe_convert_i8(breaks)
+ expected = Index(breaks.asi8)
+ tm.assert_index_equal(result, expected)
+
+ # datetimelike scalar
+ result = index._maybe_convert_i8(breaks[0])
+ expected = breaks[0].value
+ assert result == expected
+
+ # list-like of datetimelike scalars
+ result = index._maybe_convert_i8(list(breaks))
+ expected = Index(breaks.asi8)
+ tm.assert_index_equal(result, expected)
+
+ @pytest.mark.parametrize('breaks', [
+ np.arange(5, dtype='int64'),
+ np.arange(5, dtype='float64')], ids=lambda x: str(x.dtype))
+ @pytest.mark.parametrize('make_key', [
+ IntervalIndex.from_breaks,
+ lambda breaks: Interval(breaks[0], breaks[1]),
+ lambda breaks: breaks,
+ lambda breaks: breaks[0],
+ list], ids=['IntervalIndex', 'Interval', 'Index', 'scalar', 'list'])
+ def test_maybe_convert_i8_numeric(self, breaks, make_key):
+ # GH 20636
+ index = IntervalIndex.from_breaks(breaks)
+ key = make_key(breaks)
+
+ # no conversion occurs for numeric
+ result = index._maybe_convert_i8(key)
+ assert result is key
+
+ @pytest.mark.parametrize('breaks1, breaks2', permutations([
+ date_range('20180101', periods=4),
+ date_range('20180101', periods=4, tz='US/Eastern'),
+ timedelta_range('0 days', periods=4)], 2), ids=lambda x: str(x.dtype))
+ @pytest.mark.parametrize('make_key', [
+ IntervalIndex.from_breaks,
+ lambda breaks: Interval(breaks[0], breaks[1]),
+ lambda breaks: breaks,
+ lambda breaks: breaks[0],
+ list], ids=['IntervalIndex', 'Interval', 'Index', 'scalar', 'list'])
+ def test_maybe_convert_i8_errors(self, breaks1, breaks2, make_key):
+ # GH 20636
+ index = IntervalIndex.from_breaks(breaks1)
+ key = make_key(breaks2)
+
+ msg = ('Cannot index an IntervalIndex of subtype {dtype1} with '
+ 'values of dtype {dtype2}')
+ msg = re.escape(msg.format(dtype1=breaks1.dtype, dtype2=breaks2.dtype))
+ with tm.assert_raises_regex(ValueError, msg):
+ index._maybe_convert_i8(key)
+
# To be removed, replaced by test_interval_new.py (see #16316, #16386)
def test_contains(self):
# Only endpoints are valid.
| - [X] closes #20636
- [X] tests added / passed
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [X] whatsnew entry
I've seen a few complaints about this on StackOverflow, so wanted to get this into 0.24.0 before I try implementing larger changes like the new behavior specs and interval accessor. | https://api.github.com/repos/pandas-dev/pandas/pulls/22988 | 2018-10-04T05:54:52Z | 2018-10-07T22:35:36Z | 2018-10-07T22:35:36Z | 2018-10-08T17:00:55Z |
BUG-22984 Fix truncation of DataFrame representations | diff --git a/doc/source/whatsnew/v0.24.0.rst b/doc/source/whatsnew/v0.24.0.rst
index 44c467795d1ed..9275357e5ad18 100644
--- a/doc/source/whatsnew/v0.24.0.rst
+++ b/doc/source/whatsnew/v0.24.0.rst
@@ -1319,7 +1319,8 @@ Notice how we now instead output ``np.nan`` itself instead of a stringified form
- :func:`read_sas()` will correctly parse sas7bdat files with many columns (:issue:`22628`)
- :func:`read_sas()` will correctly parse sas7bdat files with data page types having also bit 7 set (so page type is 128 + 256 = 384) (:issue:`16615`)
- Bug in :meth:`detect_client_encoding` where potential ``IOError`` goes unhandled when importing in a mod_wsgi process due to restricted access to stdout. (:issue:`21552`)
-- Bug in :func:`to_string()` that broke column alignment when ``index=False`` and width of first column's values is greater than the width of first column's header (:issue:`16839`, :issue:`13032`)
+- Bug in :func:`DataFrame.to_string()` that broke column alignment when ``index=False`` and width of first column's values is greater than the width of first column's header (:issue:`16839`, :issue:`13032`)
+- Bug in :func:`DataFrame.to_string()` that caused representations of :class:`DataFrame` to not take up the whole window (:issue:`22984`)
- Bug in :func:`DataFrame.to_csv` where a single level MultiIndex incorrectly wrote a tuple. Now just the value of the index is written (:issue:`19589`).
- Bug in :meth:`HDFStore.append` when appending a :class:`DataFrame` with an empty string column and ``min_itemsize`` < 8 (:issue:`12242`)
- Bug in :meth:`read_csv()` in which :class:`MultiIndex` index names were being improperly handled in the cases when they were not provided (:issue:`23484`)
diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py
index 6f64605bcf175..9857129f56b0c 100644
--- a/pandas/io/formats/format.py
+++ b/pandas/io/formats/format.py
@@ -608,11 +608,6 @@ def to_string(self):
else: # max_cols == 0. Try to fit frame to terminal
text = self.adj.adjoin(1, *strcols).split('\n')
max_len = Series(text).str.len().max()
- headers = [ele[0] for ele in strcols]
- # Size of last col determines dot col size. See
- # `self._to_str_columns
- size_tr_col = len(headers[self.tr_size_col])
- max_len += size_tr_col # Need to make space for largest row
# plus truncate dot col
dif = max_len - self.w
# '+ 1' to avoid too wide repr (GH PR #17023)
diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py
index 28aa8a92cc410..b8ca8cb73c7e9 100644
--- a/pandas/tests/io/formats/test_format.py
+++ b/pandas/tests/io/formats/test_format.py
@@ -305,14 +305,10 @@ def test_repr_non_interactive(self):
assert not has_truncated_repr(df)
assert not has_expanded_repr(df)
- def test_repr_truncates_terminal_size(self):
+ def test_repr_truncates_terminal_size(self, mock):
# https://github.com/pandas-dev/pandas/issues/21180
# TODO: use mock fixutre.
# This is being backported, so doing it directly here.
- try:
- from unittest import mock
- except ImportError:
- mock = pytest.importorskip("mock")
terminal_size = (118, 96)
p1 = mock.patch('pandas.io.formats.console.get_terminal_size',
@@ -343,6 +339,17 @@ def test_repr_truncates_terminal_size(self):
assert df2.columns[0] in result.split('\n')[0]
+ def test_repr_truncates_terminal_size_full(self, mock):
+ # GH 22984 ensure entire window is filled
+ terminal_size = (80, 24)
+ df = pd.DataFrame(np.random.rand(1, 7))
+ p1 = mock.patch('pandas.io.formats.console.get_terminal_size',
+ return_value=terminal_size)
+ p2 = mock.patch('pandas.io.formats.format.get_terminal_size',
+ return_value=terminal_size)
+ with p1, p2:
+ assert "..." not in str(df)
+
def test_repr_max_columns_max_rows(self):
term_width, term_height = get_terminal_size()
if term_width < 10 or term_height < 10:
| - [X] closes #22984
- [X] tests added / passed
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [X] whatsnew entry
When printing a DataFrame to terminal, an extra column's worth of space is added to the calculated width of the DataFrame. This is presumably to help edge cases, but the calculated difference between the DataFrame width and the terminal window width is incremented by 1 a few lines later, seemingly to fix the same problem. Do any more experienced developers know of a reason to pad the DataFrame width even more? | https://api.github.com/repos/pandas-dev/pandas/pulls/22987 | 2018-10-04T00:10:03Z | 2018-11-15T03:02:25Z | 2018-11-15T03:02:25Z | 2018-11-15T03:02:32Z |
CLN: prepare unifying hashtable.factorize and .unique; add doc-strings | diff --git a/pandas/_libs/hashtable_class_helper.pxi.in b/pandas/_libs/hashtable_class_helper.pxi.in
index 3ff98b7b5a9b5..c061102fbaddc 100644
--- a/pandas/_libs/hashtable_class_helper.pxi.in
+++ b/pandas/_libs/hashtable_class_helper.pxi.in
@@ -355,19 +355,38 @@ cdef class {{name}}HashTable(HashTable):
return np.asarray(locs)
- def factorize(self, {{dtype}}_t values):
- uniques = {{name}}Vector()
- labels = self.get_labels(values, uniques, 0, 0)
- return uniques.to_array(), labels
-
@cython.boundscheck(False)
- def get_labels(self, const {{dtype}}_t[:] values, {{name}}Vector uniques,
- Py_ssize_t count_prior, Py_ssize_t na_sentinel,
+ @cython.wraparound(False)
+ def _factorize(self, const {{dtype}}_t[:] values, {{name}}Vector uniques,
+ Py_ssize_t count_prior=0, Py_ssize_t na_sentinel=-1,
object na_value=None):
+ """
+ Calculate unique values and labels (no sorting); ignores all NA-values
+
+ Parameters
+ ----------
+ values : ndarray[{{dtype}}]
+ Array of values of which unique will be calculated
+ uniques : {{name}}Vector
+ Vector into which uniques will be written
+ count_prior : Py_ssize_t, default 0
+ Number of existing entries in uniques
+ na_sentinel : Py_ssize_t, default -1
+ Sentinel value used for all NA-values in inverse
+ na_value : object, default None
+ Value to identify as missing. If na_value is None, then
+ any value satisfying val!=val are considered missing.
+
+ Returns
+ -------
+ uniques : ndarray[{{dtype}}]
+ Unique values of input, not sorted
+ labels : ndarray[int64]
+ The labels from values to uniques
+ """
cdef:
- Py_ssize_t i, n = len(values)
+ Py_ssize_t i, idx, count = count_prior, n = len(values)
int64_t[:] labels
- Py_ssize_t idx, count = count_prior
int ret = 0
{{dtype}}_t val, na_value2
khiter_t k
@@ -399,9 +418,11 @@ cdef class {{name}}HashTable(HashTable):
k = kh_get_{{dtype}}(self.table, val)
if k != self.table.n_buckets:
+ # k falls into a previous bucket
idx = self.table.vals[k]
labels[i] = idx
else:
+ # k hasn't been seen yet
k = kh_put_{{dtype}}(self.table, val, &ret)
self.table.vals[k] = count
@@ -418,6 +439,19 @@ cdef class {{name}}HashTable(HashTable):
return np.asarray(labels)
+ def factorize(self, const {{dtype}}_t[:] values, Py_ssize_t na_sentinel=-1,
+ object na_value=None):
+ uniques = {{name}}Vector()
+ labels = self._factorize(values, uniques=uniques,
+ na_sentinel=na_sentinel, na_value=na_value)
+ return labels, uniques.to_array()
+
+ def get_labels(self, const {{dtype}}_t[:] values, {{name}}Vector uniques,
+ Py_ssize_t count_prior=0, Py_ssize_t na_sentinel=-1,
+ object na_value=None):
+ return self._factorize(values, uniques, count_prior=count_prior,
+ na_sentinel=na_sentinel, na_value=na_value)
+
@cython.boundscheck(False)
def get_labels_groupby(self, const {{dtype}}_t[:] values):
cdef:
@@ -464,7 +498,21 @@ cdef class {{name}}HashTable(HashTable):
return np.asarray(labels), arr_uniques
@cython.boundscheck(False)
+ @cython.wraparound(False)
def unique(self, const {{dtype}}_t[:] values):
+ """
+ Calculate unique values without sorting
+
+ Parameters
+ ----------
+ values : ndarray[{{dtype}}]
+ Array of values of which unique will be calculated
+
+ Returns
+ -------
+ uniques : ndarray[{{dtype}}]
+ Unique values of input, not sorted
+ """
cdef:
Py_ssize_t i, n = len(values)
int ret = 0
@@ -567,7 +615,21 @@ cdef class StringHashTable(HashTable):
return labels
@cython.boundscheck(False)
+ @cython.wraparound(False)
def unique(self, ndarray[object] values):
+ """
+ Calculate unique values without sorting
+
+ Parameters
+ ----------
+ values : ndarray[object]
+ Array of values of which unique will be calculated
+
+ Returns
+ -------
+ uniques : ndarray[object]
+ Unique values of input, not sorted
+ """
cdef:
Py_ssize_t i, count, n = len(values)
int64_t[:] uindexer
@@ -602,11 +664,6 @@ cdef class StringHashTable(HashTable):
uniques.append(values[uindexer[i]])
return uniques.to_array()
- def factorize(self, ndarray[object] values):
- uniques = ObjectVector()
- labels = self.get_labels(values, uniques, 0, 0)
- return uniques.to_array(), labels
-
@cython.boundscheck(False)
def lookup(self, ndarray[object] values):
cdef:
@@ -669,14 +726,37 @@ cdef class StringHashTable(HashTable):
free(vecs)
@cython.boundscheck(False)
- def get_labels(self, ndarray[object] values, ObjectVector uniques,
- Py_ssize_t count_prior, int64_t na_sentinel,
+ @cython.wraparound(False)
+ def _factorize(self, ndarray[object] values, ObjectVector uniques,
+ Py_ssize_t count_prior=0, Py_ssize_t na_sentinel=-1,
object na_value=None):
+ """
+ Calculate unique values and labels (no sorting); ignores all NA-values
+
+ Parameters
+ ----------
+ values : ndarray[object]
+ Array of values of which unique will be calculated
+ uniques : ObjectVector
+ Vector into which uniques will be written
+ count_prior : Py_ssize_t, default 0
+ Number of existing entries in uniques
+ na_sentinel : Py_ssize_t, default -1
+ Sentinel value used for all NA-values in inverse
+ na_value : object, default None
+ Value to identify as missing
+
+ Returns
+ -------
+ uniques : ndarray[object]
+ Unique values of input, not sorted
+ labels : ndarray[int64]
+ The labels from values to uniques
+ """
cdef:
- Py_ssize_t i, n = len(values)
+ Py_ssize_t i, idx, count = count_prior, n = len(values)
int64_t[:] labels
int64_t[:] uindexer
- Py_ssize_t idx, count = count_prior
int ret = 0
object val
const char *v
@@ -684,19 +764,17 @@ cdef class StringHashTable(HashTable):
khiter_t k
bint use_na_value
- # these by-definition *must* be strings
labels = np.zeros(n, dtype=np.int64)
uindexer = np.empty(n, dtype=np.int64)
use_na_value = na_value is not None
- # pre-filter out missing
- # and assign pointers
+ # assign pointers and pre-filter out missing
vecs = <const char **> malloc(n * sizeof(char *))
for i in range(n):
val = values[i]
- if ((PyUnicode_Check(val) or PyString_Check(val)) and
- not (use_na_value and val == na_value)):
+ if ((PyUnicode_Check(val) or PyString_Check(val))
+ and not (use_na_value and val == na_value)):
v = util.get_c_string(val)
vecs[i] = v
else:
@@ -711,9 +789,11 @@ cdef class StringHashTable(HashTable):
v = vecs[i]
k = kh_get_str(self.table, v)
if k != self.table.n_buckets:
+ # k falls into a previous bucket
idx = self.table.vals[k]
labels[i] = <int64_t>idx
else:
+ # k hasn't been seen yet
k = kh_put_str(self.table, v, &ret)
self.table.vals[k] = count
uindexer[count] = i
@@ -728,6 +808,19 @@ cdef class StringHashTable(HashTable):
return np.asarray(labels)
+ def factorize(self, ndarray[object] values, Py_ssize_t na_sentinel=-1,
+ object na_value=None):
+ uniques = ObjectVector()
+ labels = self._factorize(values, uniques=uniques,
+ na_sentinel=na_sentinel, na_value=na_value)
+ return labels, uniques.to_array()
+
+ def get_labels(self, ndarray[object] values, ObjectVector uniques,
+ Py_ssize_t count_prior=0, Py_ssize_t na_sentinel=-1,
+ object na_value=None):
+ return self._factorize(values, uniques, count_prior=count_prior,
+ na_sentinel=na_sentinel, na_value=na_value)
+
cdef class PyObjectHashTable(HashTable):
@@ -814,7 +907,22 @@ cdef class PyObjectHashTable(HashTable):
return np.asarray(locs)
+ @cython.boundscheck(False)
+ @cython.wraparound(False)
def unique(self, ndarray[object] values):
+ """
+ Calculate unique values without sorting
+
+ Parameters
+ ----------
+ values : ndarray[object]
+ Array of values of which unique will be calculated
+
+ Returns
+ -------
+ uniques : ndarray[object]
+ Unique values of input, not sorted
+ """
cdef:
Py_ssize_t i, n = len(values)
int ret = 0
@@ -832,13 +940,38 @@ cdef class PyObjectHashTable(HashTable):
return uniques.to_array()
- def get_labels(self, ndarray[object] values, ObjectVector uniques,
- Py_ssize_t count_prior, int64_t na_sentinel,
+ @cython.boundscheck(False)
+ @cython.wraparound(False)
+ def _factorize(self, ndarray[object] values, ObjectVector uniques,
+ Py_ssize_t count_prior=0, Py_ssize_t na_sentinel=-1,
object na_value=None):
+ """
+ Calculate unique values and labels (no sorting); ignores all NA-values
+
+ Parameters
+ ----------
+ values : ndarray[object]
+ Array of values of which unique will be calculated
+ uniques : ObjectVector
+ Vector into which uniques will be written
+ count_prior : Py_ssize_t, default 0
+ Number of existing entries in uniques
+ na_sentinel : Py_ssize_t, default -1
+ Sentinel value used for all NA-values in inverse
+ na_value : object, default None
+ Value to identify as missing. If na_value is None, then None _plus_
+ any value satisfying val!=val are considered missing.
+
+ Returns
+ -------
+ uniques : ndarray[object]
+ Unique values of input, not sorted
+ labels : ndarray[int64]
+ The labels from values to uniques
+ """
cdef:
- Py_ssize_t i, n = len(values)
+ Py_ssize_t i, idx, count = count_prior, n = len(values)
int64_t[:] labels
- Py_ssize_t idx, count = count_prior
int ret = 0
object val
khiter_t k
@@ -851,16 +984,18 @@ cdef class PyObjectHashTable(HashTable):
val = values[i]
hash(val)
- if ((val != val or val is None) or
- (use_na_value and val == na_value)):
+ if ((val != val or val is None)
+ or (use_na_value and val == na_value)):
labels[i] = na_sentinel
continue
k = kh_get_pymap(self.table, <PyObject*>val)
if k != self.table.n_buckets:
+ # k falls into a previous bucket
idx = self.table.vals[k]
labels[i] = idx
else:
+ # k hasn't been seen yet
k = kh_put_pymap(self.table, <PyObject*>val, &ret)
self.table.vals[k] = count
uniques.append(val)
@@ -868,3 +1003,16 @@ cdef class PyObjectHashTable(HashTable):
count += 1
return np.asarray(labels)
+
+ def factorize(self, ndarray[object] values, Py_ssize_t na_sentinel=-1,
+ object na_value=None):
+ uniques = ObjectVector()
+ labels = self._factorize(values, uniques=uniques,
+ na_sentinel=na_sentinel, na_value=na_value)
+ return labels, uniques.to_array()
+
+ def get_labels(self, ndarray[object] values, ObjectVector uniques,
+ Py_ssize_t count_prior=0, Py_ssize_t na_sentinel=-1,
+ object na_value=None):
+ return self._factorize(values, uniques, count_prior=count_prior,
+ na_sentinel=na_sentinel, na_value=na_value)
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index cb9ffc4bd0fd5..0f1eb12883fd5 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -467,15 +467,13 @@ def _factorize_array(values, na_sentinel=-1, size_hint=None,
-------
labels, uniques : ndarray
"""
- (hash_klass, vec_klass), values = _get_data_algo(values, _hashtables)
+ (hash_klass, _), values = _get_data_algo(values, _hashtables)
table = hash_klass(size_hint or len(values))
- uniques = vec_klass()
- labels = table.get_labels(values, uniques, 0, na_sentinel,
- na_value=na_value)
+ labels, uniques = table.factorize(values, na_sentinel=na_sentinel,
+ na_value=na_value)
labels = ensure_platform_int(labels)
- uniques = uniques.to_array()
return labels, uniques
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index 1fd801c68fdde..557669260604a 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -15,7 +15,6 @@
from pandas import compat
from pandas._libs import (groupby as libgroupby, algos as libalgos,
hashtable as ht)
-from pandas._libs.hashtable import unique_label_indices
from pandas.compat import lrange, range
import pandas.core.algorithms as algos
import pandas.core.common as com
@@ -228,19 +227,53 @@ def test_complex_sorting(self):
pytest.raises(TypeError, algos.factorize, x17[::-1], sort=True)
+ def test_float64_factorize(self, writable):
+ data = np.array([1.0, 1e8, 1.0, 1e-8, 1e8, 1.0], dtype=np.float64)
+ data.setflags(write=writable)
+ exp_labels = np.array([0, 1, 0, 2, 1, 0], dtype=np.intp)
+ exp_uniques = np.array([1.0, 1e8, 1e-8], dtype=np.float64)
+
+ labels, uniques = algos.factorize(data)
+ tm.assert_numpy_array_equal(labels, exp_labels)
+ tm.assert_numpy_array_equal(uniques, exp_uniques)
+
def test_uint64_factorize(self, writable):
- data = np.array([2**63, 1, 2**63], dtype=np.uint64)
+ data = np.array([2**64 - 1, 1, 2**64 - 1], dtype=np.uint64)
data.setflags(write=writable)
exp_labels = np.array([0, 1, 0], dtype=np.intp)
- exp_uniques = np.array([2**63, 1], dtype=np.uint64)
+ exp_uniques = np.array([2**64 - 1, 1], dtype=np.uint64)
labels, uniques = algos.factorize(data)
tm.assert_numpy_array_equal(labels, exp_labels)
tm.assert_numpy_array_equal(uniques, exp_uniques)
- data = np.array([2**63, -1, 2**63], dtype=object)
+ def test_int64_factorize(self, writable):
+ data = np.array([2**63 - 1, -2**63, 2**63 - 1], dtype=np.int64)
+ data.setflags(write=writable)
exp_labels = np.array([0, 1, 0], dtype=np.intp)
- exp_uniques = np.array([2**63, -1], dtype=object)
+ exp_uniques = np.array([2**63 - 1, -2**63], dtype=np.int64)
+
+ labels, uniques = algos.factorize(data)
+ tm.assert_numpy_array_equal(labels, exp_labels)
+ tm.assert_numpy_array_equal(uniques, exp_uniques)
+
+ def test_string_factorize(self, writable):
+ data = np.array(['a', 'c', 'a', 'b', 'c'],
+ dtype=object)
+ data.setflags(write=writable)
+ exp_labels = np.array([0, 1, 0, 2, 1], dtype=np.intp)
+ exp_uniques = np.array(['a', 'c', 'b'], dtype=object)
+
+ labels, uniques = algos.factorize(data)
+ tm.assert_numpy_array_equal(labels, exp_labels)
+ tm.assert_numpy_array_equal(uniques, exp_uniques)
+
+ def test_object_factorize(self, writable):
+ data = np.array(['a', 'c', None, np.nan, 'a', 'b', pd.NaT, 'c'],
+ dtype=object)
+ data.setflags(write=writable)
+ exp_labels = np.array([0, 1, -1, -1, 0, 2, -1, 1], dtype=np.intp)
+ exp_uniques = np.array(['a', 'c', 'b'], dtype=object)
labels, uniques = algos.factorize(data)
tm.assert_numpy_array_equal(labels, exp_labels)
@@ -1262,41 +1295,107 @@ def test_get_unique(self):
exp = np.array([1, 2, 2**63], dtype=np.uint64)
tm.assert_numpy_array_equal(s.unique(), exp)
- def test_vector_resize(self, writable):
+ @pytest.mark.parametrize('nvals', [0, 10]) # resizing to 0 is special case
+ @pytest.mark.parametrize('htable, uniques, dtype, safely_resizes', [
+ (ht.PyObjectHashTable, ht.ObjectVector, 'object', False),
+ (ht.StringHashTable, ht.ObjectVector, 'object', True),
+ (ht.Float64HashTable, ht.Float64Vector, 'float64', False),
+ (ht.Int64HashTable, ht.Int64Vector, 'int64', False),
+ (ht.UInt64HashTable, ht.UInt64Vector, 'uint64', False)])
+ def test_vector_resize(self, writable, htable, uniques, dtype,
+ safely_resizes, nvals):
# Test for memory errors after internal vector
- # reallocations (pull request #7157)
-
- def _test_vector_resize(htable, uniques, dtype, nvals, safely_resizes):
- vals = np.array(np.random.randn(1000), dtype=dtype)
- # GH 21688 ensure we can deal with readonly memory views
- vals.setflags(write=writable)
- # get_labels may append to uniques
- htable.get_labels(vals[:nvals], uniques, 0, -1)
- # to_array() set an external_view_exists flag on uniques.
- tmp = uniques.to_array()
- oldshape = tmp.shape
- # subsequent get_labels() calls can no longer append to it
- # (for all but StringHashTables + ObjectVector)
- if safely_resizes:
+ # reallocations (GH 7157)
+ vals = np.array(np.random.randn(1000), dtype=dtype)
+
+ # GH 21688 ensures we can deal with read-only memory views
+ vals.setflags(write=writable)
+
+ # initialise instances; cannot initialise in parametrization,
+ # as otherwise external views would be held on the array (which is
+ # one of the things this test is checking)
+ htable = htable()
+ uniques = uniques()
+
+ # get_labels may append to uniques
+ htable.get_labels(vals[:nvals], uniques, 0, -1)
+ # to_array() sets an external_view_exists flag on uniques.
+ tmp = uniques.to_array()
+ oldshape = tmp.shape
+
+ # subsequent get_labels() calls can no longer append to it
+ # (except for StringHashTables + ObjectVector)
+ if safely_resizes:
+ htable.get_labels(vals, uniques, 0, -1)
+ else:
+ with tm.assert_raises_regex(ValueError, 'external reference.*'):
htable.get_labels(vals, uniques, 0, -1)
- else:
- with pytest.raises(ValueError) as excinfo:
- htable.get_labels(vals, uniques, 0, -1)
- assert str(excinfo.value).startswith('external reference')
- uniques.to_array() # should not raise here
- assert tmp.shape == oldshape
-
- test_cases = [
- (ht.PyObjectHashTable, ht.ObjectVector, 'object', False),
- (ht.StringHashTable, ht.ObjectVector, 'object', True),
- (ht.Float64HashTable, ht.Float64Vector, 'float64', False),
- (ht.Int64HashTable, ht.Int64Vector, 'int64', False),
- (ht.UInt64HashTable, ht.UInt64Vector, 'uint64', False)]
-
- for (tbl, vect, dtype, safely_resizes) in test_cases:
- # resizing to empty is a special case
- _test_vector_resize(tbl(), vect(), dtype, 0, safely_resizes)
- _test_vector_resize(tbl(), vect(), dtype, 10, safely_resizes)
+
+ uniques.to_array() # should not raise here
+ assert tmp.shape == oldshape
+
+ @pytest.mark.parametrize('htable, tm_dtype', [
+ (ht.PyObjectHashTable, 'String'),
+ (ht.StringHashTable, 'String'),
+ (ht.Float64HashTable, 'Float'),
+ (ht.Int64HashTable, 'Int'),
+ (ht.UInt64HashTable, 'UInt')])
+ def test_hashtable_unique(self, htable, tm_dtype, writable):
+ # output of maker has guaranteed unique elements
+ maker = getattr(tm, 'make' + tm_dtype + 'Index')
+ s = Series(maker(1000))
+ if htable == ht.Float64HashTable:
+ # add NaN for float column
+ s.loc[500] = np.nan
+ elif htable == ht.PyObjectHashTable:
+ # use different NaN types for object column
+ s.loc[500:502] = [np.nan, None, pd.NaT]
+
+ # create duplicated selection
+ s_duplicated = s.sample(frac=3, replace=True).reset_index(drop=True)
+ s_duplicated.values.setflags(write=writable)
+
+ # drop_duplicates has own cython code (hash_table_func_helper.pxi)
+ # and is tested separately; keeps first occurrence like ht.unique()
+ expected_unique = s_duplicated.drop_duplicates(keep='first').values
+ result_unique = htable().unique(s_duplicated.values)
+ tm.assert_numpy_array_equal(result_unique, expected_unique)
+
+ @pytest.mark.parametrize('htable, tm_dtype', [
+ (ht.PyObjectHashTable, 'String'),
+ (ht.StringHashTable, 'String'),
+ (ht.Float64HashTable, 'Float'),
+ (ht.Int64HashTable, 'Int'),
+ (ht.UInt64HashTable, 'UInt')])
+ def test_hashtable_factorize(self, htable, tm_dtype, writable):
+ # output of maker has guaranteed unique elements
+ maker = getattr(tm, 'make' + tm_dtype + 'Index')
+ s = Series(maker(1000))
+ if htable == ht.Float64HashTable:
+ # add NaN for float column
+ s.loc[500] = np.nan
+ elif htable == ht.PyObjectHashTable:
+ # use different NaN types for object column
+ s.loc[500:502] = [np.nan, None, pd.NaT]
+
+ # create duplicated selection
+ s_duplicated = s.sample(frac=3, replace=True).reset_index(drop=True)
+ s_duplicated.values.setflags(write=writable)
+ na_mask = s_duplicated.isna().values
+
+ result_inverse, result_unique = htable().factorize(s_duplicated.values)
+
+ # drop_duplicates has own cython code (hash_table_func_helper.pxi)
+ # and is tested separately; keeps first occurrence like ht.factorize()
+ # since factorize removes all NaNs, we do the same here
+ expected_unique = s_duplicated.dropna().drop_duplicates().values
+ tm.assert_numpy_array_equal(result_unique, expected_unique)
+
+ # reconstruction can only succeed if the inverse is correct. Since
+ # factorize removes the NaNs, those have to be excluded here as well
+ result_reconstruct = result_unique[result_inverse[~na_mask]]
+ expected_reconstruct = s_duplicated.dropna().values
+ tm.assert_numpy_array_equal(result_reconstruct, expected_reconstruct)
def test_quantile():
@@ -1311,14 +1410,14 @@ def test_unique_label_indices():
a = np.random.randint(1, 1 << 10, 1 << 15).astype('i8')
- left = unique_label_indices(a)
+ left = ht.unique_label_indices(a)
right = np.unique(a, return_index=True)[1]
tm.assert_numpy_array_equal(left, right,
check_dtype=False)
a[np.random.choice(len(a), 10)] = -1
- left = unique_label_indices(a)
+ left = ht.unique_label_indices(a)
right = np.unique(a, return_index=True)[1][1:]
tm.assert_numpy_array_equal(left, right,
check_dtype=False)
| For adding a `return_inverse`-kwarg to `unique` (#21357 / #21645), I originally didn't want to have to add something to the templated cython code, preferring to add a solution using `numpy.unique` as a first step (with the idea of improving the performance later).
@jorisvandenbossche then remarked:
> Which led me think: `pd.unique` with a `return_inverse` argument is actually basically the same as `pd.factorize`?
I didn't know what `factorize` was doing, so I had no idea about this connection. From looking at the cython code in `hashtable_class_helper.pxi.in`, I found that there's substantial overlap between `unique` and `get_labels` (the core of `factorize`) - the only difference is the handling of `NaN/None/etc.`
I think that these could/should be unified for less code duplication. Alternatively, the first commit of this PR could be split off into a separate PR - it is *just* adding a `return_inverse`-kwarg to `unique` -- though effectively by duplicating the `factorize` code.
Both variants pass the the test suite locally, the only question is whether there's appreciable differences in the ASVs. Since the only extra complexity of unifying the code is reading the value of some `bint` within the loop, I don't think that it'll be relevant. I got some noisy data the first time 'round, will let it run again when I have the possibility.
So long story short, this PR prepares the hashtable-backend to support `return_inverse=True`, which plays into #21357 #21645 #22824, and will also allow to easily solve #21720.
Side note: this already builds on #22978 to be able to run the ASVs at all. | https://api.github.com/repos/pandas-dev/pandas/pulls/22986 | 2018-10-03T22:47:17Z | 2018-10-18T15:50:49Z | 2018-10-18T15:50:49Z | 2018-10-22T14:16:36Z |
CLN: values is required argument in _shallow_copy_with_infer | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index af04a846ed787..51c84d6e28cb4 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -530,7 +530,7 @@ def _shallow_copy(self, values=None, **kwargs):
return self._simple_new(values, **attributes)
- def _shallow_copy_with_infer(self, values=None, **kwargs):
+ def _shallow_copy_with_infer(self, values, **kwargs):
"""
create a new Index inferring the class with passed value, don't copy
the data, use the same object attributes with passed in attributes
@@ -543,8 +543,6 @@ def _shallow_copy_with_infer(self, values=None, **kwargs):
values : the values to create the new Index, optional
kwargs : updates the default attributes for this Index
"""
- if values is None:
- values = self.values
attributes = self._get_attributes_dict()
attributes.update(kwargs)
attributes['copy'] = False
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 3e6b934e1e863..822c0b864059c 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -555,7 +555,7 @@ def view(self, cls=None):
result._id = self._id
return result
- def _shallow_copy_with_infer(self, values=None, **kwargs):
+ def _shallow_copy_with_infer(self, values, **kwargs):
# On equal MultiIndexes the difference is empty.
# Therefore, an empty MultiIndex is returned GH13490
if len(values) == 0:
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py
index 969391569ce50..cc008694a8b84 100644
--- a/pandas/core/indexes/period.py
+++ b/pandas/core/indexes/period.py
@@ -287,7 +287,7 @@ def _from_ordinals(cls, values, name=None, freq=None, **kwargs):
result._reset_identity()
return result
- def _shallow_copy_with_infer(self, values=None, **kwargs):
+ def _shallow_copy_with_infer(self, values, **kwargs):
""" we always want to return a PeriodIndex """
return self._shallow_copy(values=values, **kwargs)
| @TomAugspurger @jbrockmendel From looking at the code related to the discussion in https://github.com/pandas-dev/pandas/pull/22961, I noticed `_shallow_copy_with_infer` has the potential to not pass any values, which is never actually used in pandas. So a small code clean-up | https://api.github.com/repos/pandas-dev/pandas/pulls/22983 | 2018-10-03T19:55:24Z | 2018-10-04T11:16:28Z | 2018-10-04T11:16:28Z | 2018-10-04T16:57:29Z |
Merge asof float fix | diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt
index f246ebad3aa2c..bded5c1b644e9 100644
--- a/doc/source/whatsnew/v0.24.0.txt
+++ b/doc/source/whatsnew/v0.24.0.txt
@@ -847,6 +847,7 @@ Reshaping
- Bug in :meth:`DataFrame.drop_duplicates` for empty ``DataFrame`` which incorrectly raises an error (:issue:`20516`)
- Bug in :func:`pandas.wide_to_long` when a string is passed to the stubnames argument and a column name is a substring of that stubname (:issue:`22468`)
- Bug in :func:`merge` when merging ``datetime64[ns, tz]`` data that contained a DST transition (:issue:`18885`)
+- Bug in :func:`merge_asof` when merging on float values within defined tolerance (:issue:`22981`)
Build Changes
^^^^^^^^^^^^^
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index c4305136accb1..d0c7b66978661 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -23,6 +23,7 @@
is_categorical_dtype,
is_integer_dtype,
is_float_dtype,
+ is_number,
is_numeric_dtype,
is_integer,
is_int_or_datetime_dtype,
@@ -1356,8 +1357,14 @@ def _get_merge_keys(self):
if self.tolerance < 0:
raise MergeError("tolerance must be positive")
+ elif is_float_dtype(lt):
+ if not is_number(self.tolerance):
+ raise MergeError(msg)
+ if self.tolerance < 0:
+ raise MergeError("tolerance must be positive")
+
else:
- raise MergeError("key must be integer or timestamp")
+ raise MergeError("key must be integer, timestamp or float")
# validate allow_exact_matches
if not is_bool(self.allow_exact_matches):
diff --git a/pandas/tests/reshape/merge/test_merge_asof.py b/pandas/tests/reshape/merge/test_merge_asof.py
index d5df9d3820fdc..c75a6a707cafc 100644
--- a/pandas/tests/reshape/merge/test_merge_asof.py
+++ b/pandas/tests/reshape/merge/test_merge_asof.py
@@ -642,6 +642,21 @@ def test_tolerance_tz(self):
'value2': list("BCDEE")})
assert_frame_equal(result, expected)
+ def test_tolerance_float(self):
+ # GH22981
+ left = pd.DataFrame({'a': [1.1, 3.5, 10.9],
+ 'left_val': ['a', 'b', 'c']})
+ right = pd.DataFrame({'a': [1.0, 2.5, 3.3, 7.5, 11.5],
+ 'right_val': [1.0, 2.5, 3.3, 7.5, 11.5]})
+
+ expected = pd.DataFrame({'a': [1.1, 3.5, 10.9],
+ 'left_val': ['a', 'b', 'c'],
+ 'right_val': [1, 3.3, np.nan]})
+
+ result = pd.merge_asof(left, right, on='a', direction='nearest',
+ tolerance=0.5)
+ assert_frame_equal(result, expected)
+
def test_index_tolerance(self):
# GH 15135
expected = self.tolerance.set_index('time')
| Fix bug with merge_asof when merging on floats and selecting a tolerance
- [ ] closes #22981
- [ ] tests added / passed
- [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/22982 | 2018-10-03T19:08:28Z | 2018-10-04T23:29:07Z | 2018-10-04T23:29:07Z | 2018-10-17T06:02:50Z |
DOC: Documentation for pandas.core.indexes.api | diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py
index e50a4b099a8e1..4929710d416e7 100644
--- a/pandas/core/indexes/api.py
+++ b/pandas/core/indexes/api.py
@@ -44,9 +44,28 @@
def _get_objs_combined_axis(objs, intersect=False, axis=0, sort=True):
- # Extract combined index: return intersection or union (depending on the
- # value of "intersect") of indexes on given axis, or None if all objects
- # lack indexes (e.g. they are numpy arrays)
+ """
+ Extract combined index: return intersection or union (depending on the
+ value of "intersect") of indexes on given axis, or None if all objects
+ lack indexes (e.g. they are numpy arrays).
+
+ Parameters
+ ----------
+ objs : list of objects
+ Each object will only be considered if it has a _get_axis
+ attribute.
+ intersect : bool, default False
+ If True, calculate the intersection between indexes. Otherwise,
+ calculate the union.
+ axis : {0 or 'index', 1 or 'outer'}, default 0
+ The axis to extract indexes from.
+ sort : bool, default True
+ Whether the result index should come out sorted or not.
+
+ Returns
+ -------
+ Index
+ """
obs_idxes = [obj._get_axis(axis) for obj in objs
if hasattr(obj, '_get_axis')]
if obs_idxes:
@@ -54,6 +73,24 @@ def _get_objs_combined_axis(objs, intersect=False, axis=0, sort=True):
def _get_combined_index(indexes, intersect=False, sort=False):
+ """
+ Return the union or intersection of indexes.
+
+ Parameters
+ ----------
+ indexes : list of Index or list objects
+ When intersect=True, do not accept list of lists.
+ intersect : bool, default False
+ If True, calculate the intersection between indexes. Otherwise,
+ calculate the union.
+ sort : bool, default False
+ Whether the result index should come out sorted or not.
+
+ Returns
+ -------
+ Index
+ """
+
# TODO: handle index names!
indexes = com.get_distinct_objs(indexes)
if len(indexes) == 0:
@@ -77,6 +114,21 @@ def _get_combined_index(indexes, intersect=False, sort=False):
def _union_indexes(indexes, sort=True):
+ """
+ Return the union of indexes.
+
+ The behavior of sort and names is not consistent.
+
+ Parameters
+ ----------
+ indexes : list of Index or list objects
+ sort : bool, default True
+ Whether the result index should come out sorted or not.
+
+ Returns
+ -------
+ Index
+ """
if len(indexes) == 0:
raise AssertionError('Must have at least 1 Index to union')
if len(indexes) == 1:
@@ -88,6 +140,19 @@ def _union_indexes(indexes, sort=True):
indexes, kind = _sanitize_and_check(indexes)
def _unique_indices(inds):
+ """
+ Convert indexes to lists and concatenate them, removing duplicates.
+
+ The final dtype is inferred.
+
+ Parameters
+ ----------
+ inds : list of Index or list objects
+
+ Returns
+ -------
+ Index
+ """
def conv(i):
if isinstance(i, Index):
i = i.tolist()
@@ -126,6 +191,26 @@ def conv(i):
def _sanitize_and_check(indexes):
+ """
+ Verify the type of indexes and convert lists to Index.
+
+ Cases:
+
+ - [list, list, ...]: Return ([list, list, ...], 'list')
+ - [list, Index, ...]: Return _sanitize_and_check([Index, Index, ...])
+ Lists are sorted and converted to Index.
+ - [Index, Index, ...]: Return ([Index, Index, ...], TYPE)
+ TYPE = 'special' if at least one special type, 'array' otherwise.
+
+ Parameters
+ ----------
+ indexes : list of Index or list objects
+
+ Returns
+ -------
+ sanitized_indexes : list of Index or list objects
+ type : {'list', 'array', 'special'}
+ """
kinds = list({type(index) for index in indexes})
if list in kinds:
@@ -144,6 +229,21 @@ def _sanitize_and_check(indexes):
def _get_consensus_names(indexes):
+ """
+ Give a consensus 'names' to indexes.
+
+ If there's exactly one non-empty 'names', return this,
+ otherwise, return empty.
+
+ Parameters
+ ----------
+ indexes : list of Index objects
+
+ Returns
+ -------
+ list
+ A list representing the consensus 'names' found.
+ """
# find the non-none names, need to tupleify to make
# the set hashable, then reverse on return
@@ -155,6 +255,18 @@ def _get_consensus_names(indexes):
def _all_indexes_same(indexes):
+ """
+ Determine if all indexes contain the same elements.
+
+ Parameters
+ ----------
+ indexes : list of Index objects
+
+ Returns
+ -------
+ bool
+ True if all indexes contain the same elements, False otherwise.
+ """
first = indexes[0]
for index in indexes[1:]:
if not first.equals(index):
| The functions on pandas.core.indexes.api had almost no documentation. This is an attempt to explain them better and a progress towards #22915. | https://api.github.com/repos/pandas-dev/pandas/pulls/22980 | 2018-10-03T18:52:47Z | 2018-11-04T09:56:13Z | 2018-11-04T09:56:13Z | 2018-11-04T09:56:28Z |
Fix ASV import error | diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py
index c5b147b152aa6..2850fa249725c 100644
--- a/asv_bench/benchmarks/indexing.py
+++ b/asv_bench/benchmarks/indexing.py
@@ -2,10 +2,10 @@
import numpy as np
import pandas.util.testing as tm
-from pandas import (Series, DataFrame, MultiIndex, Int64Index, Float64Index,
- IntervalIndex, CategoricalIndex,
- IndexSlice, concat, date_range)
-from .pandas_vb_common import setup, Panel # noqa
+from pandas import (Series, DataFrame, MultiIndex, Panel,
+ Int64Index, Float64Index, IntervalIndex,
+ CategoricalIndex, IndexSlice, concat, date_range)
+from .pandas_vb_common import setup # noqa
class NumericSeriesIndexing(object):
diff --git a/asv_bench/benchmarks/join_merge.py b/asv_bench/benchmarks/join_merge.py
index 7487a0d8489b7..6624c3d0aaf49 100644
--- a/asv_bench/benchmarks/join_merge.py
+++ b/asv_bench/benchmarks/join_merge.py
@@ -3,14 +3,15 @@
import numpy as np
import pandas.util.testing as tm
-from pandas import (DataFrame, Series, MultiIndex, date_range, concat, merge,
- merge_asof)
+from pandas import (DataFrame, Series, Panel, MultiIndex,
+ date_range, concat, merge, merge_asof)
+
try:
from pandas import merge_ordered
except ImportError:
from pandas import ordered_merge as merge_ordered
-from .pandas_vb_common import Panel, setup # noqa
+from .pandas_vb_common import setup # noqa
class Append(object):
diff --git a/asv_bench/benchmarks/panel_ctor.py b/asv_bench/benchmarks/panel_ctor.py
index ce946c76ed199..4614bbd198afa 100644
--- a/asv_bench/benchmarks/panel_ctor.py
+++ b/asv_bench/benchmarks/panel_ctor.py
@@ -1,9 +1,9 @@
import warnings
from datetime import datetime, timedelta
-from pandas import DataFrame, DatetimeIndex, date_range
+from pandas import DataFrame, Panel, DatetimeIndex, date_range
-from .pandas_vb_common import Panel, setup # noqa
+from .pandas_vb_common import setup # noqa
class DifferentIndexes(object):
diff --git a/asv_bench/benchmarks/panel_methods.py b/asv_bench/benchmarks/panel_methods.py
index a5b1a92e9cf67..4d19e9a87c507 100644
--- a/asv_bench/benchmarks/panel_methods.py
+++ b/asv_bench/benchmarks/panel_methods.py
@@ -1,8 +1,9 @@
import warnings
import numpy as np
+from pandas import Panel
-from .pandas_vb_common import Panel, setup # noqa
+from .pandas_vb_common import setup # noqa
class PanelMethods(object):
| #22886 removed `from pandas import Panel` (a left-over from waiting to deprecating `WidePanel`, I believe) from `asv_bench/benchmarks/pandas_vb_common.py` due to linting, and now several benchmarks are failing because they try
```
from .pandas_vb_common import setup, Panel # noqa
```
This fixes the imports, by adding `Panel` to the other pandas-import appropriately.
The larger question is if the ASV code should be part of the CI somehow to catch such errors. There's a way to execute them in minimal form with `asv dev` (corresponding to `asv run --python=same --quick --show-stderr --dry-run`), see https://asv.readthedocs.io/en/stable/writing_benchmarks.html#running-benchmarks-during-development | https://api.github.com/repos/pandas-dev/pandas/pulls/22978 | 2018-10-03T16:05:06Z | 2018-10-04T01:34:35Z | 2018-10-04T01:34:35Z | 2018-10-05T16:21:36Z |
Safer is dtype | diff --git a/.travis.yml b/.travis.yml
index 40baee2c03ea0..c9bdb91283d42 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -53,11 +53,7 @@ matrix:
- dist: trusty
env:
- JOB="3.6, coverage" ENV_FILE="ci/travis-36.yaml" TEST_ARGS="--skip-slow --skip-network" PANDAS_TESTING_MODE="deprecate" COVERAGE=true DOCTEST=true
- # In allow_failures
- - dist: trusty
- env:
- - JOB="3.6, slow" ENV_FILE="ci/travis-36-slow.yaml" SLOW=true
- # In allow_failures
+
- dist: trusty
env:
- JOB="3.7, NumPy dev" ENV_FILE="ci/travis-37-numpydev.yaml" TEST_ARGS="--skip-slow --skip-network -W error" PANDAS_TESTING_MODE="deprecate"
@@ -65,6 +61,12 @@ matrix:
apt:
packages:
- xsel
+
+ # In allow_failures
+ - dist: trusty
+ env:
+ - JOB="3.6, slow" ENV_FILE="ci/travis-36-slow.yaml" SLOW=true
+
# In allow_failures
- dist: trusty
env:
@@ -73,13 +75,6 @@ matrix:
- dist: trusty
env:
- JOB="3.6, slow" ENV_FILE="ci/travis-36-slow.yaml" SLOW=true
- - dist: trusty
- env:
- - JOB="3.7, NumPy dev" ENV_FILE="ci/travis-37-numpydev.yaml" TEST_ARGS="--skip-slow --skip-network -W error" PANDAS_TESTING_MODE="deprecate"
- addons:
- apt:
- packages:
- - xsel
- dist: trusty
env:
- JOB="3.6, doc" ENV_FILE="ci/travis-36-doc.yaml" DOC=true
diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py
index a552251ebbafa..db0a917aefb85 100644
--- a/pandas/core/dtypes/base.py
+++ b/pandas/core/dtypes/base.py
@@ -2,6 +2,7 @@
import numpy as np
from pandas import compat
+from pandas.core.dtypes.generic import ABCSeries, ABCIndexClass, ABCDataFrame
from pandas.errors import AbstractMethodError
@@ -83,7 +84,12 @@ def is_dtype(cls, dtype):
"""
dtype = getattr(dtype, 'dtype', dtype)
- if isinstance(dtype, np.dtype):
+ if isinstance(dtype, (ABCSeries, ABCIndexClass,
+ ABCDataFrame, np.dtype)):
+ # https://github.com/pandas-dev/pandas/issues/22960
+ # avoid passing data to `construct_from_string`. This could
+ # cause a FutureWarning from numpy about failing elementwise
+ # comparison from, e.g., comparing DataFrame == 'category'.
return False
elif dtype is None:
return False
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index ff7590f6d5358..f4b7ccb0fdf5b 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4908,7 +4908,8 @@ def _combine_match_index(self, other, func, level=None):
return ops.dispatch_to_series(left, right, func)
else:
# fastpath --> operate directly on values
- new_data = func(left.values.T, right.values).T
+ with np.errstate(all="ignore"):
+ new_data = func(left.values.T, right.values).T
return self._constructor(new_data,
index=left.index, columns=self.columns,
copy=False)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 82198c2b3edd5..fde83237b23d7 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -4224,7 +4224,7 @@ def _try_cast(arr, take_fast_path):
try:
# gh-15832: Check if we are requesting a numeric dype and
# that we can convert the data to the requested dtype.
- if is_float_dtype(dtype) or is_integer_dtype(dtype):
+ if is_integer_dtype(dtype):
subarr = maybe_cast_to_integer_array(arr, dtype)
subarr = maybe_cast_to_datetime(arr, dtype)
diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py
index e3d14497a38f9..7e95b076a8a66 100644
--- a/pandas/tests/dtypes/test_dtypes.py
+++ b/pandas/tests/dtypes/test_dtypes.py
@@ -815,3 +815,23 @@ def test_registry_find(dtype, expected):
('datetime64[ns, US/Eastern]', DatetimeTZDtype('ns', 'US/Eastern'))])
def test_pandas_registry_find(dtype, expected):
assert _pandas_registry.find(dtype) == expected
+
+
+@pytest.mark.parametrize("check", [
+ is_categorical_dtype,
+ is_datetime64tz_dtype,
+ is_period_dtype,
+ is_datetime64_ns_dtype,
+ is_datetime64_dtype,
+ is_interval_dtype,
+ is_datetime64_any_dtype,
+ is_string_dtype,
+ is_bool_dtype,
+])
+def test_is_dtype_no_warning(check):
+ data = pd.DataFrame({"A": [1, 2]})
+ with tm.assert_produces_warning(None):
+ check(data)
+
+ with tm.assert_produces_warning(None):
+ check(data["A"])
diff --git a/pandas/tests/frame/test_operators.py b/pandas/tests/frame/test_operators.py
index 97c94e1134cc8..6ed289614b96a 100644
--- a/pandas/tests/frame/test_operators.py
+++ b/pandas/tests/frame/test_operators.py
@@ -1030,3 +1030,9 @@ def test_alignment_non_pandas(self):
align(df, val, 'index')
with pytest.raises(ValueError):
align(df, val, 'columns')
+
+ def test_no_warning(self, all_arithmetic_operators):
+ df = pd.DataFrame({"A": [0., 0.], "B": [0., None]})
+ b = df['B']
+ with tm.assert_produces_warning(None):
+ getattr(df, all_arithmetic_operators)(b, 0)
| Closes https://github.com/pandas-dev/pandas/issues/22960 | https://api.github.com/repos/pandas-dev/pandas/pulls/22975 | 2018-10-03T13:43:12Z | 2018-10-04T11:30:30Z | 2018-10-04T11:30:30Z | 2018-10-04T17:35:46Z |
TST: Fixturize series/test_missing.py | diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py
index ab3fdd8cbf84f..b3f105ee5cb67 100644
--- a/pandas/tests/series/test_missing.py
+++ b/pandas/tests/series/test_missing.py
@@ -21,8 +21,6 @@
import pandas.util.testing as tm
import pandas.util._test_decorators as td
-from .common import TestData
-
try:
import scipy
_is_scipy_ge_0190 = (LooseVersion(scipy.__version__) >=
@@ -52,7 +50,7 @@ def _simple_ts(start, end, freq='D'):
return Series(np.random.randn(len(rng)), index=rng)
-class TestSeriesMissingData(TestData):
+class TestSeriesMissingData():
def test_remove_na_deprecation(self):
# see gh-16971
@@ -489,7 +487,7 @@ def test_isnull_for_inf_deprecated(self):
tm.assert_series_equal(r, e)
tm.assert_series_equal(dr, de)
- def test_fillna(self):
+ def test_fillna(self, datetime_series):
ts = Series([0., 1., 2., 3., 4.], index=tm.makeDateIndex(5))
tm.assert_series_equal(ts, ts.fillna(method='ffill'))
@@ -506,7 +504,8 @@ def test_fillna(self):
tm.assert_series_equal(ts.fillna(value=5), exp)
pytest.raises(ValueError, ts.fillna)
- pytest.raises(ValueError, self.ts.fillna, value=0, method='ffill')
+ pytest.raises(ValueError, datetime_series.fillna, value=0,
+ method='ffill')
# GH 5703
s1 = Series([np.nan])
@@ -576,9 +575,9 @@ def test_fillna_inplace(self):
expected = x.fillna(value=0)
assert_series_equal(y, expected)
- def test_fillna_invalid_method(self):
+ def test_fillna_invalid_method(self, datetime_series):
try:
- self.ts.fillna(method='ffil')
+ datetime_series.fillna(method='ffil')
except ValueError as inst:
assert 'ffil' in str(inst)
@@ -632,8 +631,8 @@ def test_timedelta64_nan(self):
# def test_logical_range_select(self):
# np.random.seed(12345)
- # selector = -0.5 <= self.ts <= 0.5
- # expected = (self.ts >= -0.5) & (self.ts <= 0.5)
+ # selector = -0.5 <= datetime_series <= 0.5
+ # expected = (datetime_series >= -0.5) & (datetime_series <= 0.5)
# assert_series_equal(selector, expected)
def test_dropna_empty(self):
@@ -688,8 +687,8 @@ def test_dropna_intervals(self):
expected = s.iloc[1:]
assert_series_equal(result, expected)
- def test_valid(self):
- ts = self.ts.copy()
+ def test_valid(self, datetime_series):
+ ts = datetime_series.copy()
ts[::2] = np.NaN
result = ts.dropna()
@@ -734,12 +733,12 @@ def test_pad_require_monotonicity(self):
pytest.raises(ValueError, rng2.get_indexer, rng, method='pad')
- def test_dropna_preserve_name(self):
- self.ts[:5] = np.nan
- result = self.ts.dropna()
- assert result.name == self.ts.name
- name = self.ts.name
- ts = self.ts.copy()
+ def test_dropna_preserve_name(self, datetime_series):
+ datetime_series[:5] = np.nan
+ result = datetime_series.dropna()
+ assert result.name == datetime_series.name
+ name = datetime_series.name
+ ts = datetime_series.copy()
ts.dropna(inplace=True)
assert ts.name == name
@@ -825,10 +824,11 @@ def test_series_pad_backfill_limit(self):
assert_series_equal(result, expected)
-class TestSeriesInterpolateData(TestData):
+class TestSeriesInterpolateData():
- def test_interpolate(self):
- ts = Series(np.arange(len(self.ts), dtype=float), self.ts.index)
+ def test_interpolate(self, datetime_series, string_series):
+ ts = Series(np.arange(len(datetime_series), dtype=float),
+ datetime_series.index)
ts_copy = ts.copy()
ts_copy[5:10] = np.NaN
@@ -836,8 +836,8 @@ def test_interpolate(self):
linear_interp = ts_copy.interpolate(method='linear')
tm.assert_series_equal(linear_interp, ts)
- ord_ts = Series([d.toordinal() for d in self.ts.index],
- index=self.ts.index).astype(float)
+ ord_ts = Series([d.toordinal() for d in datetime_series.index],
+ index=datetime_series.index).astype(float)
ord_ts_copy = ord_ts.copy()
ord_ts_copy[5:10] = np.NaN
@@ -847,7 +847,7 @@ def test_interpolate(self):
# try time interpolation on a non-TimeSeries
# Only raises ValueError if there are NaNs.
- non_ts = self.series.copy()
+ non_ts = string_series.copy()
non_ts[0] = np.NaN
pytest.raises(ValueError, non_ts.interpolate, method='time')
| This is in reference to issue #22550 | https://api.github.com/repos/pandas-dev/pandas/pulls/22973 | 2018-10-03T09:36:05Z | 2018-10-04T11:20:47Z | 2018-10-04T11:20:47Z | 2018-10-04T11:20:51Z |
TST: Fixturize series/test_io.py | diff --git a/pandas/tests/series/test_io.py b/pandas/tests/series/test_io.py
index cbf9bff06ad34..50f548b855247 100644
--- a/pandas/tests/series/test_io.py
+++ b/pandas/tests/series/test_io.py
@@ -16,10 +16,8 @@
assert_frame_equal, ensure_clean)
import pandas.util.testing as tm
-from .common import TestData
-
-class TestSeriesToCSV(TestData):
+class TestSeriesToCSV():
def read_csv(self, path, **kwargs):
params = dict(squeeze=True, index_col=0,
@@ -34,10 +32,10 @@ def read_csv(self, path, **kwargs):
return out
- def test_from_csv_deprecation(self):
+ def test_from_csv_deprecation(self, datetime_series):
# see gh-17812
with ensure_clean() as path:
- self.ts.to_csv(path, header=False)
+ datetime_series.to_csv(path, header=False)
with tm.assert_produces_warning(FutureWarning,
check_stacklevel=False):
@@ -46,7 +44,7 @@ def test_from_csv_deprecation(self):
assert_series_equal(depr_ts, ts)
@pytest.mark.parametrize("arg", ["path", "header", "both"])
- def test_to_csv_deprecation(self, arg):
+ def test_to_csv_deprecation(self, arg, datetime_series):
# see gh-19715
with ensure_clean() as path:
if arg == "path":
@@ -57,18 +55,18 @@ def test_to_csv_deprecation(self, arg):
kwargs = dict(path=path)
with tm.assert_produces_warning(FutureWarning):
- self.ts.to_csv(**kwargs)
+ datetime_series.to_csv(**kwargs)
# Make sure roundtrip still works.
ts = self.read_csv(path)
- assert_series_equal(self.ts, ts, check_names=False)
+ assert_series_equal(datetime_series, ts, check_names=False)
- def test_from_csv(self):
+ def test_from_csv(self, datetime_series, string_series):
with ensure_clean() as path:
- self.ts.to_csv(path, header=False)
+ datetime_series.to_csv(path, header=False)
ts = self.read_csv(path)
- assert_series_equal(self.ts, ts, check_names=False)
+ assert_series_equal(datetime_series, ts, check_names=False)
assert ts.name is None
assert ts.index.name is None
@@ -79,18 +77,18 @@ def test_from_csv(self):
assert_series_equal(depr_ts, ts)
# see gh-10483
- self.ts.to_csv(path, header=True)
+ datetime_series.to_csv(path, header=True)
ts_h = self.read_csv(path, header=0)
assert ts_h.name == "ts"
- self.series.to_csv(path, header=False)
+ string_series.to_csv(path, header=False)
series = self.read_csv(path)
- assert_series_equal(self.series, series, check_names=False)
+ assert_series_equal(string_series, series, check_names=False)
assert series.name is None
assert series.index.name is None
- self.series.to_csv(path, header=True)
+ string_series.to_csv(path, header=True)
series_h = self.read_csv(path, header=0)
assert series_h.name == "series"
@@ -106,19 +104,19 @@ def test_from_csv(self):
check_series = Series({"1998-01-01": 1.0, "1999-01-01": 2.0})
assert_series_equal(check_series, series)
- def test_to_csv(self):
+ def test_to_csv(self, datetime_series):
import io
with ensure_clean() as path:
- self.ts.to_csv(path, header=False)
+ datetime_series.to_csv(path, header=False)
with io.open(path, newline=None) as f:
lines = f.readlines()
assert (lines[1] != '\n')
- self.ts.to_csv(path, index=False, header=False)
+ datetime_series.to_csv(path, index=False, header=False)
arr = np.loadtxt(path)
- assert_almost_equal(arr, self.ts.values)
+ assert_almost_equal(arr, datetime_series.values)
def test_to_csv_unicode_index(self):
buf = StringIO()
@@ -196,22 +194,23 @@ def test_to_csv_compression(self, s, encoding, compression):
encoding=encoding))
-class TestSeriesIO(TestData):
+class TestSeriesIO():
- def test_to_frame(self):
- self.ts.name = None
- rs = self.ts.to_frame()
- xp = pd.DataFrame(self.ts.values, index=self.ts.index)
+ def test_to_frame(self, datetime_series):
+ datetime_series.name = None
+ rs = datetime_series.to_frame()
+ xp = pd.DataFrame(datetime_series.values, index=datetime_series.index)
assert_frame_equal(rs, xp)
- self.ts.name = 'testname'
- rs = self.ts.to_frame()
- xp = pd.DataFrame(dict(testname=self.ts.values), index=self.ts.index)
+ datetime_series.name = 'testname'
+ rs = datetime_series.to_frame()
+ xp = pd.DataFrame(dict(testname=datetime_series.values),
+ index=datetime_series.index)
assert_frame_equal(rs, xp)
- rs = self.ts.to_frame(name='testdifferent')
- xp = pd.DataFrame(
- dict(testdifferent=self.ts.values), index=self.ts.index)
+ rs = datetime_series.to_frame(name='testdifferent')
+ xp = pd.DataFrame(dict(testdifferent=datetime_series.values),
+ index=datetime_series.index)
assert_frame_equal(rs, xp)
def test_timeseries_periodindex(self):
@@ -256,11 +255,12 @@ class SubclassedFrame(DataFrame):
dict,
collections.defaultdict(list),
collections.OrderedDict))
- def test_to_dict(self, mapping):
+ def test_to_dict(self, mapping, datetime_series):
# GH16122
- ts = TestData().ts
tm.assert_series_equal(
- Series(ts.to_dict(mapping), name='ts'), ts)
- from_method = Series(ts.to_dict(collections.Counter))
- from_constructor = Series(collections.Counter(ts.iteritems()))
+ Series(datetime_series.to_dict(mapping), name='ts'),
+ datetime_series)
+ from_method = Series(datetime_series.to_dict(collections.Counter))
+ from_constructor = Series(collections
+ .Counter(datetime_series.iteritems()))
tm.assert_series_equal(from_method, from_constructor)
| This is in reference to issue #22550 | https://api.github.com/repos/pandas-dev/pandas/pulls/22972 | 2018-10-03T09:23:48Z | 2018-10-04T11:21:46Z | 2018-10-04T11:21:46Z | 2018-10-04T11:21:49Z |
DOC: fixed doc-string for combine & combine_first in pandas/core/series.py | diff --git a/pandas/core/series.py b/pandas/core/series.py
index 892b24f6ee552..b20bcad2aa09f 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2281,37 +2281,71 @@ def _binop(self, other, func, level=None, fill_value=None):
def combine(self, other, func, fill_value=None):
"""
- Perform elementwise binary operation on two Series using given function
- with optional fill value when an index is missing from one Series or
- the other
+ Combine the Series with a Series or scalar according to `func`.
+
+ Combine the Series and `other` using `func` to perform elementwise
+ selection for combined Series.
+ `fill_value` is assumed when value is missing at some index
+ from one of the two objects being combined.
Parameters
----------
- other : Series or scalar value
+ other : Series or scalar
+ The value(s) to be combined with the `Series`.
func : function
- Function that takes two scalars as inputs and return a scalar
- fill_value : scalar value
- The default specifies to use the appropriate NaN value for
- the underlying dtype of the Series
+ Function that takes two scalars as inputs and returns an element.
+ fill_value : scalar, optional
+ The value to assume when an index is missing from
+ one Series or the other. The default specifies to use the
+ appropriate NaN value for the underlying dtype of the Series.
Returns
-------
- result : Series
-
- Examples
- --------
- >>> s1 = pd.Series([1, 2])
- >>> s2 = pd.Series([0, 3])
- >>> s1.combine(s2, lambda x1, x2: x1 if x1 < x2 else x2)
- 0 0
- 1 2
- dtype: int64
+ Series
+ The result of combining the Series with the other object.
See Also
--------
Series.combine_first : Combine Series values, choosing the calling
- Series's values first.
- """
+ Series' values first.
+
+ Examples
+ --------
+ Consider 2 Datasets ``s1`` and ``s2`` containing
+ highest clocked speeds of different birds.
+
+ >>> s1 = pd.Series({'falcon': 330.0, 'eagle': 160.0})
+ >>> s1
+ falcon 330.0
+ eagle 160.0
+ dtype: float64
+ >>> s2 = pd.Series({'falcon': 345.0, 'eagle': 200.0, 'duck': 30.0})
+ >>> s2
+ falcon 345.0
+ eagle 200.0
+ duck 30.0
+ dtype: float64
+
+ Now, to combine the two datasets and view the highest speeds
+ of the birds across the two datasets
+
+ >>> s1.combine(s2, max)
+ duck NaN
+ eagle 200.0
+ falcon 345.0
+ dtype: float64
+
+ In the previous example, the resulting value for duck is missing,
+ because the maximum of a NaN and a float is a NaN.
+ So, in the example, we set ``fill_value=0``,
+ so the maximum value returned will be the value from some dataset.
+
+ >>> s1.combine(s2, max, fill_value=0)
+ duck 30.0
+ eagle 200.0
+ falcon 345.0
+ dtype: float64
+"""
if fill_value is None:
fill_value = na_value_for_dtype(self.dtype, compat=False)
@@ -2352,16 +2386,26 @@ def combine(self, other, func, fill_value=None):
def combine_first(self, other):
"""
- Combine Series values, choosing the calling Series's values
- first. Result index will be the union of the two indexes
+ Combine Series values, choosing the calling Series's values first.
Parameters
----------
other : Series
+ The value(s) to be combined with the `Series`.
Returns
-------
- combined : Series
+ Series
+ The result of combining the Series with the other object.
+
+ See Also
+ --------
+ Series.combine : Perform elementwise operation on two Series
+ using a given function.
+
+ Notes
+ -----
+ Result index will be the union of the two indexes.
Examples
--------
@@ -2371,11 +2415,6 @@ def combine_first(self, other):
0 1.0
1 4.0
dtype: float64
-
- See Also
- --------
- Series.combine : Perform elementwise operation on two Series
- using a given function.
"""
new_index = self.index.union(other.index)
this = self.reindex(new_index, copy=False)
| - [x] closes #22953
- [ ] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/22971 | 2018-10-03T09:21:50Z | 2018-11-21T12:48:25Z | 2018-11-21T12:48:25Z | 2019-03-27T12:35:19Z |
DOC: Fixed the doctsring for _set_axis_name (GH 22895) | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index dde671993a56b..97ea4fb96ce95 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -1109,16 +1109,15 @@ def rename(self, *args, **kwargs):
('inplace', False)])
def rename_axis(self, mapper=None, **kwargs):
"""
- Alter the name of the index or name of Index object that is the
- columns.
+ Set the name of the axis for the index or columns.
Parameters
----------
mapper : scalar, list-like, optional
Value to set the axis name attribute.
index, columns : scalar, list-like, dict-like or function, optional
- dict-like or functions transformations to apply to
- that axis' values.
+ A scalar, list-like, dict-like or functions transformations to
+ apply to that axis' values.
Use either ``mapper`` and ``axis`` to
specify the axis to target with ``mapper``, or ``index``
@@ -1126,18 +1125,25 @@ def rename_axis(self, mapper=None, **kwargs):
.. versionchanged:: 0.24.0
- axis : int or string, default 0
- copy : boolean, default True
+ axis : {0 or 'index', 1 or 'columns'}, default 0
+ The axis to rename.
+ copy : bool, default True
Also copy underlying data.
- inplace : boolean, default False
+ inplace : bool, default False
Modifies the object directly, instead of creating a new Series
or DataFrame.
Returns
-------
- renamed : Series, DataFrame, or None
+ Series, DataFrame, or None
The same type as the caller or None if `inplace` is True.
+ See Also
+ --------
+ Series.rename : Alter Series index labels or name.
+ DataFrame.rename : Alter DataFrame index labels or name.
+ Index.rename : Set new names on index.
+
Notes
-----
Prior to version 0.21.0, ``rename_axis`` could also be used to change
@@ -1162,75 +1168,73 @@ def rename_axis(self, mapper=None, **kwargs):
We *highly* recommend using keyword arguments to clarify your
intent.
- See Also
- --------
- Series.rename : Alter Series index labels or name.
- DataFrame.rename : Alter DataFrame index labels or name.
- Index.rename : Set new names on index.
-
Examples
--------
**Series**
- >>> s = pd.Series([1, 2, 3])
- >>> s.rename_axis("foo")
- foo
- 0 1
- 1 2
- 2 3
- dtype: int64
+ >>> s = pd.Series(["dog", "cat", "monkey"])
+ >>> s
+ 0 dog
+ 1 cat
+ 2 monkey
+ dtype: object
+ >>> s.rename_axis("animal")
+ animal
+ 0 dog
+ 1 cat
+ 2 monkey
+ dtype: object
**DataFrame**
- >>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
- >>> df.rename_axis("foo")
- A B
- foo
- 0 1 4
- 1 2 5
- 2 3 6
-
- >>> df.rename_axis("bar", axis="columns")
- bar A B
- 0 1 4
- 1 2 5
- 2 3 6
-
- >>> mi = pd.MultiIndex.from_product([['a', 'b', 'c'], [1, 2]],
- ... names=['let','num'])
- >>> df = pd.DataFrame({'x': [i for i in range(len(mi))],
- ... 'y' : [i*10 for i in range(len(mi))]},
- ... index=mi)
- >>> df.rename_axis(index={'num' : 'n'})
- x y
- let n
- a 1 0 0
- 2 1 10
- b 1 2 20
- 2 3 30
- c 1 4 40
- 2 5 50
-
- >>> cdf = df.rename_axis(columns='col')
- >>> cdf
- col x y
- let num
- a 1 0 0
- 2 1 10
- b 1 2 20
- 2 3 30
- c 1 4 40
- 2 5 50
-
- >>> cdf.rename_axis(columns=str.upper)
- COL x y
- let num
- a 1 0 0
- 2 1 10
- b 1 2 20
- 2 3 30
- c 1 4 40
- 2 5 50
+ >>> df = pd.DataFrame({"num_legs": [4, 4, 2],
+ ... "num_arms": [0, 0, 2]},
+ ... ["dog", "cat", "monkey"])
+ >>> df
+ num_legs num_arms
+ dog 4 0
+ cat 4 0
+ monkey 2 2
+ >>> df = df.rename_axis("animal")
+ >>> df
+ num_legs num_arms
+ animal
+ dog 4 0
+ cat 4 0
+ monkey 2 2
+ >>> df = df.rename_axis("limbs", axis="columns")
+ >>> df
+ limbs num_legs num_arms
+ animal
+ dog 4 0
+ cat 4 0
+ monkey 2 2
+
+ **MultiIndex**
+
+ >>> df.index = pd.MultiIndex.from_product([['mammal'],
+ ... ['dog', 'cat', 'monkey']],
+ ... names=['type', 'name'])
+ >>> df
+ limbs num_legs num_arms
+ type name
+ mammal dog 4 0
+ cat 4 0
+ monkey 2 2
+
+ >>> df.rename_axis(index={'type': 'class'})
+ limbs num_legs num_arms
+ class name
+ mammal dog 4 0
+ cat 4 0
+ monkey 2 2
+
+ >>> df.rename_axis(columns=str.upper)
+ LIMBS num_legs num_arms
+ type name
+ mammal dog 4 0
+ cat 4 0
+ monkey 2 2
"""
axes, kwargs = self._construct_axes_from_arguments((), kwargs)
copy = kwargs.pop('copy', True)
@@ -1285,45 +1289,57 @@ def rename_axis(self, mapper=None, **kwargs):
def _set_axis_name(self, name, axis=0, inplace=False):
"""
- Alter the name or names of the axis.
+ Set the name(s) of the axis.
Parameters
----------
name : str or list of str
- Name for the Index, or list of names for the MultiIndex
- axis : int or str
- 0 or 'index' for the index; 1 or 'columns' for the columns
- inplace : bool
- whether to modify `self` directly or return a copy
+ Name(s) to set.
+ axis : {0 or 'index', 1 or 'columns'}, default 0
+ The axis to set the label. The value 0 or 'index' specifies index,
+ and the value 1 or 'columns' specifies columns.
+ inplace : bool, default False
+ If `True`, do operation inplace and return None.
.. versionadded:: 0.21.0
Returns
-------
- renamed : same type as caller or None if inplace=True
+ Series, DataFrame, or None
+ The same type as the caller or `None` if `inplace` is `True`.
See Also
--------
- pandas.DataFrame.rename
- pandas.Series.rename
- pandas.Index.rename
+ DataFrame.rename : Alter the axis labels of :class:`DataFrame`.
+ Series.rename : Alter the index labels or set the index name
+ of :class:`Series`.
+ Index.rename : Set the name of :class:`Index` or :class:`MultiIndex`.
Examples
--------
- >>> df._set_axis_name("foo")
- A
- foo
- 0 1
- 1 2
- 2 3
- >>> df.index = pd.MultiIndex.from_product([['A'], ['a', 'b', 'c']])
- >>> df._set_axis_name(["bar", "baz"])
- A
- bar baz
- A a 1
- b 2
- c 3
- """
+ >>> df = pd.DataFrame({"num_legs": [4, 4, 2]},
+ ... ["dog", "cat", "monkey"])
+ >>> df
+ num_legs
+ dog 4
+ cat 4
+ monkey 2
+ >>> df._set_axis_name("animal")
+ num_legs
+ animal
+ dog 4
+ cat 4
+ monkey 2
+ >>> df.index = pd.MultiIndex.from_product(
+ ... [["mammal"], ['dog', 'cat', 'monkey']])
+ >>> df._set_axis_name(["type", "name"])
+ legs
+ type name
+ mammal dog 4
+ cat 4
+ monkey 2
+ """
+ pd.MultiIndex.from_product([["mammal"], ['dog', 'cat', 'monkey']])
axis = self._get_axis_number(axis)
idx = self._get_axis(axis).set_names(name)
| Fixed the docstring of the function `_set_axis_name` in `pandas/core/generic.py`
Closes #22895 | https://api.github.com/repos/pandas-dev/pandas/pulls/22969 | 2018-10-03T09:08:31Z | 2018-11-20T02:21:07Z | 2018-11-20T02:21:07Z | 2018-11-26T15:36:35Z |
TST: Fixturize series/test_dtypes.py | diff --git a/pandas/tests/series/test_dtypes.py b/pandas/tests/series/test_dtypes.py
index 125dff9ecfa7c..63ead2dc7d245 100644
--- a/pandas/tests/series/test_dtypes.py
+++ b/pandas/tests/series/test_dtypes.py
@@ -24,10 +24,8 @@
from pandas import compat
import pandas.util.testing as tm
-from .common import TestData
-
-class TestSeriesDtypes(TestData):
+class TestSeriesDtypes():
def test_dt64_series_astype_object(self):
dt64ser = Series(date_range('20130101', periods=3))
@@ -56,17 +54,17 @@ def test_asobject_deprecated(self):
o = s.asobject
assert isinstance(o, np.ndarray)
- def test_dtype(self):
+ def test_dtype(self, datetime_series):
- assert self.ts.dtype == np.dtype('float64')
- assert self.ts.dtypes == np.dtype('float64')
- assert self.ts.ftype == 'float64:dense'
- assert self.ts.ftypes == 'float64:dense'
- tm.assert_series_equal(self.ts.get_dtype_counts(),
+ assert datetime_series.dtype == np.dtype('float64')
+ assert datetime_series.dtypes == np.dtype('float64')
+ assert datetime_series.ftype == 'float64:dense'
+ assert datetime_series.ftypes == 'float64:dense'
+ tm.assert_series_equal(datetime_series.get_dtype_counts(),
Series(1, ['float64']))
# GH18243 - Assert .get_ftype_counts is deprecated
with tm.assert_produces_warning(FutureWarning):
- tm.assert_series_equal(self.ts.get_ftype_counts(),
+ tm.assert_series_equal(datetime_series.get_ftype_counts(),
Series(1, ['float64:dense']))
@pytest.mark.parametrize("value", [np.nan, np.inf])
| This is in reference to issue #22550 | https://api.github.com/repos/pandas-dev/pandas/pulls/22967 | 2018-10-03T08:59:38Z | 2018-10-04T11:22:22Z | 2018-10-04T11:22:22Z | 2018-10-04T11:23:01Z |
TST: Fixturize series/test_datetime_values.py | diff --git a/pandas/tests/series/test_datetime_values.py b/pandas/tests/series/test_datetime_values.py
index fee2323310b9c..e06d3a67db662 100644
--- a/pandas/tests/series/test_datetime_values.py
+++ b/pandas/tests/series/test_datetime_values.py
@@ -23,10 +23,8 @@
from pandas.util.testing import assert_series_equal
import pandas.util.testing as tm
-from .common import TestData
-
-class TestSeriesDatetimeValues(TestData):
+class TestSeriesDatetimeValues():
def test_dt_namespace_accessor(self):
| This is in reference to issue #22550 | https://api.github.com/repos/pandas-dev/pandas/pulls/22966 | 2018-10-03T08:55:49Z | 2018-10-04T11:23:21Z | 2018-10-04T11:23:21Z | 2018-10-04T11:23:21Z |
TST: Fixturize series/test_constructors.py | diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py
index 4817f5bdccc29..57a3f54fadbcc 100644
--- a/pandas/tests/series/test_constructors.py
+++ b/pandas/tests/series/test_constructors.py
@@ -26,10 +26,8 @@
from pandas.util.testing import assert_series_equal
import pandas.util.testing as tm
-from .common import TestData
-
-class TestSeriesConstructors(TestData):
+class TestSeriesConstructors():
def test_invalid_dtype(self):
# GH15520
@@ -50,23 +48,23 @@ def test_scalar_conversion(self):
assert int(Series([1.])) == 1
assert long(Series([1.])) == 1
- def test_constructor(self):
- assert self.ts.index.is_all_dates
+ def test_constructor(self, datetime_series, empty_series):
+ assert datetime_series.index.is_all_dates
# Pass in Series
- derived = Series(self.ts)
+ derived = Series(datetime_series)
assert derived.index.is_all_dates
- assert tm.equalContents(derived.index, self.ts.index)
+ assert tm.equalContents(derived.index, datetime_series.index)
# Ensure new index is not created
- assert id(self.ts.index) == id(derived.index)
+ assert id(datetime_series.index) == id(derived.index)
# Mixed type Series
mixed = Series(['hello', np.NaN], index=[0, 1])
assert mixed.dtype == np.object_
assert mixed[1] is np.NaN
- assert not self.empty.index.is_all_dates
+ assert not empty_series.index.is_all_dates
assert not Series({}).index.is_all_dates
pytest.raises(Exception, Series, np.random.randn(3, 3),
index=np.arange(3))
@@ -977,27 +975,27 @@ def test_fromDict(self):
series = Series(data, dtype=float)
assert series.dtype == np.float64
- def test_fromValue(self):
+ def test_fromValue(self, datetime_series):
- nans = Series(np.NaN, index=self.ts.index)
+ nans = Series(np.NaN, index=datetime_series.index)
assert nans.dtype == np.float_
- assert len(nans) == len(self.ts)
+ assert len(nans) == len(datetime_series)
- strings = Series('foo', index=self.ts.index)
+ strings = Series('foo', index=datetime_series.index)
assert strings.dtype == np.object_
- assert len(strings) == len(self.ts)
+ assert len(strings) == len(datetime_series)
d = datetime.now()
- dates = Series(d, index=self.ts.index)
+ dates = Series(d, index=datetime_series.index)
assert dates.dtype == 'M8[ns]'
- assert len(dates) == len(self.ts)
+ assert len(dates) == len(datetime_series)
# GH12336
# Test construction of categorical series from value
- categorical = Series(0, index=self.ts.index, dtype="category")
- expected = Series(0, index=self.ts.index).astype("category")
+ categorical = Series(0, index=datetime_series.index, dtype="category")
+ expected = Series(0, index=datetime_series.index).astype("category")
assert categorical.dtype == 'category'
- assert len(categorical) == len(self.ts)
+ assert len(categorical) == len(datetime_series)
tm.assert_series_equal(categorical, expected)
def test_constructor_dtype_timedelta64(self):
| This is in reference to issue #22550 | https://api.github.com/repos/pandas-dev/pandas/pulls/22965 | 2018-10-03T08:46:26Z | 2018-10-04T11:23:40Z | 2018-10-04T11:23:40Z | 2018-10-04T13:27:08Z |
TST: Fixturize series/test_combine_concat.py | diff --git a/pandas/tests/series/test_combine_concat.py b/pandas/tests/series/test_combine_concat.py
index 35ba4fbf0ce25..8b021ab81ff81 100644
--- a/pandas/tests/series/test_combine_concat.py
+++ b/pandas/tests/series/test_combine_concat.py
@@ -15,29 +15,28 @@
from pandas.util.testing import assert_series_equal
import pandas.util.testing as tm
-from .common import TestData
+class TestSeriesCombine():
-class TestSeriesCombine(TestData):
-
- def test_append(self):
- appendedSeries = self.series.append(self.objSeries)
+ def test_append(self, datetime_series, string_series, object_series):
+ appendedSeries = string_series.append(object_series)
for idx, value in compat.iteritems(appendedSeries):
- if idx in self.series.index:
- assert value == self.series[idx]
- elif idx in self.objSeries.index:
- assert value == self.objSeries[idx]
+ if idx in string_series.index:
+ assert value == string_series[idx]
+ elif idx in object_series.index:
+ assert value == object_series[idx]
else:
raise AssertionError("orphaned index!")
- pytest.raises(ValueError, self.ts.append, self.ts,
+ pytest.raises(ValueError, datetime_series.append, datetime_series,
verify_integrity=True)
- def test_append_many(self):
- pieces = [self.ts[:5], self.ts[5:10], self.ts[10:]]
+ def test_append_many(self, datetime_series):
+ pieces = [datetime_series[:5], datetime_series[5:10],
+ datetime_series[10:]]
result = pieces[0].append(pieces[1:])
- assert_series_equal(result, self.ts)
+ assert_series_equal(result, datetime_series)
def test_append_duplicates(self):
# GH 13677
| This is in reference to issue #22550 | https://api.github.com/repos/pandas-dev/pandas/pulls/22964 | 2018-10-03T08:38:21Z | 2018-10-04T11:24:06Z | 2018-10-04T11:24:06Z | 2018-10-04T13:26:53Z |
BUG GH22858 When creating empty dataframe, only cast int to float if index given | diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt
index 9b71ab656920d..606f29ef75ba7 100644
--- a/doc/source/whatsnew/v0.24.0.txt
+++ b/doc/source/whatsnew/v0.24.0.txt
@@ -199,6 +199,7 @@ Other Enhancements
Backwards incompatible API changes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+- A newly constructed empty :class:`DataFrame` with integer as the ``dtype`` will now only be cast to ``float64`` if ``index`` is specified (:issue:`22858`)
.. _whatsnew_0240.api_breaking.interval_values:
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 410e061c895db..a95a45d5f9ae4 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -1220,7 +1220,9 @@ def construct_1d_arraylike_from_scalar(value, length, dtype):
dtype = dtype.dtype
# coerce if we have nan for an integer dtype
- if is_integer_dtype(dtype) and isna(value):
+ # GH 22858: only cast to float if an index
+ # (passed here as length) is specified
+ if length and is_integer_dtype(dtype) and isna(value):
dtype = np.float64
subarr = np.empty(length, dtype=dtype)
subarr.fill(value)
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py
index 2f1c9e05a01b0..e2be410d51b88 100644
--- a/pandas/tests/frame/test_constructors.py
+++ b/pandas/tests/frame/test_constructors.py
@@ -798,25 +798,20 @@ def test_constructor_mrecarray(self):
result = DataFrame(mrecs, index=[1, 2])
assert_fr_equal(result, expected)
- def test_constructor_corner(self):
+ def test_constructor_corner_shape(self):
df = DataFrame(index=[])
assert df.values.shape == (0, 0)
- # empty but with specified dtype
- df = DataFrame(index=lrange(10), columns=['a', 'b'], dtype=object)
- assert df.values.dtype == np.object_
-
- # does not error but ends up float
- df = DataFrame(index=lrange(10), columns=['a', 'b'], dtype=int)
- assert df.values.dtype == np.dtype('float64')
-
- # #1783 empty dtype object
- df = DataFrame({}, columns=['foo', 'bar'])
- assert df.values.dtype == np.object_
-
- df = DataFrame({'b': 1}, index=lrange(10), columns=list('abc'),
- dtype=int)
- assert df.values.dtype == np.dtype('float64')
+ @pytest.mark.parametrize("data, index, columns, dtype, expected", [
+ (None, lrange(10), ['a', 'b'], object, np.object_),
+ (None, None, ['a', 'b'], 'int64', np.dtype('int64')),
+ (None, lrange(10), ['a', 'b'], int, np.dtype('float64')),
+ ({}, None, ['foo', 'bar'], None, np.object_),
+ ({'b': 1}, lrange(10), list('abc'), int, np.dtype('float64'))
+ ])
+ def test_constructor_dtype(self, data, index, columns, dtype, expected):
+ df = DataFrame(data, index, columns, dtype)
+ assert df.values.dtype == expected
def test_constructor_scalar_inference(self):
data = {'int': 1, 'bool': True,
| - [X] closes #22858
- [X] tests added / passed
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Previously, when creating a dataframe with no data of dtype int, the dtype would be changed to float. This is necessary when a predefined number of rows is included as the index parameter, so that they can be filled with nan. However, when no index is passed, this cast is unexpected. This PR changes it so dtype is only altered when necessary. | https://api.github.com/repos/pandas-dev/pandas/pulls/22963 | 2018-10-03T05:22:58Z | 2018-10-04T23:13:58Z | 2018-10-04T23:13:58Z | 2018-10-05T04:34:22Z |
CLN: Move some PI/DTI methods to EA subclasses, implement tests | diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index a0a9b57712249..7daaa8de1734f 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -31,7 +31,7 @@
from pandas.core.algorithms import checked_add_with_arr
from pandas.core import ops
-from pandas.tseries.frequencies import to_offset
+from pandas.tseries.frequencies import to_offset, get_period_alias
from pandas.tseries.offsets import Tick, generate_range
from pandas.core.arrays import datetimelike as dtl
@@ -200,6 +200,10 @@ def __new__(cls, values, freq=None, tz=None, dtype=None):
# e.g. DatetimeIndex
tz = values.tz
+ if freq is None and hasattr(values, "freq"):
+ # i.e. DatetimeArray, DatetimeIndex
+ freq = values.freq
+
freq, freq_infer = dtl.maybe_infer_freq(freq)
# if dtype has an embedded tz, capture it
@@ -764,6 +768,67 @@ def normalize(self):
new_values = conversion.normalize_i8_timestamps(self.asi8, self.tz)
return type(self)(new_values, freq='infer').tz_localize(self.tz)
+ def to_period(self, freq=None):
+ """
+ Cast to PeriodArray/Index at a particular frequency.
+
+ Converts DatetimeArray/Index to PeriodArray/Index.
+
+ Parameters
+ ----------
+ freq : string or Offset, optional
+ One of pandas' :ref:`offset strings <timeseries.offset_aliases>`
+ or an Offset object. Will be inferred by default.
+
+ Returns
+ -------
+ PeriodArray/Index
+
+ Raises
+ ------
+ ValueError
+ When converting a DatetimeArray/Index with non-regular values,
+ so that a frequency cannot be inferred.
+
+ Examples
+ --------
+ >>> df = pd.DataFrame({"y": [1,2,3]},
+ ... index=pd.to_datetime(["2000-03-31 00:00:00",
+ ... "2000-05-31 00:00:00",
+ ... "2000-08-31 00:00:00"]))
+ >>> df.index.to_period("M")
+ PeriodIndex(['2000-03', '2000-05', '2000-08'],
+ dtype='period[M]', freq='M')
+
+ Infer the daily frequency
+
+ >>> idx = pd.date_range("2017-01-01", periods=2)
+ >>> idx.to_period()
+ PeriodIndex(['2017-01-01', '2017-01-02'],
+ dtype='period[D]', freq='D')
+
+ See also
+ --------
+ pandas.PeriodIndex: Immutable ndarray holding ordinal values
+ pandas.DatetimeIndex.to_pydatetime: Return DatetimeIndex as object
+ """
+ from pandas.core.arrays.period import PeriodArrayMixin
+
+ if self.tz is not None:
+ warnings.warn("Converting to PeriodArray/Index representation "
+ "will drop timezone information.", UserWarning)
+
+ if freq is None:
+ freq = self.freqstr or self.inferred_freq
+
+ if freq is None:
+ raise ValueError("You must pass a freq argument as "
+ "current index has none.")
+
+ freq = get_period_alias(freq)
+
+ return PeriodArrayMixin(self.values, freq=freq)
+
# -----------------------------------------------------------------
# Properties - Vectorized Timestamp Properties/Methods
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index 41b4c5c669efc..9e877de1a3c0a 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -10,14 +10,15 @@
Period, IncompatibleFrequency, DIFFERENT_FREQ_INDEX,
get_period_field_arr, period_asfreq_arr)
from pandas._libs.tslibs import period as libperiod
-from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds
+from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds, Timedelta
from pandas._libs.tslibs.fields import isleapyear_arr
from pandas import compat
from pandas.util._decorators import cache_readonly
from pandas.core.dtypes.common import (
- is_integer_dtype, is_float_dtype, is_period_dtype)
+ is_integer_dtype, is_float_dtype, is_period_dtype,
+ is_datetime64_dtype)
from pandas.core.dtypes.dtypes import PeriodDtype
from pandas.core.dtypes.generic import ABCSeries
@@ -127,6 +128,10 @@ def __new__(cls, values, freq=None, **kwargs):
freq = values.freq
values = values.asi8
+ elif is_datetime64_dtype(values):
+ # TODO: what if it has tz?
+ values = dt64arr_to_periodarr(values, freq)
+
return cls._simple_new(values, freq, **kwargs)
@classmethod
@@ -207,6 +212,14 @@ def is_leap_year(self):
""" Logical indicating if the date belongs to a leap year """
return isleapyear_arr(np.asarray(self.year))
+ @property
+ def start_time(self):
+ return self.to_timestamp(how='start')
+
+ @property
+ def end_time(self):
+ return self.to_timestamp(how='end')
+
def asfreq(self, freq=None, how='E'):
"""
Convert the Period Array/Index to the specified frequency `freq`.
@@ -266,6 +279,48 @@ def asfreq(self, freq=None, how='E'):
return self._shallow_copy(new_data, freq=freq)
+ def to_timestamp(self, freq=None, how='start'):
+ """
+ Cast to DatetimeArray/Index
+
+ Parameters
+ ----------
+ freq : string or DateOffset, optional
+ Target frequency. The default is 'D' for week or longer,
+ 'S' otherwise
+ how : {'s', 'e', 'start', 'end'}
+
+ Returns
+ -------
+ DatetimeArray/Index
+ """
+ from pandas.core.arrays.datetimes import DatetimeArrayMixin
+
+ how = libperiod._validate_end_alias(how)
+
+ end = how == 'E'
+ if end:
+ if freq == 'B':
+ # roll forward to ensure we land on B date
+ adjust = Timedelta(1, 'D') - Timedelta(1, 'ns')
+ return self.to_timestamp(how='start') + adjust
+ else:
+ adjust = Timedelta(1, 'ns')
+ return (self + 1).to_timestamp(how='start') - adjust
+
+ if freq is None:
+ base, mult = frequencies.get_freq_code(self.freq)
+ freq = frequencies.get_to_timestamp_base(base)
+ else:
+ freq = Period._maybe_convert_freq(freq)
+
+ base, mult = frequencies.get_freq_code(freq)
+ new_data = self.asfreq(freq, how=how)
+
+ new_data = libperiod.periodarr_to_dt64arr(new_data._ndarray_values,
+ base)
+ return DatetimeArrayMixin(new_data, freq='infer')
+
# ------------------------------------------------------------------
# Arithmetic Methods
@@ -392,6 +447,15 @@ def _maybe_convert_timedelta(self, other):
# -------------------------------------------------------------------
# Constructor Helpers
+def dt64arr_to_periodarr(data, freq, tz=None):
+ if data.dtype != np.dtype('M8[ns]'):
+ raise ValueError('Wrong dtype: %s' % data.dtype)
+
+ freq = Period._maybe_convert_freq(freq)
+ base, mult = frequencies.get_freq_code(freq)
+ return libperiod.dt64arr_to_periodarr(data.view('i8'), base, tz)
+
+
def _get_ordinal_range(start, end, periods, freq, mult=1):
if com.count_not_none(start, end, periods) != 2:
raise ValueError('Of the three parameters: start, end, and periods, '
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index a6cdaa0c2163a..e40ceadc1a083 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -36,7 +36,7 @@
from pandas.core.indexes.base import Index, _index_shared_docs
from pandas.core.indexes.numeric import Int64Index, Float64Index
import pandas.compat as compat
-from pandas.tseries.frequencies import to_offset, get_period_alias, Resolution
+from pandas.tseries.frequencies import to_offset, Resolution
from pandas.core.indexes.datetimelike import (
DatelikeOps, TimelikeOps, DatetimeIndexOpsMixin)
from pandas.tseries.offsets import (
@@ -302,7 +302,8 @@ def __new__(cls, data=None,
tz=tz, normalize=normalize,
closed=closed, ambiguous=ambiguous)
- if not isinstance(data, (np.ndarray, Index, ABCSeries)):
+ if not isinstance(data, (np.ndarray, Index, ABCSeries,
+ DatetimeArrayMixin)):
if is_scalar(data):
raise ValueError('DatetimeIndex() must be called with a '
'collection of some kind, %s was passed'
@@ -673,67 +674,12 @@ def to_series(self, keep_tz=False, index=None, name=None):
return Series(values, index=index, name=name)
+ @Appender(DatetimeArrayMixin.to_period.__doc__)
def to_period(self, freq=None):
- """
- Cast to PeriodIndex at a particular frequency.
-
- Converts DatetimeIndex to PeriodIndex.
-
- Parameters
- ----------
- freq : string or Offset, optional
- One of pandas' :ref:`offset strings <timeseries.offset_aliases>`
- or an Offset object. Will be inferred by default.
-
- Returns
- -------
- PeriodIndex
-
- Raises
- ------
- ValueError
- When converting a DatetimeIndex with non-regular values, so that a
- frequency cannot be inferred.
-
- Examples
- --------
- >>> df = pd.DataFrame({"y": [1,2,3]},
- ... index=pd.to_datetime(["2000-03-31 00:00:00",
- ... "2000-05-31 00:00:00",
- ... "2000-08-31 00:00:00"]))
- >>> df.index.to_period("M")
- PeriodIndex(['2000-03', '2000-05', '2000-08'],
- dtype='period[M]', freq='M')
-
- Infer the daily frequency
-
- >>> idx = pd.date_range("2017-01-01", periods=2)
- >>> idx.to_period()
- PeriodIndex(['2017-01-01', '2017-01-02'],
- dtype='period[D]', freq='D')
-
- See also
- --------
- pandas.PeriodIndex: Immutable ndarray holding ordinal values
- pandas.DatetimeIndex.to_pydatetime: Return DatetimeIndex as object
- """
from pandas.core.indexes.period import PeriodIndex
- if self.tz is not None:
- warnings.warn("Converting to PeriodIndex representation will "
- "drop timezone information.", UserWarning)
-
- if freq is None:
- freq = self.freqstr or self.inferred_freq
-
- if freq is None:
- msg = ("You must pass a freq argument as "
- "current index has none.")
- raise ValueError(msg)
-
- freq = get_period_alias(freq)
-
- return PeriodIndex(self.values, name=self.name, freq=freq)
+ result = DatetimeArrayMixin.to_period(self, freq=freq)
+ return PeriodIndex(result, name=self.name)
def snap(self, freq='S'):
"""
@@ -758,6 +704,7 @@ def snap(self, freq='S'):
# we know it conforms; skip check
return DatetimeIndex(snapped, freq=freq, verify_integrity=False)
+ # TODO: what about self.name? if so, use shallow_copy?
def unique(self, level=None):
# Override here since IndexOpsMixin.unique uses self._values.unique
@@ -769,8 +716,7 @@ def unique(self, level=None):
else:
naive = self
result = super(DatetimeIndex, naive).unique(level=level)
- return self._simple_new(result.values, name=self.name, tz=self.tz,
- freq=self.freq)
+ return self._shallow_copy(result.values)
def union(self, other):
"""
@@ -1421,8 +1367,7 @@ def insert(self, loc, item):
try:
new_dates = np.concatenate((self[:loc].asi8, [item.view(np.int64)],
self[loc:].asi8))
- return DatetimeIndex(new_dates, name=self.name, freq=freq,
- tz=self.tz)
+ return self._shallow_copy(new_dates, freq=freq)
except (AttributeError, TypeError):
# fall back to object index
@@ -1458,7 +1403,7 @@ def delete(self, loc):
if (loc.start in (0, None) or loc.stop in (len(self), None)):
freq = self.freq
- return DatetimeIndex(new_dates, name=self.name, freq=freq, tz=self.tz)
+ return self._shallow_copy(new_dates, freq=freq)
def indexer_at_time(self, time, asof=False):
"""
diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py
index cc008694a8b84..7833dd851db34 100644
--- a/pandas/core/indexes/period.py
+++ b/pandas/core/indexes/period.py
@@ -17,7 +17,6 @@
pandas_dtype,
ensure_object)
-import pandas.tseries.frequencies as frequencies
from pandas.tseries.frequencies import get_freq_code as _gfc
from pandas.core.indexes.datetimes import DatetimeIndex, Int64Index, Index
@@ -25,13 +24,13 @@
from pandas.core.tools.datetimes import parse_time_string
from pandas._libs.lib import infer_dtype
-from pandas._libs import tslib, index as libindex, Timedelta
+from pandas._libs import tslib, index as libindex
from pandas._libs.tslibs.period import (Period, IncompatibleFrequency,
- DIFFERENT_FREQ_INDEX,
- _validate_end_alias)
+ DIFFERENT_FREQ_INDEX)
from pandas._libs.tslibs import resolution, period
-from pandas.core.arrays.period import PeriodArrayMixin
+from pandas.core.arrays import datetimelike as dtl
+from pandas.core.arrays.period import PeriodArrayMixin, dt64arr_to_periodarr
from pandas.core.base import _shared_docs
from pandas.core.indexes.base import _index_shared_docs, ensure_index
@@ -56,14 +55,6 @@ def f(self):
return property(f)
-def dt64arr_to_periodarr(data, freq, tz):
- if data.dtype != np.dtype('M8[ns]'):
- raise ValueError('Wrong dtype: %s' % data.dtype)
-
- freq = Period._maybe_convert_freq(freq)
- base, mult = _gfc(freq)
- return period.dt64arr_to_periodarr(data.view('i8'), base, tz)
-
# --- Period index sketch
@@ -185,12 +176,7 @@ def __new__(cls, data=None, ordinal=None, freq=None, start=None, end=None,
raise TypeError('__new__() got an unexpected keyword argument {}'.
format(list(set(fields) - valid_field_set)[0]))
- if periods is not None:
- if is_float(periods):
- periods = int(periods)
- elif not is_integer(periods):
- msg = 'periods must be a number, got {periods}'
- raise TypeError(msg.format(periods=periods))
+ periods = dtl.validate_periods(periods)
if name is None and hasattr(data, 'name'):
name = data.name
@@ -461,55 +447,23 @@ def is_full(self):
daysinmonth = days_in_month
@property
+ @Appender(PeriodArrayMixin.start_time.__doc__)
def start_time(self):
- return self.to_timestamp(how='start')
+ return PeriodArrayMixin.start_time.fget(self)
@property
+ @Appender(PeriodArrayMixin.end_time.__doc__)
def end_time(self):
- return self.to_timestamp(how='end')
+ return PeriodArrayMixin.end_time.fget(self)
def _mpl_repr(self):
# how to represent ourselves to matplotlib
return self.astype(object).values
+ @Appender(PeriodArrayMixin.to_timestamp.__doc__)
def to_timestamp(self, freq=None, how='start'):
- """
- Cast to DatetimeIndex
-
- Parameters
- ----------
- freq : string or DateOffset, optional
- Target frequency. The default is 'D' for week or longer,
- 'S' otherwise
- how : {'s', 'e', 'start', 'end'}
-
- Returns
- -------
- DatetimeIndex
- """
- how = _validate_end_alias(how)
-
- end = how == 'E'
- if end:
- if freq == 'B':
- # roll forward to ensure we land on B date
- adjust = Timedelta(1, 'D') - Timedelta(1, 'ns')
- return self.to_timestamp(how='start') + adjust
- else:
- adjust = Timedelta(1, 'ns')
- return (self + 1).to_timestamp(how='start') - adjust
-
- if freq is None:
- base, mult = _gfc(self.freq)
- freq = frequencies.get_to_timestamp_base(base)
- else:
- freq = Period._maybe_convert_freq(freq)
-
- base, mult = _gfc(freq)
- new_data = self.asfreq(freq, how)
-
- new_data = period.periodarr_to_dt64arr(new_data._ndarray_values, base)
- return DatetimeIndex(new_data, freq='infer', name=self.name)
+ result = PeriodArrayMixin.to_timestamp(self, freq=freq, how=how)
+ return DatetimeIndex(result, name=self.name)
@property
def inferred_type(self):
diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py
index 933bc6233dca9..ee604f44b98e0 100644
--- a/pandas/core/indexes/timedeltas.py
+++ b/pandas/core/indexes/timedeltas.py
@@ -668,7 +668,7 @@ def insert(self, loc, item):
try:
new_tds = np.concatenate((self[:loc].asi8, [item.view(np.int64)],
self[loc:].asi8))
- return TimedeltaIndex(new_tds, name=self.name, freq=freq)
+ return self._shallow_copy(new_tds, freq=freq)
except (AttributeError, TypeError):
diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py
index 24f34884dc077..6bb4241451b3f 100644
--- a/pandas/tests/arrays/test_datetimelike.py
+++ b/pandas/tests/arrays/test_datetimelike.py
@@ -1,13 +1,50 @@
# -*- coding: utf-8 -*-
import numpy as np
+import pytest
import pandas as pd
+import pandas.util.testing as tm
from pandas.core.arrays.datetimes import DatetimeArrayMixin
from pandas.core.arrays.timedeltas import TimedeltaArrayMixin
from pandas.core.arrays.period import PeriodArrayMixin
+# TODO: more freq variants
+@pytest.fixture(params=['D', 'B', 'W', 'M', 'Q', 'Y'])
+def period_index(request):
+ """
+ A fixture to provide PeriodIndex objects with different frequencies.
+
+ Most PeriodArray behavior is already tested in PeriodIndex tests,
+ so here we just test that the PeriodArray behavior matches
+ the PeriodIndex behavior.
+ """
+ freqstr = request.param
+ # TODO: non-monotone indexes; NaTs, different start dates
+ pi = pd.period_range(start=pd.Timestamp('2000-01-01'),
+ periods=100,
+ freq=freqstr)
+ return pi
+
+
+@pytest.fixture(params=['D', 'B', 'W', 'M', 'Q', 'Y'])
+def datetime_index(request):
+ """
+ A fixture to provide DatetimeIndex objects with different frequencies.
+
+ Most DatetimeArray behavior is already tested in DatetimeIndex tests,
+ so here we just test that the DatetimeIndex behavior matches
+ the DatetimeIndex behavior.
+ """
+ freqstr = request.param
+ # TODO: non-monotone indexes; NaTs, different start dates, timezones
+ pi = pd.date_range(start=pd.Timestamp('2000-01-01'),
+ periods=100,
+ freq=freqstr)
+ return pi
+
+
class TestDatetimeArray(object):
def test_from_dti(self, tz_naive_fixture):
@@ -30,6 +67,41 @@ def test_astype_object(self, tz_naive_fixture):
assert asobj.dtype == 'O'
assert list(asobj) == list(dti)
+ @pytest.mark.parametrize('freqstr', ['D', 'B', 'W', 'M', 'Q', 'Y'])
+ def test_to_period(self, datetime_index, freqstr):
+ dti = datetime_index
+ arr = DatetimeArrayMixin(dti)
+
+ expected = dti.to_period(freq=freqstr)
+ result = arr.to_period(freq=freqstr)
+ assert isinstance(result, PeriodArrayMixin)
+
+ # placeholder until these become actual EA subclasses and we can use
+ # an EA-specific tm.assert_ function
+ tm.assert_index_equal(pd.Index(result), pd.Index(expected))
+
+ @pytest.mark.parametrize('propname', pd.DatetimeIndex._bool_ops)
+ def test_bool_properties(self, datetime_index, propname):
+ # in this case _bool_ops is just `is_leap_year`
+ dti = datetime_index
+ arr = DatetimeArrayMixin(dti)
+ assert dti.freq == arr.freq
+
+ result = getattr(arr, propname)
+ expected = np.array(getattr(dti, propname), dtype=result.dtype)
+
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize('propname', pd.DatetimeIndex._field_ops)
+ def test_int_properties(self, datetime_index, propname):
+ dti = datetime_index
+ arr = DatetimeArrayMixin(dti)
+
+ result = getattr(arr, propname)
+ expected = np.array(getattr(dti, propname), dtype=result.dtype)
+
+ tm.assert_numpy_array_equal(result, expected)
+
class TestTimedeltaArray(object):
def test_from_tdi(self):
@@ -53,20 +125,54 @@ def test_astype_object(self):
class TestPeriodArray(object):
- def test_from_pi(self):
- pi = pd.period_range('2016', freq='Q', periods=3)
+ def test_from_pi(self, period_index):
+ pi = period_index
arr = PeriodArrayMixin(pi)
assert list(arr) == list(pi)
- # Check that Index.__new__ knows what to do with TimedeltaArray
+ # Check that Index.__new__ knows what to do with PeriodArray
pi2 = pd.Index(arr)
assert isinstance(pi2, pd.PeriodIndex)
assert list(pi2) == list(arr)
- def test_astype_object(self):
- pi = pd.period_range('2016', freq='Q', periods=3)
+ def test_astype_object(self, period_index):
+ pi = period_index
arr = PeriodArrayMixin(pi)
asobj = arr.astype('O')
assert isinstance(asobj, np.ndarray)
assert asobj.dtype == 'O'
assert list(asobj) == list(pi)
+
+ @pytest.mark.parametrize('how', ['S', 'E'])
+ def test_to_timestamp(self, how, period_index):
+ pi = period_index
+ arr = PeriodArrayMixin(pi)
+
+ expected = DatetimeArrayMixin(pi.to_timestamp(how=how))
+ result = arr.to_timestamp(how=how)
+ assert isinstance(result, DatetimeArrayMixin)
+
+ # placeholder until these become actual EA subclasses and we can use
+ # an EA-specific tm.assert_ function
+ tm.assert_index_equal(pd.Index(result), pd.Index(expected))
+
+ @pytest.mark.parametrize('propname', pd.PeriodIndex._bool_ops)
+ def test_bool_properties(self, period_index, propname):
+ # in this case _bool_ops is just `is_leap_year`
+ pi = period_index
+ arr = PeriodArrayMixin(pi)
+
+ result = getattr(arr, propname)
+ expected = np.array(getattr(pi, propname))
+
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize('propname', pd.PeriodIndex._field_ops)
+ def test_int_properties(self, period_index, propname):
+ pi = period_index
+ arr = PeriodArrayMixin(pi)
+
+ result = getattr(arr, propname)
+ expected = np.array(getattr(pi, propname))
+
+ tm.assert_numpy_array_equal(result, expected)
| If/when this goes through the basic template it creates for tests will be pretty straightforward to extend to the other relevant methods/properties.
@TomAugspurger this definitely overlaps with #22862, particularly the pieces touching constructors. LMK if this causes problems and I can try to stay in my lane. | https://api.github.com/repos/pandas-dev/pandas/pulls/22961 | 2018-10-03T02:58:05Z | 2018-10-08T20:07:30Z | 2018-10-08T20:07:30Z | 2020-04-05T17:38:58Z |
CI: pin moto to 1.3.4 | diff --git a/ci/travis-27.yaml b/ci/travis-27.yaml
index a921bcb46dba4..6955db363ca1f 100644
--- a/ci/travis-27.yaml
+++ b/ci/travis-27.yaml
@@ -44,7 +44,7 @@ dependencies:
# universal
- pytest
- pytest-xdist
- - moto
+ - moto==1.3.4
- hypothesis>=3.58.0
- pip:
- backports.lzma
| xref https://github.com/pandas-dev/pandas/issues/22934
Looking back at the logs, moto 1.3.4 didn't seem to have an issues. Going to run this on the CI a few times to see if we get any failures. May have to make some additional pins of boto if this doesn't work. | https://api.github.com/repos/pandas-dev/pandas/pulls/22959 | 2018-10-03T01:36:07Z | 2018-10-03T13:49:44Z | 2018-10-03T13:49:44Z | 2018-10-03T13:49:45Z |
CLN: Use is_period_dtype instead of ABCPeriodIndex checks | diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index 481d5313f0e25..41b4c5c669efc 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -264,7 +264,7 @@ def asfreq(self, freq=None, how='E'):
if self.hasnans:
new_data[self._isnan] = iNaT
- return self._simple_new(new_data, self.name, freq=freq)
+ return self._shallow_copy(new_data, freq=freq)
# ------------------------------------------------------------------
# Arithmetic Methods
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index 37a12a588db03..1ec30ecbb3a3b 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -21,6 +21,7 @@
is_list_like,
is_scalar,
is_bool_dtype,
+ is_period_dtype,
is_categorical_dtype,
is_datetime_or_timedelta_dtype,
is_float_dtype,
@@ -28,7 +29,7 @@
is_object_dtype,
is_string_dtype)
from pandas.core.dtypes.generic import (
- ABCIndex, ABCSeries, ABCPeriodIndex, ABCIndexClass)
+ ABCIndex, ABCSeries, ABCIndexClass)
from pandas.core.dtypes.missing import isna
from pandas.core import common as com, algorithms, ops
@@ -239,9 +240,8 @@ def equals(self, other):
# have different timezone
return False
- # ToDo: Remove this when PeriodDtype is added
- elif isinstance(self, ABCPeriodIndex):
- if not isinstance(other, ABCPeriodIndex):
+ elif is_period_dtype(self):
+ if not is_period_dtype(other):
return False
if self.freq != other.freq:
return False
@@ -359,7 +359,7 @@ def sort_values(self, return_indexer=False, ascending=True):
attribs = self._get_attributes_dict()
freq = attribs['freq']
- if freq is not None and not isinstance(self, ABCPeriodIndex):
+ if freq is not None and not is_period_dtype(self):
if freq.n > 0 and not ascending:
freq = freq * -1
elif freq.n < 0 and ascending:
@@ -386,8 +386,8 @@ def take(self, indices, axis=0, allow_fill=True,
fill_value=fill_value,
na_value=iNaT)
- # keep freq in PeriodIndex, reset otherwise
- freq = self.freq if isinstance(self, ABCPeriodIndex) else None
+ # keep freq in PeriodArray/Index, reset otherwise
+ freq = self.freq if is_period_dtype(self) else None
return self._shallow_copy(taken, freq=freq)
_can_hold_na = True
@@ -618,7 +618,7 @@ def repeat(self, repeats, *args, **kwargs):
Analogous to ndarray.repeat
"""
nv.validate_repeat(args, kwargs)
- if isinstance(self, ABCPeriodIndex):
+ if is_period_dtype(self):
freq = self.freq
else:
freq = None
@@ -673,7 +673,7 @@ def _concat_same_dtype(self, to_concat, name):
attribs = self._get_attributes_dict()
attribs['name'] = name
- if not isinstance(self, ABCPeriodIndex):
+ if not is_period_dtype(self):
# reset freq
attribs['freq'] = None
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 119a607fc0e68..6091df776a01b 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -1001,7 +1001,7 @@ def _try_mi(k):
(compat.PY3 and isinstance(key, compat.string_types))):
try:
return _try_mi(key)
- except (KeyError):
+ except KeyError:
raise
except (IndexError, ValueError, TypeError):
pass
diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py
index 981bfddeadac1..fd8e17c369f5a 100644
--- a/pandas/core/indexes/range.py
+++ b/pandas/core/indexes/range.py
@@ -512,33 +512,33 @@ def __getitem__(self, key):
# This is basically PySlice_GetIndicesEx, but delegation to our
# super routines if we don't have integers
- l = len(self)
+ length = len(self)
# complete missing slice information
step = 1 if key.step is None else key.step
if key.start is None:
- start = l - 1 if step < 0 else 0
+ start = length - 1 if step < 0 else 0
else:
start = key.start
if start < 0:
- start += l
+ start += length
if start < 0:
start = -1 if step < 0 else 0
- if start >= l:
- start = l - 1 if step < 0 else l
+ if start >= length:
+ start = length - 1 if step < 0 else length
if key.stop is None:
- stop = -1 if step < 0 else l
+ stop = -1 if step < 0 else length
else:
stop = key.stop
if stop < 0:
- stop += l
+ stop += length
if stop < 0:
stop = -1
- if stop > l:
- stop = l
+ if stop > length:
+ stop = length
# delegate non-integer slices
if (start != int(start) or
| Will be more generally correct for catching both PeriodIndex and PeriodArray.
Unrelated change of `l` -> `length` | https://api.github.com/repos/pandas-dev/pandas/pulls/22958 | 2018-10-03T01:28:04Z | 2018-10-03T09:19:28Z | 2018-10-03T09:19:28Z | 2018-10-03T12:17:32Z |
CLN: small clean-up of IntervalIndex | diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 90df596b98296..134999f05364f 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -108,12 +108,7 @@ class IntervalArray(IntervalMixin, ExtensionArray):
_na_value = _fill_value = np.nan
def __new__(cls, data, closed=None, dtype=None, copy=False,
- fastpath=False, verify_integrity=True):
-
- if fastpath:
- return cls._simple_new(data.left, data.right, closed,
- copy=copy, dtype=dtype,
- verify_integrity=False)
+ verify_integrity=True):
if isinstance(data, ABCSeries) and is_interval_dtype(data):
data = data.values
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index 4b125580bd7e0..f72f87aeb2af6 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -146,17 +146,13 @@ class IntervalIndex(IntervalMixin, Index):
_mask = None
def __new__(cls, data, closed=None, dtype=None, copy=False,
- name=None, fastpath=False, verify_integrity=True):
-
- if fastpath:
- return cls._simple_new(data, name)
+ name=None, verify_integrity=True):
if name is None and hasattr(data, 'name'):
name = data.name
with rewrite_exception("IntervalArray", cls.__name__):
array = IntervalArray(data, closed=closed, copy=copy, dtype=dtype,
- fastpath=fastpath,
verify_integrity=verify_integrity)
return cls._simple_new(array, name)
@@ -187,14 +183,6 @@ def _shallow_copy(self, left=None, right=None, **kwargs):
attributes.update(kwargs)
return self._simple_new(result, **attributes)
- @cache_readonly
- def hasnans(self):
- """
- Return if the IntervalIndex has any nans; enables various performance
- speedups
- """
- return self._isnan.any()
-
@cache_readonly
def _isnan(self):
"""Return a mask indicating if each value is NA"""
@@ -206,10 +194,6 @@ def _isnan(self):
def _engine(self):
return IntervalTree(self.left, self.right, closed=self.closed)
- @property
- def _constructor(self):
- return type(self)
-
def __contains__(self, key):
"""
return a boolean if this key is IN the index
@@ -394,18 +378,7 @@ def _values(self):
@cache_readonly
def _ndarray_values(self):
- left = self.left
- right = self.right
- mask = self._isnan
- closed = self.closed
-
- result = np.empty(len(left), dtype=object)
- for i in range(len(left)):
- if mask[i]:
- result[i] = np.nan
- else:
- result[i] = Interval(left[i], right[i], closed)
- return result
+ return np.array(self._data)
def __array__(self, result=None):
""" the array interface, return my values """
@@ -892,18 +865,12 @@ def take(self, indices, axis=0, allow_fill=True,
return self._simple_new(result, **attributes)
def __getitem__(self, value):
- mask = self._isnan[value]
- if is_scalar(mask) and mask:
- return self._na_value
-
- left = self.left[value]
- right = self.right[value]
-
- # scalar
- if not isinstance(left, Index):
- return Interval(left, right, self.closed)
-
- return self._shallow_copy(left, right)
+ result = self._data[value]
+ if isinstance(result, IntervalArray):
+ return self._shallow_copy(result)
+ else:
+ # scalar
+ return result
# __repr__ associated methods are based on MultiIndex
| Removed some parts of IntervalIndex that are not needed (because they are inherited from Index or can be dispatched to the array)
\+ removed `fastpath` (for IntervalArray this is no problem (never used), for IntervalIndex I am not fully sure, since this signature might need to match the other index classes)
cc @jschendel @TomAugspurger | https://api.github.com/repos/pandas-dev/pandas/pulls/22956 | 2018-10-02T21:20:04Z | 2018-10-03T07:24:37Z | 2018-10-03T07:24:37Z | 2018-10-03T07:25:07Z |
Support for PEP 3141 numbers | diff --git a/doc/source/whatsnew/v0.24.0.rst b/doc/source/whatsnew/v0.24.0.rst
index f94aa3d320b75..22f2add40c451 100644
--- a/doc/source/whatsnew/v0.24.0.rst
+++ b/doc/source/whatsnew/v0.24.0.rst
@@ -465,6 +465,7 @@ For situations where you need an ``ndarray`` of ``Interval`` objects, use
np.asarray(idx)
idx.values.astype(object)
+
.. _whatsnew_0240.api.timezone_offset_parsing:
Parsing Datetime Strings with Timezone Offsets
@@ -1471,6 +1472,7 @@ Other
- :meth:`DataFrame.nlargest` and :meth:`DataFrame.nsmallest` now returns the correct n values when keep != 'all' also when tied on the first columns (:issue:`22752`)
- :meth:`~pandas.io.formats.style.Styler.bar` now also supports tablewise application (in addition to rowwise and columnwise) with ``axis=None`` and setting clipping range with ``vmin`` and ``vmax`` (:issue:`21548` and :issue:`21526`). ``NaN`` values are also handled properly.
- Logical operations ``&, |, ^`` between :class:`Series` and :class:`Index` will no longer raise ``ValueError`` (:issue:`22092`)
+- Checking PEP 3141 numbers in :func:`~pandas.api.types.is_scalar` function returns ``True`` (:issue:`22903`)
- Bug in :meth:`DataFrame.combine_first` in which column types were unexpectedly converted to float (:issue:`20699`)
.. _whatsnew_0.24.0.contributors:
@@ -1479,3 +1481,4 @@ Contributors
~~~~~~~~~~~~
.. contributors:: v0.23.4..HEAD
+
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index e89c8fa579687..ad538ff103c2f 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -1,5 +1,8 @@
# -*- coding: utf-8 -*-
from decimal import Decimal
+from fractions import Fraction
+from numbers import Number
+
import sys
import cython
@@ -15,7 +18,6 @@ from cpython.datetime cimport (PyDateTime_Check, PyDate_Check,
PyDateTime_IMPORT)
PyDateTime_IMPORT
-
import numpy as np
cimport numpy as cnp
from numpy cimport (ndarray, PyArray_GETITEM,
@@ -105,23 +107,54 @@ def is_scalar(val: object) -> bool:
"""
Return True if given value is scalar.
- This includes:
- - numpy array scalar (e.g. np.int64)
- - Python builtin numerics
- - Python builtin byte arrays and strings
- - None
- - instances of datetime.datetime
- - instances of datetime.timedelta
- - Period
- - instances of decimal.Decimal
- - Interval
- - DateOffset
+ Parameters
+ ----------
+ val : object
+ This includes:
+
+ - numpy array scalar (e.g. np.int64)
+ - Python builtin numerics
+ - Python builtin byte arrays and strings
+ - None
+ - datetime.datetime
+ - datetime.timedelta
+ - Period
+ - decimal.Decimal
+ - Interval
+ - DateOffset
+ - Fraction
+ - Number
+
+ Returns
+ -------
+ bool
+ Return True if given object is scalar, False otherwise
+
+ Examples
+ --------
+ >>> dt = pd.datetime.datetime(2018, 10, 3)
+ >>> pd.is_scalar(dt)
+ True
+
+ >>> pd.api.types.is_scalar([2, 3])
+ False
+
+ >>> pd.api.types.is_scalar({0: 1, 2: 3})
+ False
+
+ >>> pd.api.types.is_scalar((0, 2))
+ False
+
+ pandas supports PEP 3141 numbers:
+ >>> from fractions import Fraction
+ >>> pd.api.types.is_scalar(Fraction(3, 5))
+ True
"""
return (cnp.PyArray_IsAnyScalar(val)
# As of numpy-1.9, PyArray_IsAnyScalar misses bytearrays on Py3.
- or isinstance(val, bytes)
+ or isinstance(val, (bytes, Fraction, Number))
# We differ from numpy (as of 1.10), which claims that None is
# not scalar in np.isscalar().
or val is None
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py
index f2552cffc6651..fd3222cd1119b 100644
--- a/pandas/tests/dtypes/test_inference.py
+++ b/pandas/tests/dtypes/test_inference.py
@@ -10,10 +10,11 @@
import re
from datetime import datetime, date, timedelta, time
from decimal import Decimal
+from numbers import Number
+from fractions import Fraction
import numpy as np
import pytz
import pytest
-
import pandas as pd
from pandas._libs import lib, iNaT, missing as libmissing
from pandas import (Series, Index, DataFrame, Timedelta,
@@ -1183,6 +1184,8 @@ def test_is_scalar_builtin_scalars(self):
assert is_scalar(None)
assert is_scalar(True)
assert is_scalar(False)
+ assert is_scalar(Number())
+ assert is_scalar(Fraction())
assert is_scalar(0.)
assert is_scalar(np.nan)
assert is_scalar('foobar')
| - [x] closes #22903
- [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/22952 | 2018-10-02T19:57:09Z | 2018-11-20T10:41:34Z | 2018-11-20T10:41:33Z | 2018-11-20T10:41:57Z |
CI: deduplicate skip printing | diff --git a/ci/script_multi.sh b/ci/script_multi.sh
index 2b2d4d5488b91..dcc5a14d7b3b4 100755
--- a/ci/script_multi.sh
+++ b/ci/script_multi.sh
@@ -28,16 +28,16 @@ if [ "$DOC" ]; then
elif [ "$COVERAGE" ]; then
echo pytest -s -n 2 -m "not single" --cov=pandas --cov-report xml:/tmp/cov-multiple.xml --junitxml=/tmp/multiple.xml --strict $TEST_ARGS pandas
- pytest -s -n 2 -m "not single" --cov=pandas --cov-report xml:/tmp/cov-multiple.xml --junitxml=/tmp/multiple.xml --strict $TEST_ARGS pandas
+ pytest -s -n 2 -m "not single" --cov=pandas --cov-report xml:/tmp/cov-multiple.xml --junitxml=/tmp/multiple.xml --strict $TEST_ARGS pandas
elif [ "$SLOW" ]; then
TEST_ARGS="--only-slow --skip-network"
- echo pytest -r xX -m "not single and slow" -v --junitxml=/tmp/multiple.xml --strict $TEST_ARGS pandas
- pytest -r xX -m "not single and slow" -v --junitxml=/tmp/multiple.xml --strict $TEST_ARGS pandas
+ echo pytest -m "not single and slow" -v --junitxml=/tmp/multiple.xml --strict $TEST_ARGS pandas
+ pytest -m "not single and slow" -v --junitxml=/tmp/multiple.xml --strict $TEST_ARGS pandas
else
- echo pytest -n 2 -r xX -m "not single" --junitxml=/tmp/multiple.xml --strict $TEST_ARGS pandas
- pytest -n 2 -r xX -m "not single" --junitxml=/tmp/multiple.xml --strict $TEST_ARGS pandas # TODO: doctest
+ echo pytest -n 2 -m "not single" --junitxml=/tmp/multiple.xml --strict $TEST_ARGS pandas
+ pytest -n 2 -m "not single" --junitxml=/tmp/multiple.xml --strict $TEST_ARGS pandas # TODO: doctest
fi
diff --git a/ci/script_single.sh b/ci/script_single.sh
index ed12ee35b9151..09e7446a2d876 100755
--- a/ci/script_single.sh
+++ b/ci/script_single.sh
@@ -25,14 +25,14 @@ if [ "$DOC" ]; then
echo "We are not running pytest as this is a doc-build"
elif [ "$COVERAGE" ]; then
- echo pytest -s -m "single" -r xXs --strict --cov=pandas --cov-report xml:/tmp/cov-single.xml --junitxml=/tmp/single.xml $TEST_ARGS pandas
- pytest -s -m "single" -r xXs --strict --cov=pandas --cov-report xml:/tmp/cov-single.xml --junitxml=/tmp/single.xml $TEST_ARGS pandas
+ echo pytest -s -m "single" --strict --cov=pandas --cov-report xml:/tmp/cov-single.xml --junitxml=/tmp/single.xml $TEST_ARGS pandas
+ pytest -s -m "single" --strict --cov=pandas --cov-report xml:/tmp/cov-single.xml --junitxml=/tmp/single.xml $TEST_ARGS pandas
- echo pytest -s -r xXs --strict scripts
- pytest -s -r xXs --strict scripts
+ echo pytest -s --strict scripts
+ pytest -s --strict scripts
else
- echo pytest -m "single" -r xXs --junitxml=/tmp/single.xml --strict $TEST_ARGS pandas
- pytest -m "single" -r xXs --junitxml=/tmp/single.xml --strict $TEST_ARGS pandas # TODO: doctest
+ echo pytest -m "single" --junitxml=/tmp/single.xml --strict $TEST_ARGS pandas
+ pytest -m "single" --junitxml=/tmp/single.xml --strict $TEST_ARGS pandas # TODO: doctest
fi
| Trying to cut down on the noise in the travis log. Right now, we print out skipped / xfailed tests twice. This removes the `-r` flag passed to `pytest`. The skipped tests output will still be available under the output of `ci/print_skipped.py`. I believe that azure automatically parses the XML output anyway.
cc @datapythonista | https://api.github.com/repos/pandas-dev/pandas/pulls/22950 | 2018-10-02T18:38:06Z | 2018-10-08T13:42:22Z | 2018-10-08T13:42:21Z | 2018-10-08T13:42:25Z |
Use ._tshift internally for datetimelike ops | diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 91c119808db52..1ce60510c6a69 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -455,7 +455,7 @@ def _sub_period_array(self, other):
def _addsub_int_array(self, other, op):
"""
Add or subtract array-like of integers equivalent to applying
- `shift` pointwise.
+ `_time_shift` pointwise.
Parameters
----------
@@ -553,6 +553,23 @@ def shift(self, periods, freq=None):
--------
Index.shift : Shift values of Index.
"""
+ return self._time_shift(periods=periods, freq=freq)
+
+ def _time_shift(self, periods, freq=None):
+ """
+ Shift each value by `periods`.
+
+ Note this is different from ExtensionArray.shift, which
+ shifts the *position* of each element, padding the end with
+ missing values.
+
+ Parameters
+ ----------
+ periods : int
+ Number of periods to shift by.
+ freq : pandas.DateOffset, pandas.Timedelta, or string
+ Frequency increment to shift by.
+ """
if freq is not None and freq != self.freq:
if isinstance(freq, compat.string_types):
freq = frequencies.to_offset(freq)
@@ -600,7 +617,7 @@ def __add__(self, other):
elif lib.is_integer(other):
# This check must come after the check for np.timedelta64
# as is_integer returns True for these
- result = self.shift(other)
+ result = self._time_shift(other)
# array-like others
elif is_timedelta64_dtype(other):
@@ -652,7 +669,7 @@ def __sub__(self, other):
elif lib.is_integer(other):
# This check must come after the check for np.timedelta64
# as is_integer returns True for these
- result = self.shift(-other)
+ result = self._time_shift(-other)
elif isinstance(other, Period):
result = self._sub_period(other)
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index 41b4c5c669efc..92803ab5f52e0 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -297,7 +297,7 @@ def _add_offset(self, other):
if base != self.freq.rule_code:
msg = DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr)
raise IncompatibleFrequency(msg)
- return self.shift(other.n)
+ return self._time_shift(other.n)
def _add_delta_td(self, other):
assert isinstance(other, (timedelta, np.timedelta64, Tick))
@@ -307,7 +307,7 @@ def _add_delta_td(self, other):
if isinstance(own_offset, Tick):
offset_nanos = delta_to_nanoseconds(own_offset)
if np.all(nanos % offset_nanos == 0):
- return self.shift(nanos // offset_nanos)
+ return self._time_shift(nanos // offset_nanos)
# raise when input doesn't have freq
raise IncompatibleFrequency("Input has different freq from "
@@ -317,7 +317,7 @@ def _add_delta_td(self, other):
def _add_delta(self, other):
ordinal_delta = self._maybe_convert_timedelta(other)
- return self.shift(ordinal_delta)
+ return self._time_shift(ordinal_delta)
def shift(self, n):
"""
@@ -332,6 +332,9 @@ def shift(self, n):
-------
shifted : Period Array/Index
"""
+ return self._time_shift(n)
+
+ def _time_shift(self, n):
values = self._ndarray_values + n * self.freq.n
if self.hasnans:
values[self._isnan] = iNaT
| In preperation for PeriodArray / DatetimeArray / TimedeltaArray.
Index.shift has a different meaning from ExtensionArray.shift.
- Index.shift pointwise shifts each element by some amount
- ExtensionArray.shift shits the *position* of each value in the array
padding the end with NA
This is going to get confusing. This PR tries to avoid some of that by
internally using a new `_tshift` method (time-shift) when we want to do pointwise
shifting of each value. Places that know they want that behavior (like in the
datetimelike ops) should use that. | https://api.github.com/repos/pandas-dev/pandas/pulls/22949 | 2018-10-02T18:26:44Z | 2018-10-05T12:00:39Z | 2018-10-05T12:00:39Z | 2018-10-05T12:00:43Z |
change windows vm image | diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index c82dafa224961..5d473bfc5a38c 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -18,8 +18,8 @@ jobs:
- template: ci/azure/windows.yml
parameters:
name: Windows
- vmImage: vs2017-win2017
+ vmImage: vs2017-win2016
- template: ci/azure/windows-py27.yml
parameters:
name: WindowsPy27
- vmImage: vs2017-win2017
+ vmImage: vs2017-win2016
| Closes #22946
copying https://github.com/numba/numba/pull/3371/files | https://api.github.com/repos/pandas-dev/pandas/pulls/22948 | 2018-10-02T17:55:01Z | 2018-10-02T18:25:23Z | 2018-10-02T18:25:22Z | 2018-10-02T21:37:06Z |
STYLE: #22885, Moved all setup imports to bottom of benchmark files and added noqa: F401 to each | diff --git a/asv_bench/benchmarks/algorithms.py b/asv_bench/benchmarks/algorithms.py
index fc34440ece2ed..baac179355022 100644
--- a/asv_bench/benchmarks/algorithms.py
+++ b/asv_bench/benchmarks/algorithms.py
@@ -12,8 +12,6 @@
except (ImportError, TypeError, ValueError):
pass
-from .pandas_vb_common import setup # noqa
-
class Factorize(object):
@@ -126,3 +124,6 @@ def time_series_timedeltas(self, df):
def time_series_dates(self, df):
hashing.hash_pandas_object(df['dates'])
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/attrs_caching.py b/asv_bench/benchmarks/attrs_caching.py
index 48f0b7d71144c..7fb9fd26ad8ba 100644
--- a/asv_bench/benchmarks/attrs_caching.py
+++ b/asv_bench/benchmarks/attrs_caching.py
@@ -5,8 +5,6 @@
except ImportError:
from pandas.util.decorators import cache_readonly
-from .pandas_vb_common import setup # noqa
-
class DataFrameAttributes(object):
@@ -38,3 +36,6 @@ def prop(self):
def time_cache_readonly(self):
self.obj.prop
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/binary_ops.py b/asv_bench/benchmarks/binary_ops.py
index cc8766e1fa39c..35787920dc789 100644
--- a/asv_bench/benchmarks/binary_ops.py
+++ b/asv_bench/benchmarks/binary_ops.py
@@ -6,8 +6,6 @@
except ImportError:
import pandas.computation.expressions as expr
-from .pandas_vb_common import setup # noqa
-
class Ops(object):
@@ -149,3 +147,6 @@ def time_add_overflow_b_mask_nan(self):
def time_add_overflow_both_arg_nan(self):
checked_add_with_arr(self.arr, self.arr_mixed, arr_mask=self.arr_nan_1,
b_mask=self.arr_nan_2)
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/categoricals.py b/asv_bench/benchmarks/categoricals.py
index 2a7717378c280..418e60eb6d6d3 100644
--- a/asv_bench/benchmarks/categoricals.py
+++ b/asv_bench/benchmarks/categoricals.py
@@ -11,8 +11,6 @@
except ImportError:
pass
-from .pandas_vb_common import setup # noqa
-
class Concat(object):
@@ -245,3 +243,6 @@ def time_getitem_list(self, index):
def time_getitem_bool_array(self, index):
self.data[self.data == self.cat_scalar]
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/ctors.py b/asv_bench/benchmarks/ctors.py
index 3f9016787aab4..94dbd05917455 100644
--- a/asv_bench/benchmarks/ctors.py
+++ b/asv_bench/benchmarks/ctors.py
@@ -2,8 +2,6 @@
import pandas.util.testing as tm
from pandas import Series, Index, DatetimeIndex, Timestamp, MultiIndex
-from .pandas_vb_common import setup # noqa
-
class SeriesConstructors(object):
@@ -64,3 +62,6 @@ def setup(self):
def time_multiindex_from_iterables(self):
MultiIndex.from_product(self.iterables)
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/eval.py b/asv_bench/benchmarks/eval.py
index 8e581dcf22b4c..da2d7dc7c4492 100644
--- a/asv_bench/benchmarks/eval.py
+++ b/asv_bench/benchmarks/eval.py
@@ -5,8 +5,6 @@
except ImportError:
import pandas.computation.expressions as expr
-from .pandas_vb_common import setup # noqa
-
class Eval(object):
@@ -65,3 +63,6 @@ def time_query_datetime_column(self):
def time_query_with_boolean_selection(self):
self.df.query('(a >= @self.min_val) & (a <= @self.max_val)')
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/frame_ctor.py b/asv_bench/benchmarks/frame_ctor.py
index 9def910df0bab..d3f1a416a7cc1 100644
--- a/asv_bench/benchmarks/frame_ctor.py
+++ b/asv_bench/benchmarks/frame_ctor.py
@@ -7,8 +7,6 @@
# For compatibility with older versions
from pandas.core.datetools import * # noqa
-from .pandas_vb_common import setup # noqa
-
class FromDicts(object):
@@ -99,3 +97,6 @@ def setup(self):
def time_frame_from_ndarray(self):
self.df = DataFrame(self.data)
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py
index f911d506b1f4f..89fd879746f68 100644
--- a/asv_bench/benchmarks/frame_methods.py
+++ b/asv_bench/benchmarks/frame_methods.py
@@ -6,8 +6,6 @@
from pandas import (DataFrame, Series, MultiIndex, date_range, period_range,
isnull, NaT)
-from .pandas_vb_common import setup # noqa
-
class GetNumericData(object):
@@ -537,3 +535,6 @@ def time_series_describe(self):
def time_dataframe_describe(self):
self.df.describe()
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/gil.py b/asv_bench/benchmarks/gil.py
index 21c1ccf46e1c4..32cb60be3f485 100644
--- a/asv_bench/benchmarks/gil.py
+++ b/asv_bench/benchmarks/gil.py
@@ -23,7 +23,7 @@ def wrapper(fname):
return fname
return wrapper
-from .pandas_vb_common import BaseIO, setup # noqa
+from .pandas_vb_common import BaseIO
class ParallelGroupbyMethods(object):
@@ -273,3 +273,6 @@ def time_parallel(self, threads):
def time_loop(self, threads):
for i in range(threads):
self.loop()
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py
index b51b41614bc49..be09bba97bea3 100644
--- a/asv_bench/benchmarks/groupby.py
+++ b/asv_bench/benchmarks/groupby.py
@@ -8,8 +8,6 @@
TimeGrouper, Categorical, Timestamp)
import pandas.util.testing as tm
-from .pandas_vb_common import setup # noqa
-
method_blacklist = {
'object': {'median', 'prod', 'sem', 'cumsum', 'sum', 'cummin', 'mean',
@@ -579,3 +577,6 @@ def setup(self):
def time_first(self):
self.df_nans.groupby('key').transform('first')
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/index_object.py b/asv_bench/benchmarks/index_object.py
index f1703e163917a..c1bc53823a342 100644
--- a/asv_bench/benchmarks/index_object.py
+++ b/asv_bench/benchmarks/index_object.py
@@ -3,8 +3,6 @@
from pandas import (Series, date_range, DatetimeIndex, Index, RangeIndex,
Float64Index)
-from .pandas_vb_common import setup # noqa
-
class SetOperations(object):
@@ -192,3 +190,6 @@ def setup(self):
def time_get_loc(self):
self.ind.get_loc(0)
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py
index 2850fa249725c..e83efdd0fa2a0 100644
--- a/asv_bench/benchmarks/indexing.py
+++ b/asv_bench/benchmarks/indexing.py
@@ -2,10 +2,10 @@
import numpy as np
import pandas.util.testing as tm
-from pandas import (Series, DataFrame, MultiIndex, Panel,
- Int64Index, Float64Index, IntervalIndex,
- CategoricalIndex, IndexSlice, concat, date_range)
-from .pandas_vb_common import setup # noqa
+from pandas import (Series, DataFrame, MultiIndex, Int64Index, Float64Index,
+ IntervalIndex, CategoricalIndex,
+ IndexSlice, concat, date_range)
+from .pandas_vb_common import Panel
class NumericSeriesIndexing(object):
@@ -367,3 +367,6 @@ def time_assign_with_setitem(self):
np.random.seed(1234)
for i in range(100):
self.df[i] = np.random.randn(self.N)
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/inference.py b/asv_bench/benchmarks/inference.py
index 16d9e7cd73cbb..7fb57991c99bc 100644
--- a/asv_bench/benchmarks/inference.py
+++ b/asv_bench/benchmarks/inference.py
@@ -2,7 +2,7 @@
import pandas.util.testing as tm
from pandas import DataFrame, Series, to_numeric
-from .pandas_vb_common import numeric_dtypes, lib, setup # noqa
+from .pandas_vb_common import numeric_dtypes, lib
class NumericInferOps(object):
@@ -111,3 +111,6 @@ def setup_cache(self):
def time_convert(self, data):
lib.maybe_convert_numeric(data, set(), coerce_numeric=False)
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/io/csv.py b/asv_bench/benchmarks/io/csv.py
index 12cb893462b87..ac2370fe85e5a 100644
--- a/asv_bench/benchmarks/io/csv.py
+++ b/asv_bench/benchmarks/io/csv.py
@@ -6,7 +6,7 @@
from pandas import DataFrame, Categorical, date_range, read_csv
from pandas.compat import cStringIO as StringIO
-from ..pandas_vb_common import setup, BaseIO # noqa
+from ..pandas_vb_common import BaseIO
class ToCSV(BaseIO):
@@ -225,3 +225,6 @@ def time_baseline(self):
read_csv(self.data(self.StringIO_input), sep=',', header=None,
parse_dates=[1],
names=list(string.digits[:9]))
+
+
+from ..pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/io/excel.py b/asv_bench/benchmarks/io/excel.py
index 58ab6bb8046c5..b873dc1040a66 100644
--- a/asv_bench/benchmarks/io/excel.py
+++ b/asv_bench/benchmarks/io/excel.py
@@ -3,7 +3,7 @@
from pandas.compat import BytesIO
import pandas.util.testing as tm
-from ..pandas_vb_common import BaseIO, setup # noqa
+from ..pandas_vb_common import BaseIO
class Excel(object):
@@ -34,3 +34,6 @@ def time_write_excel(self, engine):
writer_write = ExcelWriter(bio_write, engine=engine)
self.df.to_excel(writer_write, sheet_name='Sheet1')
writer_write.save()
+
+
+from ..pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/io/hdf.py b/asv_bench/benchmarks/io/hdf.py
index 4b6e1d69af92d..c150d82450770 100644
--- a/asv_bench/benchmarks/io/hdf.py
+++ b/asv_bench/benchmarks/io/hdf.py
@@ -4,7 +4,7 @@
from pandas import DataFrame, Panel, date_range, HDFStore, read_hdf
import pandas.util.testing as tm
-from ..pandas_vb_common import BaseIO, setup # noqa
+from ..pandas_vb_common import BaseIO
class HDFStoreDataFrame(BaseIO):
@@ -149,3 +149,6 @@ def time_read_hdf(self, format):
def time_write_hdf(self, format):
self.df.to_hdf(self.fname, 'df', format=format)
+
+
+from ..pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/io/json.py b/asv_bench/benchmarks/io/json.py
index acfdd327c3b51..df5bf7341c303 100644
--- a/asv_bench/benchmarks/io/json.py
+++ b/asv_bench/benchmarks/io/json.py
@@ -2,7 +2,7 @@
import pandas.util.testing as tm
from pandas import DataFrame, date_range, timedelta_range, concat, read_json
-from ..pandas_vb_common import setup, BaseIO # noqa
+from ..pandas_vb_common import BaseIO
class ReadJSON(BaseIO):
@@ -125,3 +125,6 @@ def time_float_int_lines(self, orient):
def time_float_int_str_lines(self, orient):
self.df_int_float_str.to_json(self.fname, orient='records', lines=True)
+
+
+from ..pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/io/msgpack.py b/asv_bench/benchmarks/io/msgpack.py
index 8ccce01117ca4..7033aa9ce3c40 100644
--- a/asv_bench/benchmarks/io/msgpack.py
+++ b/asv_bench/benchmarks/io/msgpack.py
@@ -2,7 +2,7 @@
from pandas import DataFrame, date_range, read_msgpack
import pandas.util.testing as tm
-from ..pandas_vb_common import BaseIO, setup # noqa
+from ..pandas_vb_common import BaseIO
class MSGPack(BaseIO):
@@ -24,3 +24,6 @@ def time_read_msgpack(self):
def time_write_msgpack(self):
self.df.to_msgpack(self.fname)
+
+
+from ..pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/io/pickle.py b/asv_bench/benchmarks/io/pickle.py
index 2ad0fcca6eb26..0960d721281c7 100644
--- a/asv_bench/benchmarks/io/pickle.py
+++ b/asv_bench/benchmarks/io/pickle.py
@@ -2,7 +2,7 @@
from pandas import DataFrame, date_range, read_pickle
import pandas.util.testing as tm
-from ..pandas_vb_common import BaseIO, setup # noqa
+from ..pandas_vb_common import BaseIO
class Pickle(BaseIO):
@@ -24,3 +24,6 @@ def time_read_pickle(self):
def time_write_pickle(self):
self.df.to_pickle(self.fname)
+
+
+from ..pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/io/sql.py b/asv_bench/benchmarks/io/sql.py
index ef4e501e5f3b9..6a8529cad592b 100644
--- a/asv_bench/benchmarks/io/sql.py
+++ b/asv_bench/benchmarks/io/sql.py
@@ -5,8 +5,6 @@
from pandas import DataFrame, date_range, read_sql_query, read_sql_table
from sqlalchemy import create_engine
-from ..pandas_vb_common import setup # noqa
-
class SQL(object):
@@ -130,3 +128,6 @@ def setup(self, dtype):
def time_read_sql_table_column(self, dtype):
read_sql_table(self.table_name, self.con, columns=[dtype])
+
+
+from ..pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/io/stata.py b/asv_bench/benchmarks/io/stata.py
index e0f5752ca930f..d74a531877e18 100644
--- a/asv_bench/benchmarks/io/stata.py
+++ b/asv_bench/benchmarks/io/stata.py
@@ -2,7 +2,7 @@
from pandas import DataFrame, date_range, read_stata
import pandas.util.testing as tm
-from ..pandas_vb_common import BaseIO, setup # noqa
+from ..pandas_vb_common import BaseIO
class Stata(BaseIO):
@@ -35,3 +35,6 @@ def time_read_stata(self, convert_dates):
def time_write_stata(self, convert_dates):
self.df.to_stata(self.fname, self.convert_dates)
+
+
+from ..pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/join_merge.py b/asv_bench/benchmarks/join_merge.py
index 6624c3d0aaf49..57811dec8cd29 100644
--- a/asv_bench/benchmarks/join_merge.py
+++ b/asv_bench/benchmarks/join_merge.py
@@ -11,7 +11,7 @@
except ImportError:
from pandas import ordered_merge as merge_ordered
-from .pandas_vb_common import setup # noqa
+from .pandas_vb_common import Panel
class Append(object):
@@ -361,3 +361,6 @@ def time_series_align_int64_index(self):
def time_series_align_left_monotonic(self):
self.ts1.align(self.ts2, join='left')
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/multiindex_object.py b/asv_bench/benchmarks/multiindex_object.py
index 0c92214795557..eaf2bbbe510c2 100644
--- a/asv_bench/benchmarks/multiindex_object.py
+++ b/asv_bench/benchmarks/multiindex_object.py
@@ -4,8 +4,6 @@
import pandas.util.testing as tm
from pandas import date_range, MultiIndex
-from .pandas_vb_common import setup # noqa
-
class GetLoc(object):
@@ -138,3 +136,6 @@ def time_datetime_level_values_copy(self, mi):
def time_datetime_level_values_sliced(self, mi):
mi[:10].values
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/panel_ctor.py b/asv_bench/benchmarks/panel_ctor.py
index 4614bbd198afa..b87583ef925f3 100644
--- a/asv_bench/benchmarks/panel_ctor.py
+++ b/asv_bench/benchmarks/panel_ctor.py
@@ -3,7 +3,7 @@
from pandas import DataFrame, Panel, DatetimeIndex, date_range
-from .pandas_vb_common import setup # noqa
+from .pandas_vb_common import Panel
class DifferentIndexes(object):
@@ -58,3 +58,6 @@ def setup(self):
def time_from_dict(self):
with warnings.catch_warnings(record=True):
Panel.from_dict(self.data_frames)
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/panel_methods.py b/asv_bench/benchmarks/panel_methods.py
index 4d19e9a87c507..e35455f36ed98 100644
--- a/asv_bench/benchmarks/panel_methods.py
+++ b/asv_bench/benchmarks/panel_methods.py
@@ -3,7 +3,7 @@
import numpy as np
from pandas import Panel
-from .pandas_vb_common import setup # noqa
+from .pandas_vb_common import Panel
class PanelMethods(object):
@@ -23,3 +23,6 @@ def time_pct_change(self, axis):
def time_shift(self, axis):
with warnings.catch_warnings(record=True):
self.panel.shift(1, axis=axis)
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/plotting.py b/asv_bench/benchmarks/plotting.py
index 5b49112b0e07d..68dc39b648152 100644
--- a/asv_bench/benchmarks/plotting.py
+++ b/asv_bench/benchmarks/plotting.py
@@ -7,8 +7,6 @@
import matplotlib
matplotlib.use('Agg')
-from .pandas_vb_common import setup # noqa
-
class Plotting(object):
@@ -62,3 +60,6 @@ def setup(self):
def time_plot_andrews_curves(self):
andrews_curves(self.df, "Name")
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/reindex.py b/asv_bench/benchmarks/reindex.py
index 413427a16f40b..13f2877e6048d 100644
--- a/asv_bench/benchmarks/reindex.py
+++ b/asv_bench/benchmarks/reindex.py
@@ -2,7 +2,7 @@
import pandas.util.testing as tm
from pandas import (DataFrame, Series, DatetimeIndex, MultiIndex, Index,
date_range)
-from .pandas_vb_common import setup, lib # noqa
+from .pandas_vb_common import lib
class Reindex(object):
@@ -170,3 +170,6 @@ def setup(self):
def time_lib_fast_zip(self):
lib.fast_zip(self.col_array_list)
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/replace.py b/asv_bench/benchmarks/replace.py
index 41208125e8f32..3236b09acec37 100644
--- a/asv_bench/benchmarks/replace.py
+++ b/asv_bench/benchmarks/replace.py
@@ -1,8 +1,6 @@
import numpy as np
import pandas as pd
-from .pandas_vb_common import setup # noqa
-
class FillNa(object):
@@ -56,3 +54,6 @@ def setup(self, constructor, replace_data):
def time_replace(self, constructor, replace_data):
self.data.replace(self.to_replace)
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/reshape.py b/asv_bench/benchmarks/reshape.py
index 3cf9a32dab398..3140f6fc81cbb 100644
--- a/asv_bench/benchmarks/reshape.py
+++ b/asv_bench/benchmarks/reshape.py
@@ -5,8 +5,6 @@
from pandas import DataFrame, MultiIndex, date_range, melt, wide_to_long
import pandas as pd
-from .pandas_vb_common import setup # noqa
-
class Melt(object):
@@ -150,3 +148,6 @@ def time_get_dummies_1d(self):
def time_get_dummies_1d_sparse(self):
pd.get_dummies(self.s, sparse=True)
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/rolling.py b/asv_bench/benchmarks/rolling.py
index e3bf551fa5f2b..86294e33e1e06 100644
--- a/asv_bench/benchmarks/rolling.py
+++ b/asv_bench/benchmarks/rolling.py
@@ -1,8 +1,6 @@
import pandas as pd
import numpy as np
-from .pandas_vb_common import setup # noqa
-
class Methods(object):
@@ -77,3 +75,6 @@ def setup(self, constructor, window, dtype, percentile, interpolation):
def time_quantile(self, constructor, window, dtype, percentile,
interpolation):
self.roll.quantile(percentile, interpolation=interpolation)
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py
index a26c5d89bc483..2388acbc2d33f 100644
--- a/asv_bench/benchmarks/series_methods.py
+++ b/asv_bench/benchmarks/series_methods.py
@@ -4,8 +4,6 @@
import pandas.util.testing as tm
from pandas import Series, date_range, NaT
-from .pandas_vb_common import setup # noqa
-
class SeriesConstructor(object):
@@ -192,3 +190,6 @@ def setup(self):
def time_series_datetimeindex_repr(self):
getattr(self.s, 'a', None)
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/sparse.py b/asv_bench/benchmarks/sparse.py
index dcb7694abc2ad..bbc076790a923 100644
--- a/asv_bench/benchmarks/sparse.py
+++ b/asv_bench/benchmarks/sparse.py
@@ -5,8 +5,6 @@
from pandas import (SparseSeries, SparseDataFrame, SparseArray, Series,
date_range, MultiIndex)
-from .pandas_vb_common import setup # noqa
-
def make_array(size, dense_proportion, fill_value, dtype):
dense_size = int(size * dense_proportion)
@@ -160,3 +158,6 @@ def time_addition(self, fill_value):
def time_division(self, fill_value):
self.arr1 / self.arr2
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/stat_ops.py b/asv_bench/benchmarks/stat_ops.py
index ecfcb27806f54..3a6223d283073 100644
--- a/asv_bench/benchmarks/stat_ops.py
+++ b/asv_bench/benchmarks/stat_ops.py
@@ -1,8 +1,6 @@
import numpy as np
import pandas as pd
-from .pandas_vb_common import setup # noqa
-
ops = ['mean', 'sum', 'median', 'std', 'skew', 'kurt', 'mad', 'prod', 'sem',
'var']
@@ -112,3 +110,6 @@ def setup(self, method):
def time_corr(self, method):
self.df.corr(method=method)
+
+
+from .pandas_vb_common import setup # noqa: F401
diff --git a/asv_bench/benchmarks/timeseries.py b/asv_bench/benchmarks/timeseries.py
index 2557ba7672a0e..11a789453c2df 100644
--- a/asv_bench/benchmarks/timeseries.py
+++ b/asv_bench/benchmarks/timeseries.py
@@ -8,8 +8,6 @@
except ImportError:
from pandas.tseries.converter import DatetimeConverter
-from .pandas_vb_common import setup # noqa
-
class DatetimeIndex(object):
@@ -416,3 +414,6 @@ def time_dt_accessor(self):
def time_dt_accessor_normalize(self):
self.series.dt.normalize()
+
+
+from .pandas_vb_common import setup # noqa: F401
| - [x] closes #22885
- [ ] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
#22885
Following the suggestions of @datapythonista, I moved all the `setup` imports for the benchmark files to the end of each file and added a `# noqa: F401` like so:
`from .pandas_vb_common import setup # noqa: F401`
Now, `flake8` only returns the following two errors in `asv_bench`:
```
./benchmarks/strings.py:95:9: E731 do not assign a lambda expression, use a def
./benchmarks/io/excel.py:6:1: F401 '..pandas_vb_common.BaseIO' imported but unused
```
These may be expected, but I wanted to mention them here just in case they need addressing.
Also, running `pytest`, I got this error:
```
usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --strict-data-files
inifile: /pandas/setup.cfg
rootdir: /pandas
```
I found a discussion on it at #22700, but there didn't seem to be a definitive solution. Open to guidance on this.
Please let me know if any corrections are needed. Thanks! | https://api.github.com/repos/pandas-dev/pandas/pulls/22947 | 2018-10-02T16:17:35Z | 2018-10-10T17:00:48Z | 2018-10-10T17:00:47Z | 2018-10-10T17:24:29Z |
BUG: Correctly weekly resample over DST | diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt
index 851c1a3fbd6e9..a64576565d093 100644
--- a/doc/source/whatsnew/v0.24.0.txt
+++ b/doc/source/whatsnew/v0.24.0.txt
@@ -794,6 +794,7 @@ Groupby/Resample/Rolling
- Bug in :meth:`Resampler.asfreq` when frequency of ``TimedeltaIndex`` is a subperiod of a new frequency (:issue:`13022`).
- Bug in :meth:`SeriesGroupBy.mean` when values were integral but could not fit inside of int64, overflowing instead. (:issue:`22487`)
- :func:`RollingGroupby.agg` and :func:`ExpandingGroupby.agg` now support multiple aggregation functions as parameters (:issue:`15072`)
+- Bug in :meth:`DataFrame.resample` and :meth:`Series.resample` when resampling by a weekly offset (``'W'``) across a DST transition (:issue:`9119`, :issue:`21459`)
Sparse
^^^^^^
diff --git a/pandas/core/resample.py b/pandas/core/resample.py
index 878ac957a8557..70a8deb33b7f2 100644
--- a/pandas/core/resample.py
+++ b/pandas/core/resample.py
@@ -16,7 +16,8 @@
from pandas.tseries.frequencies import to_offset, is_subperiod, is_superperiod
from pandas.core.indexes.datetimes import DatetimeIndex, date_range
from pandas.core.indexes.timedeltas import TimedeltaIndex
-from pandas.tseries.offsets import DateOffset, Tick, Day, delta_to_nanoseconds
+from pandas.tseries.offsets import (DateOffset, Tick, Day,
+ delta_to_nanoseconds, Nano)
from pandas.core.indexes.period import PeriodIndex
from pandas.errors import AbstractMethodError
import pandas.core.algorithms as algos
@@ -1395,18 +1396,21 @@ def _get_time_bins(self, ax):
def _adjust_bin_edges(self, binner, ax_values):
# Some hacks for > daily data, see #1471, #1458, #1483
- bin_edges = binner.asi8
-
if self.freq != 'D' and is_superperiod(self.freq, 'D'):
- day_nanos = delta_to_nanoseconds(timedelta(1))
if self.closed == 'right':
- bin_edges = bin_edges + day_nanos - 1
+ # GH 21459, GH 9119: Adjust the bins relative to the wall time
+ bin_edges = binner.tz_localize(None)
+ bin_edges = bin_edges + timedelta(1) - Nano(1)
+ bin_edges = bin_edges.tz_localize(binner.tz).asi8
+ else:
+ bin_edges = binner.asi8
# intraday values on last day
if bin_edges[-2] > ax_values.max():
bin_edges = bin_edges[:-1]
binner = binner[:-1]
-
+ else:
+ bin_edges = binner.asi8
return binner, bin_edges
def _get_time_delta_bins(self, ax):
diff --git a/pandas/tests/test_resample.py b/pandas/tests/test_resample.py
index ccd2461d1512e..5cd31e08e0a9b 100644
--- a/pandas/tests/test_resample.py
+++ b/pandas/tests/test_resample.py
@@ -2114,6 +2114,28 @@ def test_downsample_across_dst(self):
freq='H'))
tm.assert_series_equal(result, expected)
+ def test_downsample_across_dst_weekly(self):
+ # GH 9119, GH 21459
+ df = DataFrame(index=DatetimeIndex([
+ '2017-03-25', '2017-03-26', '2017-03-27',
+ '2017-03-28', '2017-03-29'
+ ], tz='Europe/Amsterdam'),
+ data=[11, 12, 13, 14, 15])
+ result = df.resample('1W').sum()
+ expected = DataFrame([23, 42], index=pd.DatetimeIndex([
+ '2017-03-26', '2017-04-02'
+ ], tz='Europe/Amsterdam'))
+ tm.assert_frame_equal(result, expected)
+
+ idx = pd.date_range("2013-04-01", "2013-05-01", tz='Europe/London',
+ freq='H')
+ s = Series(index=idx)
+ result = s.resample('W').mean()
+ expected = Series(index=pd.date_range(
+ '2013-04-07', freq='W', periods=5, tz='Europe/London'
+ ))
+ tm.assert_series_equal(result, expected)
+
def test_resample_with_nat(self):
# GH 13020
index = DatetimeIndex([pd.NaT,
| - [x] closes #21459
- [x] closes #9119
- [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/22941 | 2018-10-02T07:06:44Z | 2018-10-03T15:25:46Z | 2018-10-03T15:25:45Z | 2018-10-03T15:25:55Z |
ENH: Implement overlaps method for Interval-like | diff --git a/doc/source/api.rst b/doc/source/api.rst
index 073ed8a082a11..ce8e9f737e5af 100644
--- a/doc/source/api.rst
+++ b/doc/source/api.rst
@@ -1651,6 +1651,7 @@ IntervalIndex Components
IntervalIndex.get_loc
IntervalIndex.get_indexer
IntervalIndex.set_closed
+ IntervalIndex.overlaps
.. _api.multiindex:
@@ -2037,6 +2038,7 @@ Properties
Interval.mid
Interval.open_left
Interval.open_right
+ Interval.overlaps
Interval.right
Timedelta
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt
index 851c1a3fbd6e9..428278ad2c781 100644
--- a/doc/source/whatsnew/v0.24.0.txt
+++ b/doc/source/whatsnew/v0.24.0.txt
@@ -194,6 +194,7 @@ Other Enhancements
- :meth:`Index.to_frame` now supports overriding column name(s) (:issue:`22580`).
- New attribute :attr:`__git_version__` will return git commit sha of current build (:issue:`21295`).
- Compatibility with Matplotlib 3.0 (:issue:`22790`).
+- Added :meth:`Interval.overlaps`, :meth:`IntervalArray.overlaps`, and :meth:`IntervalIndex.overlaps` for determining overlaps between interval-like objects (:issue:`21998`)
.. _whatsnew_0240.api_breaking:
diff --git a/pandas/_libs/interval.pyx b/pandas/_libs/interval.pyx
index 82261094022fb..a395fdbabeca2 100644
--- a/pandas/_libs/interval.pyx
+++ b/pandas/_libs/interval.pyx
@@ -10,6 +10,7 @@ from cython cimport Py_ssize_t
import numpy as np
from numpy cimport ndarray
+from operator import le, lt
cimport util
util.import_array()
@@ -359,6 +360,67 @@ cdef class Interval(IntervalMixin):
self.left // y, self.right // y, closed=self.closed)
return NotImplemented
+ def overlaps(self, other):
+ """
+ Check whether two Interval objects overlap.
+
+ Two intervals overlap if they share a common point, including closed
+ endpoints. Intervals that only have an open endpoint in common do not
+ overlap.
+
+ .. versionadded:: 0.24.0
+
+ Parameters
+ ----------
+ other : Interval
+ The interval to check against for an overlap.
+
+ Returns
+ -------
+ bool
+ ``True`` if the two intervals overlap, else ``False``.
+
+ Examples
+ --------
+ >>> i1 = pd.Interval(0, 2)
+ >>> i2 = pd.Interval(1, 3)
+ >>> i1.overlaps(i2)
+ True
+ >>> i3 = pd.Interval(4, 5)
+ >>> i1.overlaps(i3)
+ False
+
+ Intervals that share closed endpoints overlap:
+
+ >>> i4 = pd.Interval(0, 1, closed='both')
+ >>> i5 = pd.Interval(1, 2, closed='both')
+ >>> i4.overlaps(i5)
+ True
+
+ Intervals that only have an open endpoint in common do not overlap:
+
+ >>> i6 = pd.Interval(1, 2, closed='neither')
+ >>> i4.overlaps(i6)
+ False
+
+ See Also
+ --------
+ IntervalArray.overlaps : The corresponding method for IntervalArray
+ IntervalIndex.overlaps : The corresponding method for IntervalIndex
+ """
+ if not isinstance(other, Interval):
+ msg = '`other` must be an Interval, got {other}'
+ raise TypeError(msg.format(other=type(other).__name__))
+
+ # equality is okay if both endpoints are closed (overlap at a point)
+ op1 = le if (self.closed_left and other.closed_right) else lt
+ op2 = le if (other.closed_left and self.closed_right) else lt
+
+ # overlaps is equivalent negation of two interval being disjoint:
+ # disjoint = (A.left > B.right) or (B.left > A.right)
+ # (simplifying the negation allows this to be done in less operations)
+ return op1(self.left, other.right) and op2(other.left, self.right)
+
@cython.wraparound(False)
@cython.boundscheck(False)
diff --git a/pandas/conftest.py b/pandas/conftest.py
index 621de3ffd4b12..fd3c9c277b397 100644
--- a/pandas/conftest.py
+++ b/pandas/conftest.py
@@ -275,6 +275,14 @@ def closed(request):
return request.param
+@pytest.fixture(params=['left', 'right', 'both', 'neither'])
+def other_closed(request):
+ """
+ Secondary closed fixture to allow parametrizing over all pairs of closed
+ """
+ return request.param
+
+
@pytest.fixture(params=[None, np.nan, pd.NaT, float('nan'), np.float('NaN')])
def nulls_fixture(request):
"""
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 90df596b98296..1ac89c0b18462 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -1,6 +1,8 @@
import textwrap
import numpy as np
+from operator import le, lt
+
from pandas._libs.interval import (Interval, IntervalMixin,
intervals_to_interval_bounds)
from pandas.compat import add_metaclass
@@ -27,8 +29,11 @@
_VALID_CLOSED = {'left', 'right', 'both', 'neither'}
_interval_shared_docs = {}
+
+# TODO(jschendel) remove constructor key when IntervalArray is public (GH22860)
_shared_docs_kwargs = dict(
klass='IntervalArray',
+ constructor='pd.core.arrays.IntervalArray',
name=''
)
@@ -1015,6 +1020,67 @@ def repeat(self, repeats, **kwargs):
right_repeat = self.right.repeat(repeats, **kwargs)
return self._shallow_copy(left=left_repeat, right=right_repeat)
+ _interval_shared_docs['overlaps'] = """
+ Check elementwise if an Interval overlaps the values in the %(klass)s.
+
+ Two intervals overlap if they share a common point, including closed
+ endpoints. Intervals that only have an open endpoint in common do not
+ overlap.
+
+ .. versionadded:: 0.24.0
+
+ Parameters
+ ----------
+ other : Interval
+ Interval to check against for an overlap.
+
+ Returns
+ -------
+ ndarray
+ Boolean array positionally indicating where an overlap occurs.
+
+ Examples
+ --------
+ >>> intervals = %(constructor)s.from_tuples([(0, 1), (1, 3), (2, 4)])
+ >>> intervals
+ %(klass)s([(0, 1], (1, 3], (2, 4]],
+ closed='right',
+ dtype='interval[int64]')
+ >>> intervals.overlaps(pd.Interval(0.5, 1.5))
+ array([ True, True, False])
+
+ Intervals that share closed endpoints overlap:
+
+ >>> intervals.overlaps(pd.Interval(1, 3, closed='left'))
+ array([ True, True, True])
+
+ Intervals that only have an open endpoint in common do not overlap:
+
+ >>> intervals.overlaps(pd.Interval(1, 2, closed='right'))
+ array([False, True, False])
+
+ See Also
+ --------
+ Interval.overlaps : Check whether two Interval objects overlap.
+ """
+
+ @Appender(_interval_shared_docs['overlaps'] % _shared_docs_kwargs)
+ def overlaps(self, other):
+ if isinstance(other, (IntervalArray, ABCIntervalIndex)):
+ raise NotImplementedError
+ elif not isinstance(other, Interval):
+ msg = '`other` must be Interval-like, got {other}'
+ raise TypeError(msg.format(other=type(other).__name__))
+
+ # equality is okay if both endpoints are closed (overlap at a point)
+ op1 = le if (self.closed_left and other.closed_right) else lt
+ op2 = le if (other.closed_left and self.closed_right) else lt
+
+ # overlaps is equivalent negation of two interval being disjoint:
+ # disjoint = (A.left > B.right) or (B.left > A.right)
+ # (simplifying the negation allows this to be done in less operations)
+ return op1(self.left, other.right) & op2(other.left, self.right)
+
def maybe_convert_platform_interval(values):
"""
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index 4b125580bd7e0..5a058c80d40c8 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -46,8 +46,11 @@
_VALID_CLOSED = {'left', 'right', 'both', 'neither'}
_index_doc_kwargs = dict(ibase._index_doc_kwargs)
+
+# TODO(jschendel) remove constructor key when IntervalArray is public (GH22860)
_index_doc_kwargs.update(
dict(klass='IntervalIndex',
+ constructor='pd.IntervalIndex',
target_klass='IntervalIndex or list of Intervals',
name=textwrap.dedent("""\
name : object, optional
@@ -982,6 +985,10 @@ def equals(self, other):
self.right.equals(other.right) and
self.closed == other.closed)
+ @Appender(_interval_shared_docs['overlaps'] % _index_doc_kwargs)
+ def overlaps(self, other):
+ return self._data.overlaps(other)
+
def _setop(op_name):
def func(self, other):
other = self._as_like_interval_index(other)
diff --git a/pandas/tests/arrays/interval/__init__.py b/pandas/tests/arrays/interval/__init__.py
new file mode 100644
index 0000000000000..e69de29bb2d1d
diff --git a/pandas/tests/arrays/test_interval.py b/pandas/tests/arrays/interval/test_interval.py
similarity index 100%
rename from pandas/tests/arrays/test_interval.py
rename to pandas/tests/arrays/interval/test_interval.py
index bcf4cea795978..ff69b68f1117c 100644
--- a/pandas/tests/arrays/test_interval.py
+++ b/pandas/tests/arrays/interval/test_interval.py
@@ -1,10 +1,10 @@
# -*- coding: utf-8 -*-
-import pytest
import numpy as np
+import pytest
+import pandas.util.testing as tm
from pandas import Index, IntervalIndex, date_range, timedelta_range
from pandas.core.arrays import IntervalArray
-import pandas.util.testing as tm
@pytest.fixture(params=[
diff --git a/pandas/tests/arrays/interval/test_ops.py b/pandas/tests/arrays/interval/test_ops.py
new file mode 100644
index 0000000000000..7000ff0f0c3f6
--- /dev/null
+++ b/pandas/tests/arrays/interval/test_ops.py
@@ -0,0 +1,82 @@
+"""Tests for Interval-Interval operations, such as overlaps, contains, etc."""
+import numpy as np
+import pytest
+
+import pandas.util.testing as tm
+from pandas import Interval, IntervalIndex, Timedelta, Timestamp
+from pandas.core.arrays import IntervalArray
+
+
+@pytest.fixture(params=[IntervalArray, IntervalIndex])
+def constructor(request):
+ """
+ Fixture for testing both interval container classes.
+ """
+ return request.param
+
+
+@pytest.fixture(params=[
+ (Timedelta('0 days'), Timedelta('1 day')),
+ (Timestamp('2018-01-01'), Timedelta('1 day')),
+ (0, 1)], ids=lambda x: type(x[0]).__name__)
+def start_shift(request):
+ """
+ Fixture for generating intervals of different types from a start value
+ and a shift value that can be added to start to generate an endpoint.
+ """
+ return request.param
+
+
+class TestOverlaps(object):
+
+ def test_overlaps_interval(
+ self, constructor, start_shift, closed, other_closed):
+ start, shift = start_shift
+ interval = Interval(start, start + 3 * shift, other_closed)
+
+ # intervals: identical, nested, spanning, partial, adjacent, disjoint
+ tuples = [(start, start + 3 * shift),
+ (start + shift, start + 2 * shift),
+ (start - shift, start + 4 * shift),
+ (start + 2 * shift, start + 4 * shift),
+ (start + 3 * shift, start + 4 * shift),
+ (start + 4 * shift, start + 5 * shift)]
+ interval_container = constructor.from_tuples(tuples, closed)
+
+ adjacent = (interval.closed_right and interval_container.closed_left)
+ expected = np.array([True, True, True, True, adjacent, False])
+ result = interval_container.overlaps(interval)
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize('other_constructor', [
+ IntervalArray, IntervalIndex])
+ def test_overlaps_interval_container(self, constructor, other_constructor):
+ # TODO: modify this test when implemented
+ interval_container = constructor.from_breaks(range(5))
+ other_container = other_constructor.from_breaks(range(5))
+ with pytest.raises(NotImplementedError):
+ interval_container.overlaps(other_container)
+
+ def test_overlaps_na(self, constructor, start_shift):
+ """NA values are marked as False"""
+ start, shift = start_shift
+ interval = Interval(start, start + shift)
+
+ tuples = [(start, start + shift),
+ np.nan,
+ (start + 2 * shift, start + 3 * shift)]
+ interval_container = constructor.from_tuples(tuples)
+
+ expected = np.array([True, False, False])
+ result = interval_container.overlaps(interval)
+ tm.assert_numpy_array_equal(result, expected)
+
+ @pytest.mark.parametrize('other', [
+ 10, True, 'foo', Timedelta('1 day'), Timestamp('2018-01-01')],
+ ids=lambda x: type(x).__name__)
+ def test_overlaps_invalid_type(self, constructor, other):
+ interval_container = constructor.from_breaks(range(5))
+ msg = '`other` must be Interval-like, got {other}'.format(
+ other=type(other).__name__)
+ with tm.assert_raises_regex(TypeError, msg):
+ interval_container.overlaps(other)
diff --git a/pandas/tests/scalar/interval/test_ops.py b/pandas/tests/scalar/interval/test_ops.py
new file mode 100644
index 0000000000000..cfd9fc34faeff
--- /dev/null
+++ b/pandas/tests/scalar/interval/test_ops.py
@@ -0,0 +1,61 @@
+"""Tests for Interval-Interval operations, such as overlaps, contains, etc."""
+import pytest
+
+import pandas.util.testing as tm
+from pandas import Interval, Timedelta, Timestamp
+
+
+@pytest.fixture(params=[
+ (Timedelta('0 days'), Timedelta('1 day')),
+ (Timestamp('2018-01-01'), Timedelta('1 day')),
+ (0, 1)], ids=lambda x: type(x[0]).__name__)
+def start_shift(request):
+ """
+ Fixture for generating intervals of types from a start value and a shift
+ value that can be added to start to generate an endpoint
+ """
+ return request.param
+
+
+class TestOverlaps(object):
+
+ def test_overlaps_self(self, start_shift, closed):
+ start, shift = start_shift
+ interval = Interval(start, start + shift, closed)
+ assert interval.overlaps(interval)
+
+ def test_overlaps_nested(self, start_shift, closed, other_closed):
+ start, shift = start_shift
+ interval1 = Interval(start, start + 3 * shift, other_closed)
+ interval2 = Interval(start + shift, start + 2 * shift, closed)
+
+ # nested intervals should always overlap
+ assert interval1.overlaps(interval2)
+
+ def test_overlaps_disjoint(self, start_shift, closed, other_closed):
+ start, shift = start_shift
+ interval1 = Interval(start, start + shift, other_closed)
+ interval2 = Interval(start + 2 * shift, start + 3 * shift, closed)
+
+ # disjoint intervals should never overlap
+ assert not interval1.overlaps(interval2)
+
+ def test_overlaps_endpoint(self, start_shift, closed, other_closed):
+ start, shift = start_shift
+ interval1 = Interval(start, start + shift, other_closed)
+ interval2 = Interval(start + shift, start + 2 * shift, closed)
+
+ # overlap if shared endpoint is closed for both (overlap at a point)
+ result = interval1.overlaps(interval2)
+ expected = interval1.closed_right and interval2.closed_left
+ assert result == expected
+
+ @pytest.mark.parametrize('other', [
+ 10, True, 'foo', Timedelta('1 day'), Timestamp('2018-01-01')],
+ ids=lambda x: type(x).__name__)
+ def test_overlaps_invalid_type(self, other):
+ interval = Interval(0, 1)
+ msg = '`other` must be an Interval, got {other}'.format(
+ other=type(other).__name__)
+ with tm.assert_raises_regex(TypeError, msg):
+ interval.overlaps(other)
| - [X] tests added / passed
- [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [X] whatsnew entry
- xref #21998, #18975
Implements `Interval.overlaps`, `IntervalArray.overlaps`, and `IntervalIndex.overlaps`.
Implementing this so there's an interval method that can be tested in the interval accessor PR (#19502), as there are currently only attributes that can be used by the accessor. Planning to reboot that PR soon after this is merged.
I didn't implement `IntervalArray.overlaps(IntervalArray)`; the PR providing the specs for `overlaps` was recently closed due to being stale, and I don't recall there being a resolution on this behavior.
| https://api.github.com/repos/pandas-dev/pandas/pulls/22939 | 2018-10-02T03:10:44Z | 2018-10-24T12:18:58Z | 2018-10-24T12:18:58Z | 2018-10-25T02:14:40Z |
Update type for PeriodDtype / DatetimeTZDtype / IntervalDtype | diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt
index 851c1a3fbd6e9..9808f5d735535 100644
--- a/doc/source/whatsnew/v0.24.0.txt
+++ b/doc/source/whatsnew/v0.24.0.txt
@@ -505,6 +505,7 @@ ExtensionType Changes
- :meth:`Series.astype` and :meth:`DataFrame.astype` now dispatch to :meth:`ExtensionArray.astype` (:issue:`21185:`).
- Slicing a single row of a ``DataFrame`` with multiple ExtensionArrays of the same type now preserves the dtype, rather than coercing to object (:issue:`22784`)
- Added :meth:`pandas.api.types.register_extension_dtype` to register an extension type with pandas (:issue:`22664`)
+- Updated the ``.type`` attribute for ``PeriodDtype``, ``DatetimeTZDtype``, and ``IntervalDtype`` to be instances of the dtype (``Period``, ``Timestamp``, and ``Interval`` respectively) (:issue:`22938`)
.. _whatsnew_0240.api.incompatibilities:
diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py
index a552251ebbafa..5c9ba921226c0 100644
--- a/pandas/core/dtypes/base.py
+++ b/pandas/core/dtypes/base.py
@@ -175,7 +175,9 @@ def type(self):
"""The scalar type for the array, e.g. ``int``
It's expected ``ExtensionArray[item]`` returns an instance
- of ``ExtensionDtype.type`` for scalar ``item``.
+ of ``ExtensionDtype.type`` for scalar ``item``, assuming
+ that value is valid (not NA). NA values do not need to be
+ instances of `type`.
"""
raise AbstractMethodError(self)
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index e2b9e246aee50..7c91e62cc9876 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -4,12 +4,13 @@
from pandas.compat import (string_types, text_type, binary_type,
PY3, PY36)
from pandas._libs import algos, lib
-from pandas._libs.tslibs import conversion
+from pandas._libs.tslibs import conversion, Period, Timestamp
+from pandas._libs.interval import Interval
from pandas.core.dtypes.dtypes import (
registry, CategoricalDtype, CategoricalDtypeType, DatetimeTZDtype,
- DatetimeTZDtypeType, PeriodDtype, PeriodDtypeType, IntervalDtype,
- IntervalDtypeType, PandasExtensionDtype, ExtensionDtype,
+ PeriodDtype, IntervalDtype,
+ PandasExtensionDtype, ExtensionDtype,
_pandas_registry)
from pandas.core.dtypes.generic import (
ABCCategorical, ABCPeriodIndex, ABCDatetimeIndex, ABCSeries,
@@ -1905,20 +1906,20 @@ def _get_dtype_type(arr_or_dtype):
elif isinstance(arr_or_dtype, CategoricalDtype):
return CategoricalDtypeType
elif isinstance(arr_or_dtype, DatetimeTZDtype):
- return DatetimeTZDtypeType
+ return Timestamp
elif isinstance(arr_or_dtype, IntervalDtype):
- return IntervalDtypeType
+ return Interval
elif isinstance(arr_or_dtype, PeriodDtype):
- return PeriodDtypeType
+ return Period
elif isinstance(arr_or_dtype, string_types):
if is_categorical_dtype(arr_or_dtype):
return CategoricalDtypeType
elif is_datetime64tz_dtype(arr_or_dtype):
- return DatetimeTZDtypeType
+ return Timestamp
elif is_period_dtype(arr_or_dtype):
- return PeriodDtypeType
+ return Period
elif is_interval_dtype(arr_or_dtype):
- return IntervalDtypeType
+ return Interval
return _get_dtype_type(np.dtype(arr_or_dtype))
try:
return arr_or_dtype.dtype.type
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index d879ded4f0f09..944365232db65 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -4,6 +4,8 @@
import numpy as np
from pandas import compat
from pandas.core.dtypes.generic import ABCIndexClass, ABCCategoricalIndex
+from pandas._libs.tslibs import Period, NaT, Timestamp
+from pandas._libs.interval import Interval
from .base import ExtensionDtype, _DtypeOpsMixin
@@ -469,13 +471,6 @@ def _is_boolean(self):
return is_bool_dtype(self.categories)
-class DatetimeTZDtypeType(type):
- """
- the type of DatetimeTZDtype, this metaclass determines subclass ability
- """
- pass
-
-
class DatetimeTZDtype(PandasExtensionDtype):
"""
@@ -485,7 +480,7 @@ class DatetimeTZDtype(PandasExtensionDtype):
THIS IS NOT A REAL NUMPY DTYPE, but essentially a sub-class of
np.datetime64[ns]
"""
- type = DatetimeTZDtypeType
+ type = Timestamp
kind = 'M'
str = '|M8[ns]'
num = 101
@@ -583,20 +578,13 @@ def __eq__(self, other):
str(self.tz) == str(other.tz))
-class PeriodDtypeType(type):
- """
- the type of PeriodDtype, this metaclass determines subclass ability
- """
- pass
-
-
class PeriodDtype(PandasExtensionDtype):
"""
A Period duck-typed class, suitable for holding a period with freq dtype.
THIS IS NOT A REAL NUMPY DTYPE, but essentially a sub-class of np.int64.
"""
- type = PeriodDtypeType
+ type = Period
kind = 'O'
str = '|O08'
base = np.dtype('O')
@@ -666,11 +654,15 @@ def construct_from_string(cls, string):
raise TypeError("could not construct PeriodDtype")
def __unicode__(self):
- return "period[{freq}]".format(freq=self.freq.freqstr)
+ return compat.text_type(self.name)
@property
def name(self):
- return str(self)
+ return str("period[{freq}]".format(freq=self.freq.freqstr))
+
+ @property
+ def na_value(self):
+ return NaT
def __hash__(self):
# make myself hashable
@@ -705,13 +697,6 @@ def is_dtype(cls, dtype):
return super(PeriodDtype, cls).is_dtype(dtype)
-class IntervalDtypeType(type):
- """
- the type of IntervalDtype, this metaclass determines subclass ability
- """
- pass
-
-
@register_extension_dtype
class IntervalDtype(PandasExtensionDtype, ExtensionDtype):
"""
@@ -800,7 +785,6 @@ def construct_from_string(cls, string):
@property
def type(self):
- from pandas import Interval
return Interval
def __unicode__(self):
diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py
index a7a9faa9e77eb..f87c51a4ee16b 100644
--- a/pandas/tests/dtypes/test_common.py
+++ b/pandas/tests/dtypes/test_common.py
@@ -605,15 +605,15 @@ def test__get_dtype_fails(input_param):
(pd.DatetimeIndex([1, 2]), np.datetime64),
(pd.DatetimeIndex([1, 2]).dtype, np.datetime64),
('<M8[ns]', np.datetime64),
- (pd.DatetimeIndex([1, 2], tz='Europe/London'), com.DatetimeTZDtypeType),
+ (pd.DatetimeIndex([1, 2], tz='Europe/London'), pd.Timestamp),
(pd.DatetimeIndex([1, 2], tz='Europe/London').dtype,
- com.DatetimeTZDtypeType),
- ('datetime64[ns, Europe/London]', com.DatetimeTZDtypeType),
+ pd.Timestamp),
+ ('datetime64[ns, Europe/London]', pd.Timestamp),
(pd.SparseSeries([1, 2], dtype='int32'), np.int32),
(pd.SparseSeries([1, 2], dtype='int32').dtype, np.int32),
- (PeriodDtype(freq='D'), com.PeriodDtypeType),
- ('period[D]', com.PeriodDtypeType),
- (IntervalDtype(), com.IntervalDtypeType),
+ (PeriodDtype(freq='D'), pd.Period),
+ ('period[D]', pd.Period),
+ (IntervalDtype(), pd.Interval),
(None, type(None)),
(1, type(None)),
(1.2, type(None)),
| Split from PeriodArray.
Updating the type to be the more correct `Period`.
Also removed the essentially unused `IntervalDtypeType`. If this doesn't break anything, it seems like there are decent chunks of `_get_dtype_type` that aren't being hit, aside from `test__get_dtype_type`.
| https://api.github.com/repos/pandas-dev/pandas/pulls/22938 | 2018-10-02T02:42:42Z | 2018-10-04T11:55:10Z | 2018-10-04T11:55:10Z | 2018-10-04T11:56:37Z |
DOC: fix DataFrame.sample doctests and reformat the docstring | diff --git a/ci/doctests.sh b/ci/doctests.sh
index b3d7f6785815a..16b3430f1e431 100755
--- a/ci/doctests.sh
+++ b/ci/doctests.sh
@@ -35,7 +35,7 @@ if [ "$DOCTEST" ]; then
fi
pytest --doctest-modules -v pandas/core/generic.py \
- -k"-_set_axis_name -_xs -describe -droplevel -groupby -interpolate -pct_change -pipe -reindex -reindex_axis -resample -sample -to_json -transpose -values -xs"
+ -k"-_set_axis_name -_xs -describe -droplevel -groupby -interpolate -pct_change -pipe -reindex -reindex_axis -resample -to_json -transpose -values -xs"
if [ $? -ne "0" ]; then
RET=1
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 393e7caae5fab..38555262885ec 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -4326,8 +4326,8 @@ def sample(self, n=None, frac=None, replace=False, weights=None,
Default = 1 if `frac` = None.
frac : float, optional
Fraction of axis items to return. Cannot be used with `n`.
- replace : boolean, optional
- Sample with or without replacement. Default = False.
+ replace : bool, default False
+ Sample with or without replacement.
weights : str or ndarray-like, optional
Default 'None' results in equal probability weighting.
If passed a Series, will align with target object on index. Index
@@ -4340,7 +4340,7 @@ def sample(self, n=None, frac=None, replace=False, weights=None,
being sampled.
If weights do not sum to 1, they will be normalized to sum to 1.
Missing values in the weights column will be treated as zero.
- inf and -inf values not allowed.
+ Infinite values not allowed.
random_state : int or numpy.random.RandomState, optional
Seed for the random number generator (if int), or numpy RandomState
object.
@@ -4350,58 +4350,52 @@ def sample(self, n=None, frac=None, replace=False, weights=None,
Returns
-------
- A new object of same type as caller.
+ Series or DataFrame
+ A new object of same type as caller containing `n` items randomly
+ sampled from the caller object.
- Examples
+ See Also
--------
- Generate an example ``Series`` and ``DataFrame``:
-
- >>> s = pd.Series(np.random.randn(50))
- >>> s.head()
- 0 -0.038497
- 1 1.820773
- 2 -0.972766
- 3 -1.598270
- 4 -1.095526
- dtype: float64
- >>> df = pd.DataFrame(np.random.randn(50, 4), columns=list('ABCD'))
- >>> df.head()
- A B C D
- 0 0.016443 -2.318952 -0.566372 -1.028078
- 1 -1.051921 0.438836 0.658280 -0.175797
- 2 -1.243569 -0.364626 -0.215065 0.057736
- 3 1.768216 0.404512 -0.385604 -1.457834
- 4 1.072446 -1.137172 0.314194 -0.046661
-
- Next extract a random sample from both of these objects...
+ numpy.random.choice: Generates a random sample from a given 1-D numpy
+ array.
- 3 random elements from the ``Series``:
-
- >>> s.sample(n=3)
- 27 -0.994689
- 55 -1.049016
- 67 -0.224565
- dtype: float64
-
- And a random 10% of the ``DataFrame`` with replacement:
-
- >>> df.sample(frac=0.1, replace=True)
- A B C D
- 35 1.981780 0.142106 1.817165 -0.290805
- 49 -1.336199 -0.448634 -0.789640 0.217116
- 40 0.823173 -0.078816 1.009536 1.015108
- 15 1.421154 -0.055301 -1.922594 -0.019696
- 6 -0.148339 0.832938 1.787600 -1.383767
-
- You can use `random state` for reproducibility:
-
- >>> df.sample(random_state=1)
- A B C D
- 37 -2.027662 0.103611 0.237496 -0.165867
- 43 -0.259323 -0.583426 1.516140 -0.479118
- 12 -1.686325 -0.579510 0.985195 -0.460286
- 8 1.167946 0.429082 1.215742 -1.636041
- 9 1.197475 -0.864188 1.554031 -1.505264
+ Examples
+ --------
+ >>> df = pd.DataFrame({'num_legs': [2, 4, 8, 0],
+ ... 'num_wings': [2, 0, 0, 0],
+ ... 'num_specimen_seen': [10, 2, 1, 8]},
+ ... index=['falcon', 'dog', 'spider', 'fish'])
+ >>> df
+ num_legs num_wings num_specimen_seen
+ falcon 2 2 10
+ dog 4 0 2
+ spider 8 0 1
+ fish 0 0 8
+
+ Extract 3 random elements from the ``Series`` ``df['num_legs']``:
+ Note that we use `random_state` to ensure the reproducibility of
+ the examples.
+
+ >>> df['num_legs'].sample(n=3, random_state=1)
+ fish 0
+ spider 8
+ falcon 2
+ Name: num_legs, dtype: int64
+
+ A random 50% sample of the ``DataFrame`` with replacement:
+
+ >>> df.sample(frac=0.5, replace=True, random_state=1)
+ num_legs num_wings num_specimen_seen
+ dog 4 0 2
+ fish 0 0 8
+
+ Using a DataFrame column as weights. Rows with larger value in the
+ `num_specimen_seen` column are more likely to be sampled.
+
+ >>> df.sample(n=2, weights='num_specimen_seen', random_state=1)
+ num_legs num_wings num_specimen_seen
+ falcon 2 2 10
+ fish 0 0 8
"""
if axis is None:
| - [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
Based on #22459. Fix the docstring for DataFrame.sample. I also updated `ci/doctests.sh`.
I was on the fence if I should remove mentions of `Panels` since it is deprecated. | https://api.github.com/repos/pandas-dev/pandas/pulls/22937 | 2018-10-02T02:29:06Z | 2018-10-08T04:31:21Z | 2018-10-08T04:31:21Z | 2018-10-09T14:39:27Z |
Catch Exception in combine | diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index 7bf13fb2fecc0..f7c4ee35adfe4 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -739,14 +739,22 @@ def _create_method(cls, op, coerce_to_dtype=True):
----------
op : function
An operator that takes arguments op(a, b)
- coerce_to_dtype : bool
+ coerce_to_dtype : bool, default True
boolean indicating whether to attempt to convert
- the result to the underlying ExtensionArray dtype
- (default True)
+ the result to the underlying ExtensionArray dtype.
+ If it's not possible to create a new ExtensionArray with the
+ values, an ndarray is returned instead.
Returns
-------
- A method that can be bound to a method of a class
+ Callable[[Any, Any], Union[ndarray, ExtensionArray]]
+ A method that can be bound to a class. When used, the method
+ receives the two arguments, one of which is the instance of
+ this class, and should return an ExtensionArray or an ndarray.
+
+ Returning an ndarray may be necessary when the result of the
+ `op` cannot be stored in the ExtensionArray. The dtype of the
+ ndarray uses NumPy's normal inference rules.
Example
-------
@@ -757,7 +765,6 @@ def _create_method(cls, op, coerce_to_dtype=True):
in the class definition of MyExtensionArray to create the operator
for addition, that will be based on the operator implementation
of the underlying elements of the ExtensionArray
-
"""
def _binop(self, other):
@@ -777,8 +784,13 @@ def convert_values(param):
if coerce_to_dtype:
try:
res = self._from_sequence(res)
- except TypeError:
- pass
+ except Exception:
+ # https://github.com/pandas-dev/pandas/issues/22850
+ # We catch all regular exceptions here, and fall back
+ # to an ndarray.
+ res = np.asarray(res)
+ else:
+ res = np.asarray(res)
return res
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 82198c2b3edd5..2e22e4e6e1bfc 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2323,10 +2323,14 @@ def combine(self, other, func, fill_value=None):
pass
elif is_extension_array_dtype(self.values):
# The function can return something of any type, so check
- # if the type is compatible with the calling EA
+ # if the type is compatible with the calling EA.
try:
new_values = self._values._from_sequence(new_values)
- except TypeError:
+ except Exception:
+ # https://github.com/pandas-dev/pandas/issues/22850
+ # pandas has no control over what 3rd-party ExtensionArrays
+ # do in _values_from_sequence. We still want ops to work
+ # though, so we catch any regular Exception.
pass
return self._constructor(new_values, index=new_index, name=new_name)
diff --git a/pandas/tests/extension/decimal/__init__.py b/pandas/tests/extension/decimal/__init__.py
index e69de29bb2d1d..c37aad0af8407 100644
--- a/pandas/tests/extension/decimal/__init__.py
+++ b/pandas/tests/extension/decimal/__init__.py
@@ -0,0 +1,4 @@
+from .array import DecimalArray, DecimalDtype, to_decimal, make_data
+
+
+__all__ = ['DecimalArray', 'DecimalDtype', 'to_decimal', 'make_data']
diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py
index 387942234e6fd..79e1a692f744a 100644
--- a/pandas/tests/extension/decimal/array.py
+++ b/pandas/tests/extension/decimal/array.py
@@ -1,5 +1,6 @@
import decimal
import numbers
+import random
import sys
import numpy as np
@@ -138,5 +139,13 @@ def _concat_same_type(cls, to_concat):
return cls(np.concatenate([x._data for x in to_concat]))
+def to_decimal(values, context=None):
+ return DecimalArray([decimal.Decimal(x) for x in values], context=context)
+
+
+def make_data():
+ return [decimal.Decimal(random.random()) for _ in range(100)]
+
+
DecimalArray._add_arithmetic_ops()
DecimalArray._add_comparison_ops()
diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py
index 93b8ea786ef5b..dd625d6e1eb3c 100644
--- a/pandas/tests/extension/decimal/test_decimal.py
+++ b/pandas/tests/extension/decimal/test_decimal.py
@@ -1,6 +1,6 @@
+import operator
import decimal
-import random
import numpy as np
import pandas as pd
import pandas.util.testing as tm
@@ -8,11 +8,7 @@
from pandas.tests.extension import base
-from .array import DecimalDtype, DecimalArray
-
-
-def make_data():
- return [decimal.Decimal(random.random()) for _ in range(100)]
+from .array import DecimalDtype, DecimalArray, make_data
@pytest.fixture
@@ -275,3 +271,47 @@ def test_compare_array(self, data, all_compare_operators):
other = pd.Series(data) * [decimal.Decimal(pow(2.0, i))
for i in alter]
self._compare_other(s, data, op_name, other)
+
+
+class DecimalArrayWithoutFromSequence(DecimalArray):
+ """Helper class for testing error handling in _from_sequence."""
+ def _from_sequence(cls, scalars, dtype=None, copy=False):
+ raise KeyError("For the test")
+
+
+class DecimalArrayWithoutCoercion(DecimalArrayWithoutFromSequence):
+ @classmethod
+ def _create_arithmetic_method(cls, op):
+ return cls._create_method(op, coerce_to_dtype=False)
+
+
+DecimalArrayWithoutCoercion._add_arithmetic_ops()
+
+
+def test_combine_from_sequence_raises():
+ # https://github.com/pandas-dev/pandas/issues/22850
+ ser = pd.Series(DecimalArrayWithoutFromSequence([
+ decimal.Decimal("1.0"),
+ decimal.Decimal("2.0")
+ ]))
+ result = ser.combine(ser, operator.add)
+
+ # note: object dtype
+ expected = pd.Series([decimal.Decimal("2.0"),
+ decimal.Decimal("4.0")], dtype="object")
+ tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize("class_", [DecimalArrayWithoutFromSequence,
+ DecimalArrayWithoutCoercion])
+def test_scalar_ops_from_sequence_raises(class_):
+ # op(EA, EA) should return an EA, or an ndarray if it's not possible
+ # to return an EA with the return values.
+ arr = class_([
+ decimal.Decimal("1.0"),
+ decimal.Decimal("2.0")
+ ])
+ result = arr + arr
+ expected = np.array([decimal.Decimal("2.0"), decimal.Decimal("4.0")],
+ dtype="object")
+ tm.assert_numpy_array_equal(result, expected)
diff --git a/pandas/tests/extension/json/__init__.py b/pandas/tests/extension/json/__init__.py
index e69de29bb2d1d..f2679d087c841 100644
--- a/pandas/tests/extension/json/__init__.py
+++ b/pandas/tests/extension/json/__init__.py
@@ -0,0 +1,3 @@
+from .array import JSONArray, JSONDtype, make_data
+
+__all__ = ['JSONArray', 'JSONDtype', 'make_data']
diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py
index 6ce0d63eb63ec..87876d84bef99 100644
--- a/pandas/tests/extension/json/array.py
+++ b/pandas/tests/extension/json/array.py
@@ -13,6 +13,8 @@
import collections
import itertools
import numbers
+import random
+import string
import sys
import numpy as np
@@ -179,3 +181,10 @@ def _values_for_argsort(self):
# cast them to an (N, P) array, instead of an (N,) array of tuples.
frozen = [()] + [tuple(x.items()) for x in self]
return np.array(frozen, dtype=object)[1:]
+
+
+def make_data():
+ # TODO: Use a regular dict. See _NDFrameIndexer._setitem_with_indexer
+ return [collections.UserDict([
+ (random.choice(string.ascii_letters), random.randint(0, 100))
+ for _ in range(random.randint(0, 10))]) for _ in range(100)]
diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py
index 93f10b7fbfc23..bcbc3e9109182 100644
--- a/pandas/tests/extension/json/test_json.py
+++ b/pandas/tests/extension/json/test_json.py
@@ -1,7 +1,5 @@
import operator
import collections
-import random
-import string
import pytest
@@ -10,18 +8,11 @@
from pandas.compat import PY2, PY36
from pandas.tests.extension import base
-from .array import JSONArray, JSONDtype
+from .array import JSONArray, JSONDtype, make_data
pytestmark = pytest.mark.skipif(PY2, reason="Py2 doesn't have a UserDict")
-def make_data():
- # TODO: Use a regular dict. See _NDFrameIndexer._setitem_with_indexer
- return [collections.UserDict([
- (random.choice(string.ascii_letters), random.randint(0, 100))
- for _ in range(random.randint(0, 10))]) for _ in range(100)]
-
-
@pytest.fixture
def dtype():
return JSONDtype()
| Closes https://github.com/pandas-dev/pandas/issues/22850 | https://api.github.com/repos/pandas-dev/pandas/pulls/22936 | 2018-10-02T02:27:06Z | 2018-10-04T11:27:55Z | 2018-10-04T11:27:55Z | 2018-10-04T11:32:54Z |
Provide default implementation for `data_repated` | diff --git a/pandas/tests/extension/conftest.py b/pandas/tests/extension/conftest.py
index 4bbbb7df2f399..8e397d228a5b6 100644
--- a/pandas/tests/extension/conftest.py
+++ b/pandas/tests/extension/conftest.py
@@ -31,12 +31,24 @@ def all_data(request, data, data_missing):
@pytest.fixture
-def data_repeated():
- """Return different versions of data for count times"""
+def data_repeated(data):
+ """
+ Generate many datasets.
+
+ Parameters
+ ----------
+ data : fixture implementing `data`
+
+ Returns
+ -------
+ Callable[[int], Generator]:
+ A callable that takes a `count` argument and
+ returns a generator yielding `count` datasets.
+ """
def gen(count):
for _ in range(count):
- yield NotImplementedError
- yield gen
+ yield data
+ return gen
@pytest.fixture
diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py
index 03fdd25826b79..93b8ea786ef5b 100644
--- a/pandas/tests/extension/decimal/test_decimal.py
+++ b/pandas/tests/extension/decimal/test_decimal.py
@@ -30,14 +30,6 @@ def data_missing():
return DecimalArray([decimal.Decimal('NaN'), decimal.Decimal(1)])
-@pytest.fixture
-def data_repeated():
- def gen(count):
- for _ in range(count):
- yield DecimalArray(make_data())
- yield gen
-
-
@pytest.fixture
def data_for_sorting():
return DecimalArray([decimal.Decimal('1'),
diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py
index 6c6cf80c16da6..ff66f53eab6f6 100644
--- a/pandas/tests/extension/test_categorical.py
+++ b/pandas/tests/extension/test_categorical.py
@@ -45,15 +45,6 @@ def data_missing():
return Categorical([np.nan, 'A'])
-@pytest.fixture
-def data_repeated():
- """Return different versions of data for count times"""
- def gen(count):
- for _ in range(count):
- yield Categorical(make_data())
- yield gen
-
-
@pytest.fixture
def data_for_sorting():
return Categorical(['A', 'B', 'C'], categories=['C', 'A', 'B'],
diff --git a/pandas/tests/extension/test_integer.py b/pandas/tests/extension/test_integer.py
index 57e0922a0b7d9..7aa33006dadda 100644
--- a/pandas/tests/extension/test_integer.py
+++ b/pandas/tests/extension/test_integer.py
@@ -47,14 +47,6 @@ def data_missing(dtype):
return integer_array([np.nan, 1], dtype=dtype)
-@pytest.fixture
-def data_repeated(data):
- def gen(count):
- for _ in range(count):
- yield data
- yield gen
-
-
@pytest.fixture
def data_for_sorting(dtype):
return integer_array([1, 2, 0], dtype=dtype)
diff --git a/pandas/tests/extension/test_interval.py b/pandas/tests/extension/test_interval.py
index 34b98f590df0d..7302c5757d144 100644
--- a/pandas/tests/extension/test_interval.py
+++ b/pandas/tests/extension/test_interval.py
@@ -47,15 +47,6 @@ def data_missing():
return IntervalArray.from_tuples([None, (0, 1)])
-@pytest.fixture
-def data_repeated():
- """Return different versions of data for count times"""
- def gen(count):
- for _ in range(count):
- yield IntervalArray(make_data())
- yield gen
-
-
@pytest.fixture
def data_for_sorting():
return IntervalArray.from_tuples([(1, 2), (2, 3), (0, 1)])
| Split from PeriodArray.
The previous implementation was not great, since failing to override it would result in `Series([NotImplementedError, NotImplementedError...])`. We could raise instead, forcing downstream arrays to implement it, or just repeat `data`. I opted for the latter, which integer_array was already doing. | https://api.github.com/repos/pandas-dev/pandas/pulls/22935 | 2018-10-02T02:15:30Z | 2018-10-02T13:50:42Z | 2018-10-02T13:50:42Z | 2018-10-02T13:50:45Z |
BUG: divmod return type | diff --git a/doc/source/extending.rst b/doc/source/extending.rst
index 9422434a1d998..ab940384594bc 100644
--- a/doc/source/extending.rst
+++ b/doc/source/extending.rst
@@ -160,9 +160,18 @@ your ``MyExtensionArray`` class, as follows:
MyExtensionArray._add_arithmetic_ops()
MyExtensionArray._add_comparison_ops()
-Note that since ``pandas`` automatically calls the underlying operator on each
-element one-by-one, this might not be as performant as implementing your own
-version of the associated operators directly on the ``ExtensionArray``.
+
+.. note::
+
+ Since ``pandas`` automatically calls the underlying operator on each
+ element one-by-one, this might not be as performant as implementing your own
+ version of the associated operators directly on the ``ExtensionArray``.
+
+For arithmetic operations, this implementation will try to reconstruct a new
+``ExtensionArray`` with the result of the element-wise operation. Whether
+or not that succeeds depends on whether the operation returns a result
+that's valid for the ``ExtensionArray``. If an ``ExtensionArray`` cannot
+be reconstructed, an ndarray containing the scalars returned instead.
.. _extending.extension.testing:
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index f7c4ee35adfe4..efe587c6aaaad 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -781,17 +781,24 @@ def convert_values(param):
# a TypeError should be raised
res = [op(a, b) for (a, b) in zip(lvalues, rvalues)]
- if coerce_to_dtype:
- try:
- res = self._from_sequence(res)
- except Exception:
+ def _maybe_convert(arr):
+ if coerce_to_dtype:
# https://github.com/pandas-dev/pandas/issues/22850
# We catch all regular exceptions here, and fall back
# to an ndarray.
- res = np.asarray(res)
+ try:
+ res = self._from_sequence(arr)
+ except Exception:
+ res = np.asarray(arr)
+ else:
+ res = np.asarray(arr)
+ return res
+
+ if op.__name__ in {'divmod', 'rdivmod'}:
+ a, b = zip(*res)
+ res = _maybe_convert(a), _maybe_convert(b)
else:
- res = np.asarray(res)
-
+ res = _maybe_convert(res)
return res
op_name = ops._get_op_name(op, True)
diff --git a/pandas/tests/extension/base/ops.py b/pandas/tests/extension/base/ops.py
index ee4a92146128b..36696bc292162 100644
--- a/pandas/tests/extension/base/ops.py
+++ b/pandas/tests/extension/base/ops.py
@@ -58,7 +58,8 @@ def test_arith_series_with_scalar(self, data, all_arithmetic_operators):
s = pd.Series(data)
self.check_opname(s, op_name, s.iloc[0], exc=TypeError)
- @pytest.mark.xfail(run=False, reason="_reduce needs implementation")
+ @pytest.mark.xfail(run=False, reason="_reduce needs implementation",
+ strict=True)
def test_arith_frame_with_scalar(self, data, all_arithmetic_operators):
# frame & scalar
op_name = all_arithmetic_operators
@@ -77,6 +78,10 @@ def test_divmod(self, data):
self._check_divmod_op(s, divmod, 1, exc=TypeError)
self._check_divmod_op(1, ops.rdivmod, s, exc=TypeError)
+ def test_divmod_series_array(self, data):
+ s = pd.Series(data)
+ self._check_divmod_op(s, divmod, data)
+
def test_add_series_with_extension_array(self, data):
s = pd.Series(data)
result = s + data
diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py
index dd625d6e1eb3c..6488c7724229b 100644
--- a/pandas/tests/extension/decimal/test_decimal.py
+++ b/pandas/tests/extension/decimal/test_decimal.py
@@ -8,7 +8,7 @@
from pandas.tests.extension import base
-from .array import DecimalDtype, DecimalArray, make_data
+from .array import DecimalDtype, DecimalArray, make_data, to_decimal
@pytest.fixture
@@ -102,7 +102,7 @@ class TestInterface(BaseDecimal, base.BaseInterfaceTests):
class TestConstructors(BaseDecimal, base.BaseConstructorsTests):
- @pytest.mark.xfail(reason="not implemented constructor from dtype")
+ @pytest.mark.skip(reason="not implemented constructor from dtype")
def test_from_dtype(self, data):
# construct from our dtype & string dtype
pass
@@ -240,9 +240,11 @@ def test_arith_series_with_array(self, data, all_arithmetic_operators):
context.traps[decimal.DivisionByZero] = divbyzerotrap
context.traps[decimal.InvalidOperation] = invalidoptrap
- @pytest.mark.skip(reason="divmod not appropriate for decimal")
- def test_divmod(self, data):
- pass
+ def _check_divmod_op(self, s, op, other, exc=NotImplementedError):
+ # We implement divmod
+ super(TestArithmeticOps, self)._check_divmod_op(
+ s, op, other, exc=None
+ )
def test_error(self):
pass
@@ -315,3 +317,21 @@ def test_scalar_ops_from_sequence_raises(class_):
expected = np.array([decimal.Decimal("2.0"), decimal.Decimal("4.0")],
dtype="object")
tm.assert_numpy_array_equal(result, expected)
+
+
+@pytest.mark.parametrize("reverse, expected_div, expected_mod", [
+ (False, [0, 1, 1, 2], [1, 0, 1, 0]),
+ (True, [2, 1, 0, 0], [0, 0, 2, 2]),
+])
+def test_divmod_array(reverse, expected_div, expected_mod):
+ # https://github.com/pandas-dev/pandas/issues/22930
+ arr = to_decimal([1, 2, 3, 4])
+ if reverse:
+ div, mod = divmod(2, arr)
+ else:
+ div, mod = divmod(arr, 2)
+ expected_div = to_decimal(expected_div)
+ expected_mod = to_decimal(expected_mod)
+
+ tm.assert_extension_array_equal(div, expected_div)
+ tm.assert_extension_array_equal(mod, expected_mod)
diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py
index bcbc3e9109182..115afdcc99f2b 100644
--- a/pandas/tests/extension/json/test_json.py
+++ b/pandas/tests/extension/json/test_json.py
@@ -131,8 +131,7 @@ def test_custom_asserts(self):
class TestConstructors(BaseJSON, base.BaseConstructorsTests):
- # TODO: Should this be pytest.mark.skip?
- @pytest.mark.xfail(reason="not implemented constructor from dtype")
+ @pytest.mark.skip(reason="not implemented constructor from dtype")
def test_from_dtype(self, data):
# construct from our dtype & string dtype
pass
@@ -147,13 +146,11 @@ class TestGetitem(BaseJSON, base.BaseGetitemTests):
class TestMissing(BaseJSON, base.BaseMissingTests):
- # TODO: Should this be pytest.mark.skip?
- @pytest.mark.xfail(reason="Setting a dict as a scalar")
+ @pytest.mark.skip(reason="Setting a dict as a scalar")
def test_fillna_series(self):
"""We treat dictionaries as a mapping in fillna, not a scalar."""
- # TODO: Should this be pytest.mark.skip?
- @pytest.mark.xfail(reason="Setting a dict as a scalar")
+ @pytest.mark.skip(reason="Setting a dict as a scalar")
def test_fillna_frame(self):
"""We treat dictionaries as a mapping in fillna, not a scalar."""
@@ -204,8 +201,7 @@ def test_combine_add(self, data_repeated):
class TestCasting(BaseJSON, base.BaseCastingTests):
- # TODO: Should this be pytest.mark.skip?
- @pytest.mark.xfail(reason="failing on np.array(self, dtype=str)")
+ @pytest.mark.skip(reason="failing on np.array(self, dtype=str)")
def test_astype_str(self):
"""This currently fails in NumPy on np.array(self, dtype=str) with
@@ -257,6 +253,11 @@ def test_add_series_with_extension_array(self, data):
with tm.assert_raises_regex(TypeError, "unsupported"):
ser + data
+ def _check_divmod_op(self, s, op, other, exc=NotImplementedError):
+ return super(TestArithmeticOps, self)._check_divmod_op(
+ s, op, other, exc=TypeError
+ )
+
class TestComparisonOps(BaseJSON, base.BaseComparisonOpsTests):
pass
diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py
index c588552572aed..f118279c4b915 100644
--- a/pandas/tests/extension/test_categorical.py
+++ b/pandas/tests/extension/test_categorical.py
@@ -140,11 +140,11 @@ def test_take_series(self):
def test_reindex_non_na_fill_value(self):
pass
- @pytest.mark.xfail(reason="Categorical.take buggy")
+ @pytest.mark.skip(reason="Categorical.take buggy")
def test_take_empty(self):
pass
- @pytest.mark.xfail(reason="test not written correctly for categorical")
+ @pytest.mark.skip(reason="test not written correctly for categorical")
def test_reindex(self):
pass
@@ -208,6 +208,11 @@ def test_add_series_with_extension_array(self, data):
with tm.assert_raises_regex(TypeError, "cannot perform"):
ser + data
+ def _check_divmod_op(self, s, op, other, exc=NotImplementedError):
+ return super(TestArithmeticOps, self)._check_divmod_op(
+ s, op, other, exc=TypeError
+ )
+
class TestComparisonOps(base.BaseComparisonOpsTests):
| Closes https://github.com/pandas-dev/pandas/issues/22930 | https://api.github.com/repos/pandas-dev/pandas/pulls/22932 | 2018-10-01T21:52:22Z | 2018-10-08T13:53:06Z | 2018-10-08T13:53:06Z | 2018-10-08T13:56:57Z |
TST/CLN: Fixturize tests/frame/test_block_internals.py | diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py
index 3fe1c84174acb..5f1d4954521ed 100644
--- a/pandas/tests/frame/test_block_internals.py
+++ b/pandas/tests/frame/test_block_internals.py
@@ -22,27 +22,25 @@
import pandas.util.testing as tm
-from pandas.tests.frame.common import TestData
-
# Segregated collection of methods that require the BlockManager internal data
# structure
-class TestDataFrameBlockInternals(TestData):
+class TestDataFrameBlockInternals():
- def test_cast_internals(self):
- casted = DataFrame(self.frame._data, dtype=int)
- expected = DataFrame(self.frame._series, dtype=int)
+ def test_cast_internals(self, float_frame):
+ casted = DataFrame(float_frame._data, dtype=int)
+ expected = DataFrame(float_frame._series, dtype=int)
assert_frame_equal(casted, expected)
- casted = DataFrame(self.frame._data, dtype=np.int32)
- expected = DataFrame(self.frame._series, dtype=np.int32)
+ casted = DataFrame(float_frame._data, dtype=np.int32)
+ expected = DataFrame(float_frame._series, dtype=np.int32)
assert_frame_equal(casted, expected)
- def test_consolidate(self):
- self.frame['E'] = 7.
- consolidated = self.frame._consolidate()
+ def test_consolidate(self, float_frame):
+ float_frame['E'] = 7.
+ consolidated = float_frame._consolidate()
assert len(consolidated._data.blocks) == 1
# Ensure copy, do I want this?
@@ -50,92 +48,92 @@ def test_consolidate(self):
assert recons is not consolidated
tm.assert_frame_equal(recons, consolidated)
- self.frame['F'] = 8.
- assert len(self.frame._data.blocks) == 3
+ float_frame['F'] = 8.
+ assert len(float_frame._data.blocks) == 3
- self.frame._consolidate(inplace=True)
- assert len(self.frame._data.blocks) == 1
+ float_frame._consolidate(inplace=True)
+ assert len(float_frame._data.blocks) == 1
- def test_consolidate_deprecation(self):
- self.frame['E'] = 7
+ def test_consolidate_deprecation(self, float_frame):
+ float_frame['E'] = 7
with tm.assert_produces_warning(FutureWarning):
- self.frame.consolidate()
+ float_frame.consolidate()
- def test_consolidate_inplace(self):
- frame = self.frame.copy() # noqa
+ def test_consolidate_inplace(self, float_frame):
+ frame = float_frame.copy() # noqa
# triggers in-place consolidation
for letter in range(ord('A'), ord('Z')):
- self.frame[chr(letter)] = chr(letter)
+ float_frame[chr(letter)] = chr(letter)
- def test_values_consolidate(self):
- self.frame['E'] = 7.
- assert not self.frame._data.is_consolidated()
- _ = self.frame.values # noqa
- assert self.frame._data.is_consolidated()
+ def test_values_consolidate(self, float_frame):
+ float_frame['E'] = 7.
+ assert not float_frame._data.is_consolidated()
+ _ = float_frame.values # noqa
+ assert float_frame._data.is_consolidated()
- def test_modify_values(self):
- self.frame.values[5] = 5
- assert (self.frame.values[5] == 5).all()
+ def test_modify_values(self, float_frame):
+ float_frame.values[5] = 5
+ assert (float_frame.values[5] == 5).all()
# unconsolidated
- self.frame['E'] = 7.
- self.frame.values[6] = 6
- assert (self.frame.values[6] == 6).all()
+ float_frame['E'] = 7.
+ float_frame.values[6] = 6
+ assert (float_frame.values[6] == 6).all()
- def test_boolean_set_uncons(self):
- self.frame['E'] = 7.
+ def test_boolean_set_uncons(self, float_frame):
+ float_frame['E'] = 7.
- expected = self.frame.values.copy()
+ expected = float_frame.values.copy()
expected[expected > 1] = 2
- self.frame[self.frame > 1] = 2
- assert_almost_equal(expected, self.frame.values)
+ float_frame[float_frame > 1] = 2
+ assert_almost_equal(expected, float_frame.values)
- def test_values_numeric_cols(self):
- self.frame['foo'] = 'bar'
+ def test_values_numeric_cols(self, float_frame):
+ float_frame['foo'] = 'bar'
- values = self.frame[['A', 'B', 'C', 'D']].values
+ values = float_frame[['A', 'B', 'C', 'D']].values
assert values.dtype == np.float64
- def test_values_lcd(self):
+ def test_values_lcd(self, mixed_float_frame, mixed_int_frame):
# mixed lcd
- values = self.mixed_float[['A', 'B', 'C', 'D']].values
+ values = mixed_float_frame[['A', 'B', 'C', 'D']].values
assert values.dtype == np.float64
- values = self.mixed_float[['A', 'B', 'C']].values
+ values = mixed_float_frame[['A', 'B', 'C']].values
assert values.dtype == np.float32
- values = self.mixed_float[['C']].values
+ values = mixed_float_frame[['C']].values
assert values.dtype == np.float16
# GH 10364
# B uint64 forces float because there are other signed int types
- values = self.mixed_int[['A', 'B', 'C', 'D']].values
+ values = mixed_int_frame[['A', 'B', 'C', 'D']].values
assert values.dtype == np.float64
- values = self.mixed_int[['A', 'D']].values
+ values = mixed_int_frame[['A', 'D']].values
assert values.dtype == np.int64
# B uint64 forces float because there are other signed int types
- values = self.mixed_int[['A', 'B', 'C']].values
+ values = mixed_int_frame[['A', 'B', 'C']].values
assert values.dtype == np.float64
# as B and C are both unsigned, no forcing to float is needed
- values = self.mixed_int[['B', 'C']].values
+ values = mixed_int_frame[['B', 'C']].values
assert values.dtype == np.uint64
- values = self.mixed_int[['A', 'C']].values
+ values = mixed_int_frame[['A', 'C']].values
assert values.dtype == np.int32
- values = self.mixed_int[['C', 'D']].values
+ values = mixed_int_frame[['C', 'D']].values
assert values.dtype == np.int64
- values = self.mixed_int[['A']].values
+ values = mixed_int_frame[['A']].values
assert values.dtype == np.int32
- values = self.mixed_int[['C']].values
+ values = mixed_int_frame[['C']].values
assert values.dtype == np.uint8
def test_constructor_with_convert(self):
@@ -205,7 +203,7 @@ def test_constructor_with_convert(self):
None], np.object_), name='A')
assert_series_equal(result, expected)
- def test_construction_with_mixed(self):
+ def test_construction_with_mixed(self, float_string_frame):
# test construction edge cases with mixed types
# f7u12, this does not work without extensive workaround
@@ -219,11 +217,11 @@ def test_construction_with_mixed(self):
expected = Series({'datetime64[ns]': 3})
# mixed-type frames
- self.mixed_frame['datetime'] = datetime.now()
- self.mixed_frame['timedelta'] = timedelta(days=1, seconds=1)
- assert self.mixed_frame['datetime'].dtype == 'M8[ns]'
- assert self.mixed_frame['timedelta'].dtype == 'm8[ns]'
- result = self.mixed_frame.get_dtype_counts().sort_values()
+ float_string_frame['datetime'] = datetime.now()
+ float_string_frame['timedelta'] = timedelta(days=1, seconds=1)
+ assert float_string_frame['datetime'].dtype == 'M8[ns]'
+ assert float_string_frame['timedelta'].dtype == 'm8[ns]'
+ result = float_string_frame.get_dtype_counts().sort_values()
expected = Series({'float64': 4,
'object': 1,
'datetime64[ns]': 1,
@@ -296,9 +294,9 @@ def test_equals_different_blocks(self):
assert df0.equals(df1)
assert df1.equals(df0)
- def test_copy_blocks(self):
+ def test_copy_blocks(self, float_frame):
# API/ENH 9607
- df = DataFrame(self.frame, copy=True)
+ df = DataFrame(float_frame, copy=True)
column = df.columns[0]
# use the default copy=True, change a column
@@ -314,9 +312,9 @@ def test_copy_blocks(self):
# make sure we did not change the original DataFrame
assert not _df[column].equals(df[column])
- def test_no_copy_blocks(self):
+ def test_no_copy_blocks(self, float_frame):
# API/ENH 9607
- df = DataFrame(self.frame, copy=True)
+ df = DataFrame(float_frame, copy=True)
column = df.columns[0]
# use the copy=False, change a column
@@ -332,29 +330,29 @@ def test_no_copy_blocks(self):
# make sure we did change the original DataFrame
assert _df[column].equals(df[column])
- def test_copy(self):
- cop = self.frame.copy()
+ def test_copy(self, float_frame, float_string_frame):
+ cop = float_frame.copy()
cop['E'] = cop['A']
- assert 'E' not in self.frame
+ assert 'E' not in float_frame
# copy objects
- copy = self.mixed_frame.copy()
- assert copy._data is not self.mixed_frame._data
+ copy = float_string_frame.copy()
+ assert copy._data is not float_string_frame._data
- def test_pickle(self):
- unpickled = tm.round_trip_pickle(self.mixed_frame)
- assert_frame_equal(self.mixed_frame, unpickled)
+ def test_pickle(self, float_string_frame, empty_frame, timezone_frame):
+ unpickled = tm.round_trip_pickle(float_string_frame)
+ assert_frame_equal(float_string_frame, unpickled)
# buglet
- self.mixed_frame._data.ndim
+ float_string_frame._data.ndim
# empty
- unpickled = tm.round_trip_pickle(self.empty)
+ unpickled = tm.round_trip_pickle(empty_frame)
repr(unpickled)
# tz frame
- unpickled = tm.round_trip_pickle(self.tzframe)
- assert_frame_equal(self.tzframe, unpickled)
+ unpickled = tm.round_trip_pickle(timezone_frame)
+ assert_frame_equal(timezone_frame, unpickled)
def test_consolidate_datetime64(self):
# numpy vstack bug
@@ -388,9 +386,9 @@ def test_consolidate_datetime64(self):
df.starting), ser_starting.index)
tm.assert_index_equal(pd.DatetimeIndex(df.ending), ser_ending.index)
- def test_is_mixed_type(self):
- assert not self.frame._is_mixed_type
- assert self.mixed_frame._is_mixed_type
+ def test_is_mixed_type(self, float_frame, float_string_frame):
+ assert not float_frame._is_mixed_type
+ assert float_string_frame._is_mixed_type
def test_get_numeric_data(self):
# TODO(wesm): unused?
@@ -448,23 +446,23 @@ def test_get_numeric_data_extension_dtype(self):
expected = df.loc[:, ['A', 'C']]
assert_frame_equal(result, expected)
- def test_convert_objects(self):
+ def test_convert_objects(self, float_string_frame):
- oops = self.mixed_frame.T.T
+ oops = float_string_frame.T.T
converted = oops._convert(datetime=True)
- assert_frame_equal(converted, self.mixed_frame)
+ assert_frame_equal(converted, float_string_frame)
assert converted['A'].dtype == np.float64
# force numeric conversion
- self.mixed_frame['H'] = '1.'
- self.mixed_frame['I'] = '1'
+ float_string_frame['H'] = '1.'
+ float_string_frame['I'] = '1'
# add in some items that will be nan
- length = len(self.mixed_frame)
- self.mixed_frame['J'] = '1.'
- self.mixed_frame['K'] = '1'
- self.mixed_frame.loc[0:5, ['J', 'K']] = 'garbled'
- converted = self.mixed_frame._convert(datetime=True, numeric=True)
+ length = len(float_string_frame)
+ float_string_frame['J'] = '1.'
+ float_string_frame['K'] = '1'
+ float_string_frame.loc[0:5, ['J', 'K']] = 'garbled'
+ converted = float_string_frame._convert(datetime=True, numeric=True)
assert converted['H'].dtype == 'float64'
assert converted['I'].dtype == 'int64'
assert converted['J'].dtype == 'float64'
@@ -473,14 +471,14 @@ def test_convert_objects(self):
assert len(converted['K'].dropna()) == length - 5
# via astype
- converted = self.mixed_frame.copy()
+ converted = float_string_frame.copy()
converted['H'] = converted['H'].astype('float64')
converted['I'] = converted['I'].astype('int64')
assert converted['H'].dtype == 'float64'
assert converted['I'].dtype == 'int64'
# via astype, but errors
- converted = self.mixed_frame.copy()
+ converted = float_string_frame.copy()
with tm.assert_raises_regex(ValueError, 'invalid literal'):
converted['H'].astype('int32')
| - [ ] Following h-vetinari's footstep (#22471 ), "translate" one of the test file
- [ ] tests added / passed
| https://api.github.com/repos/pandas-dev/pandas/pulls/22926 | 2018-10-01T14:38:40Z | 2018-10-14T17:18:26Z | 2018-10-14T17:18:26Z | 2018-10-14T17:18:40Z |
DOC GH22893 Fix docstring of groupby in pandas/core/generic.py | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 393e7caae5fab..5b4ce5a382324 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -7063,8 +7063,12 @@ def clip_lower(self, threshold, axis=None, inplace=False):
def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,
group_keys=True, squeeze=False, observed=False, **kwargs):
"""
- Group series using mapper (dict or key function, apply given function
- to group, return result as series) or by a series of columns.
+ Group DataFrame or Series using a mapper or by a Series of columns.
+
+ A groupby operation involves some combination of splitting the
+ object, applying a function, and combining the results. This can be
+ used to group large amounts of data and compute operations on these
+ groups.
Parameters
----------
@@ -7077,54 +7081,95 @@ def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,
values are used as-is determine the groups. A label or list of
labels may be passed to group by the columns in ``self``. Notice
that a tuple is interpreted a (single) key.
- axis : int, default 0
+ axis : {0 or 'index', 1 or 'columns'}, default 0
+ Split along rows (0) or columns (1).
level : int, level name, or sequence of such, default None
If the axis is a MultiIndex (hierarchical), group by a particular
- level or levels
- as_index : boolean, default True
+ level or levels.
+ as_index : bool, default True
For aggregated output, return object with group labels as the
index. Only relevant for DataFrame input. as_index=False is
- effectively "SQL-style" grouped output
- sort : boolean, default True
+ effectively "SQL-style" grouped output.
+ sort : bool, default True
Sort group keys. Get better performance by turning this off.
Note this does not influence the order of observations within each
- group. groupby preserves the order of rows within each group.
- group_keys : boolean, default True
- When calling apply, add group keys to index to identify pieces
- squeeze : boolean, default False
- reduce the dimensionality of the return type if possible,
- otherwise return a consistent type
- observed : boolean, default False
- This only applies if any of the groupers are Categoricals
+ group. Groupby preserves the order of rows within each group.
+ group_keys : bool, default True
+ When calling apply, add group keys to index to identify pieces.
+ squeeze : bool, default False
+ Reduce the dimensionality of the return type if possible,
+ otherwise return a consistent type.
+ observed : bool, default False
+ This only applies if any of the groupers are Categoricals.
If True: only show observed values for categorical groupers.
If False: show all values for categorical groupers.
.. versionadded:: 0.23.0
+ **kwargs
+ Optional, only accepts keyword argument 'mutated' and is passed
+ to groupby.
+
Returns
-------
- GroupBy object
+ DataFrameGroupBy or SeriesGroupBy
+ Depends on the calling object and returns groupby object that
+ contains information about the groups.
- Examples
+ See Also
--------
- DataFrame results
-
- >>> data.groupby(func, axis=0).mean()
- >>> data.groupby(['col1', 'col2'])['col3'].mean()
-
- DataFrame with hierarchical index
-
- >>> data.groupby(['col1', 'col2']).mean()
+ resample : Convenience method for frequency conversion and resampling
+ of time series.
Notes
-----
See the `user guide
<http://pandas.pydata.org/pandas-docs/stable/groupby.html>`_ for more.
- See also
+ Examples
--------
- resample : Convenience method for frequency conversion and resampling
- of time series.
+ >>> df = pd.DataFrame({'Animal' : ['Falcon', 'Falcon',
+ ... 'Parrot', 'Parrot'],
+ ... 'Max Speed' : [380., 370., 24., 26.]})
+ >>> df
+ Animal Max Speed
+ 0 Falcon 380.0
+ 1 Falcon 370.0
+ 2 Parrot 24.0
+ 3 Parrot 26.0
+ >>> df.groupby(['Animal']).mean()
+ Max Speed
+ Animal
+ Falcon 375.0
+ Parrot 25.0
+
+ **Hierarchical Indexes**
+
+ We can groupby different levels of a hierarchical index
+ using the `level` parameter:
+
+ >>> arrays = [['Falcon', 'Falcon', 'Parrot', 'Parrot'],
+ ... ['Capitve', 'Wild', 'Capitve', 'Wild']]
+ >>> index = pd.MultiIndex.from_arrays(arrays, names=('Animal', 'Type'))
+ >>> df = pd.DataFrame({'Max Speed' : [390., 350., 30., 20.]},
+ ... index=index)
+ >>> df
+ Max Speed
+ Animal Type
+ Falcon Capitve 390.0
+ Wild 350.0
+ Parrot Capitve 30.0
+ Wild 20.0
+ >>> df.groupby(level=0).mean()
+ Max Speed
+ Animal
+ Falcon 370.0
+ Parrot 25.0
+ >>> df.groupby(level=1).mean()
+ Max Speed
+ Type
+ Capitve 210.0
+ Wild 185.0
"""
from pandas.core.groupby.groupby import groupby
| - [x] closes #22893
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
Updated docstring following https://pandas.pydata.org/pandas-docs/stable/contributing_docstring.html
I changed the examples into similar ones that I thought better demonstrated the function, but I'm willing to change them again if they aren't up to par.
I also might need some help describing the kwargs. It only accepts 'mutated' as a keyword argument and I can't tell if it does anything. Apologies if the answer is obvious!
| https://api.github.com/repos/pandas-dev/pandas/pulls/22920 | 2018-10-01T07:18:21Z | 2018-10-03T00:01:09Z | 2018-10-03T00:01:08Z | 2018-10-03T00:01:15Z |
CLN GH22874 replace bare excepts in pandas/io/pytables.py | diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index c57b1c3e211f6..fc9e415ed38f7 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -258,7 +258,7 @@ def _tables():
try:
_table_file_open_policy_is_strict = (
tables.file._FILE_OPEN_POLICY == 'strict')
- except:
+ except AttributeError:
pass
return _table_mod
@@ -395,11 +395,11 @@ def read_hdf(path_or_buf, key=None, mode='r', **kwargs):
'contains multiple datasets.')
key = candidate_only_group._v_pathname
return store.select(key, auto_close=auto_close, **kwargs)
- except:
+ except (ValueError, TypeError):
# if there is an error, close the store
try:
store.close()
- except:
+ except AttributeError:
pass
raise
@@ -517,7 +517,7 @@ def __getattr__(self, name):
""" allow attribute access to get stores """
try:
return self.get(name)
- except:
+ except (KeyError, ClosedFileError):
pass
raise AttributeError("'%s' object has no attribute '%s'" %
(type(self).__name__, name))
@@ -675,7 +675,7 @@ def flush(self, fsync=False):
if fsync:
try:
os.fsync(self._handle.fileno())
- except:
+ except OSError:
pass
def get(self, key):
@@ -1161,7 +1161,7 @@ def get_node(self, key):
if not key.startswith('/'):
key = '/' + key
return self._handle.get_node(self.root, key)
- except:
+ except _table_mod.exceptions.NoSuchNodeError:
return None
def get_storer(self, key):
@@ -1270,7 +1270,7 @@ def _validate_format(self, format, kwargs):
# validate
try:
kwargs['format'] = _FORMAT_MAP[format.lower()]
- except:
+ except KeyError:
raise TypeError("invalid HDFStore format specified [{0}]"
.format(format))
@@ -1307,7 +1307,7 @@ def error(t):
try:
pt = _TYPE_MAP[type(value)]
- except:
+ except KeyError:
error('_TYPE_MAP')
# we are actually a table
@@ -1318,7 +1318,7 @@ def error(t):
if u('table') not in pt:
try:
return globals()[_STORER_MAP[pt]](self, group, **kwargs)
- except:
+ except KeyError:
error('_STORER_MAP')
# existing node (and must be a table)
@@ -1354,12 +1354,12 @@ def error(t):
fields = group.table._v_attrs.fields
if len(fields) == 1 and fields[0] == u('value'):
tt = u('legacy_frame')
- except:
+ except IndexError:
pass
try:
return globals()[_TABLE_MAP[tt]](self, group, **kwargs)
- except:
+ except KeyError:
error('_TABLE_MAP')
def _write_to_group(self, key, value, format, index=True, append=False,
@@ -1624,7 +1624,7 @@ def is_indexed(self):
""" return whether I am an indexed column """
try:
return getattr(self.table.cols, self.cname).is_indexed
- except:
+ except AttributeError:
False
def copy(self):
@@ -1654,9 +1654,10 @@ def convert(self, values, nan_rep, encoding, errors):
kwargs['freq'] = _ensure_decoded(self.freq)
if self.index_name is not None:
kwargs['name'] = _ensure_decoded(self.index_name)
+ # making an Index instance could throw a number of different errors
try:
self.values = Index(values, **kwargs)
- except:
+ except Exception: # noqa: E722
# if the output freq is different that what we recorded,
# it should be None (see also 'doc example part 2')
@@ -1869,7 +1870,7 @@ def create_for_block(
m = re.search(r"values_block_(\d+)", name)
if m:
name = "values_%s" % m.groups()[0]
- except:
+ except IndexError:
pass
return cls(name=name, cname=cname, **kwargs)
@@ -2232,7 +2233,7 @@ def convert(self, values, nan_rep, encoding, errors):
try:
self.data = self.data.astype(dtype, copy=False)
- except:
+ except TypeError:
self.data = self.data.astype('O', copy=False)
# convert nans / decode
@@ -2325,7 +2326,7 @@ def set_version(self):
self.version = tuple(int(x) for x in version.split('.'))
if len(self.version) == 2:
self.version = self.version + (0,)
- except:
+ except AttributeError:
self.version = (0, 0, 0)
@property
@@ -2769,7 +2770,7 @@ def write_array(self, key, value, items=None):
else:
try:
items = list(items)
- except:
+ except TypeError:
pass
ws = performance_doc % (inferred_type, key, items)
warnings.warn(ws, PerformanceWarning, stacklevel=7)
@@ -2843,7 +2844,7 @@ class SeriesFixed(GenericFixed):
def shape(self):
try:
return len(getattr(self.group, 'values')),
- except:
+ except (TypeError, AttributeError):
return None
def read(self, **kwargs):
@@ -2961,7 +2962,7 @@ def shape(self):
shape = shape[::-1]
return shape
- except:
+ except AttributeError:
return None
def read(self, start=None, stop=None, **kwargs):
@@ -3495,7 +3496,7 @@ def create_axes(self, axes, obj, validate=True, nan_rep=None,
if axes is None:
try:
axes = _AXES_MAP[type(obj)]
- except:
+ except KeyError:
raise TypeError("cannot properly create the storer for: "
"[group->%s,value->%s]"
% (self.group._v_name, type(obj)))
@@ -3614,7 +3615,7 @@ def get_blk_items(mgr, blocks):
b, b_items = by_items.pop(items)
new_blocks.append(b)
new_blk_items.append(b_items)
- except:
+ except (IndexError, KeyError):
raise ValueError(
"cannot match existing table structure for [%s] on "
"appending data" % ','.join(pprint_thing(item) for
@@ -3642,7 +3643,7 @@ def get_blk_items(mgr, blocks):
if existing_table is not None and validate:
try:
existing_col = existing_table.values_axes[i]
- except:
+ except (IndexError, KeyError):
raise ValueError("Incompatible appended table [%s] with "
"existing table [%s]"
% (blocks, existing_table.values_axes))
@@ -4460,7 +4461,7 @@ def _get_info(info, name):
""" get/create the info for this name """
try:
idx = info[name]
- except:
+ except KeyError:
idx = info[name] = dict()
return idx
@@ -4782,7 +4783,7 @@ def __init__(self, table, where=None, start=None, stop=None, **kwargs):
)
self.coordinates = where
- except:
+ except ValueError:
pass
if self.coordinates is None:
| This PR changes bare excepts in `pandas/io/pytables.py` to more specific exceptions. I defaulted to using specific exceptions that seemed likely/triggered test errors, but it may be the case that I'm missing some or it's better to leave it as `Exception`.
- [x] closes #22874
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/22919 | 2018-10-01T01:57:14Z | 2018-10-02T21:14:49Z | 2018-10-02T21:14:49Z | 2018-10-02T22:35:49Z |
BUG: to_datetime preserves name of Index argument in the result | diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt
index b71edcf1f6f51..851c1a3fbd6e9 100644
--- a/doc/source/whatsnew/v0.24.0.txt
+++ b/doc/source/whatsnew/v0.24.0.txt
@@ -655,6 +655,7 @@ Datetimelike
- Bug in :class:`DatetimeIndex` incorrectly allowing indexing with ``Timedelta`` object (:issue:`20464`)
- Bug in :class:`DatetimeIndex` where frequency was being set if original frequency was ``None`` (:issue:`22150`)
- Bug in rounding methods of :class:`DatetimeIndex` (:meth:`~DatetimeIndex.round`, :meth:`~DatetimeIndex.ceil`, :meth:`~DatetimeIndex.floor`) and :class:`Timestamp` (:meth:`~Timestamp.round`, :meth:`~Timestamp.ceil`, :meth:`~Timestamp.floor`) could give rise to loss of precision (:issue:`22591`)
+- Bug in :func:`to_datetime` with an :class:`Index` argument that would drop the ``name`` from the result (:issue:`21697`)
Timedelta
^^^^^^^^^
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py
index 57387b9ea870a..4a5290a90313d 100644
--- a/pandas/core/tools/datetimes.py
+++ b/pandas/core/tools/datetimes.py
@@ -99,13 +99,13 @@ def _convert_and_box_cache(arg, cache_array, box, errors, name=None):
result = Series(arg).map(cache_array)
if box:
if errors == 'ignore':
- return Index(result)
+ return Index(result, name=name)
else:
return DatetimeIndex(result, name=name)
return result.values
-def _return_parsed_timezone_results(result, timezones, box, tz):
+def _return_parsed_timezone_results(result, timezones, box, tz, name):
"""
Return results from array_strptime if a %z or %Z directive was passed.
@@ -119,6 +119,9 @@ def _return_parsed_timezone_results(result, timezones, box, tz):
True boxes result as an Index-like, False returns an ndarray
tz : object
None or pytz timezone object
+ name : string, default None
+ Name for a DatetimeIndex
+
Returns
-------
tz_result : ndarray of parsed dates with timezone
@@ -136,7 +139,7 @@ def _return_parsed_timezone_results(result, timezones, box, tz):
in zip(result, timezones)])
if box:
from pandas import Index
- return Index(tz_results)
+ return Index(tz_results, name=name)
return tz_results
@@ -209,7 +212,7 @@ def _convert_listlike_datetimes(arg, box, format, name=None, tz=None,
if box:
if errors == 'ignore':
from pandas import Index
- return Index(result)
+ return Index(result, name=name)
return DatetimeIndex(result, tz=tz, name=name)
return result
@@ -252,7 +255,7 @@ def _convert_listlike_datetimes(arg, box, format, name=None, tz=None,
arg, format, exact=exact, errors=errors)
if '%Z' in format or '%z' in format:
return _return_parsed_timezone_results(
- result, timezones, box, tz)
+ result, timezones, box, tz, name)
except tslibs.OutOfBoundsDatetime:
if errors == 'raise':
raise
diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py
index cc6db8f5854c8..3b7d6a709230b 100644
--- a/pandas/tests/indexes/datetimes/test_tools.py
+++ b/pandas/tests/indexes/datetimes/test_tools.py
@@ -233,6 +233,15 @@ def test_to_datetime_parse_timezone_malformed(self, offset):
with pytest.raises(ValueError):
pd.to_datetime([date], format=fmt)
+ def test_to_datetime_parse_timezone_keeps_name(self):
+ # GH 21697
+ fmt = '%Y-%m-%d %H:%M:%S %z'
+ arg = pd.Index(['2010-01-01 12:00:00 Z'], name='foo')
+ result = pd.to_datetime(arg, format=fmt)
+ expected = pd.DatetimeIndex(['2010-01-01 12:00:00'], tz='UTC',
+ name='foo')
+ tm.assert_index_equal(result, expected)
+
class TestToDatetime(object):
def test_to_datetime_pydatetime(self):
@@ -765,6 +774,14 @@ def test_unit_rounding(self, cache):
expected = pd.Timestamp('2015-06-19 19:55:31.877000093')
assert result == expected
+ @pytest.mark.parametrize('cache', [True, False])
+ def test_unit_ignore_keeps_name(self, cache):
+ # GH 21697
+ expected = pd.Index([15e9] * 2, name='name')
+ result = pd.to_datetime(expected, errors='ignore', box=True, unit='s',
+ cache=cache)
+ tm.assert_index_equal(result, expected)
+
@pytest.mark.parametrize('cache', [True, False])
def test_dataframe(self, cache):
| - [x] closes #21697
- [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/22918 | 2018-10-01T01:47:37Z | 2018-10-01T21:22:21Z | 2018-10-01T21:22:21Z | 2018-10-01T21:22:24Z |
Use fused types for _take_2d | diff --git a/pandas/_libs/algos_common_helper.pxi.in b/pandas/_libs/algos_common_helper.pxi.in
index 40b1b1a282670..9f531f36d1a64 100644
--- a/pandas/_libs/algos_common_helper.pxi.in
+++ b/pandas/_libs/algos_common_helper.pxi.in
@@ -2,7 +2,6 @@
Template for each `dtype` helper function using 1-d template
# 1-d template
-- map_indices
- pad
- pad_1d
- pad_2d
diff --git a/pandas/_libs/algos_rank_helper.pxi.in b/pandas/_libs/algos_rank_helper.pxi.in
index b2551f3733904..130276ae0e73c 100644
--- a/pandas/_libs/algos_rank_helper.pxi.in
+++ b/pandas/_libs/algos_rank_helper.pxi.in
@@ -24,17 +24,8 @@ dtypes = [('object', 'object', 'Infinity()', 'NegInfinity()'),
@cython.wraparound(False)
@cython.boundscheck(False)
-{{if dtype == 'object'}}
-
-
def rank_1d_{{dtype}}(object in_arr, ties_method='average',
ascending=True, na_option='keep', pct=False):
-{{else}}
-
-
-def rank_1d_{{dtype}}(object in_arr, ties_method='average', ascending=True,
- na_option='keep', pct=False):
-{{endif}}
"""
Fast NaN-friendly version of scipy.stats.rankdata
"""
diff --git a/pandas/_libs/algos_take_helper.pxi.in b/pandas/_libs/algos_take_helper.pxi.in
index 0e69324acd341..358479c837d05 100644
--- a/pandas/_libs/algos_take_helper.pxi.in
+++ b/pandas/_libs/algos_take_helper.pxi.in
@@ -260,33 +260,39 @@ def take_2d_multi_{{name}}_{{dest}}(ndarray[{{c_type_in}}, ndim=2] values,
{{endfor}}
-#----------------------------------------------------------------------
+# ----------------------------------------------------------------------
# take_2d internal function
-#----------------------------------------------------------------------
+# ----------------------------------------------------------------------
-{{py:
-
-# dtype, ctype, init_result
-dtypes = [('float64', 'float64_t', 'np.empty_like(values)'),
- ('uint64', 'uint64_t', 'np.empty_like(values)'),
- ('object', 'object', 'values.copy()'),
- ('int64', 'int64_t', 'np.empty_like(values)')]
-}}
+ctypedef fused take_t:
+ float64_t
+ uint64_t
+ int64_t
+ object
-{{for dtype, ctype, init_result in dtypes}}
-cdef _take_2d_{{dtype}}(ndarray[{{ctype}}, ndim=2] values, object idx):
+cdef _take_2d(ndarray[take_t, ndim=2] values, object idx):
cdef:
Py_ssize_t i, j, N, K
ndarray[Py_ssize_t, ndim=2, cast=True] indexer = idx
- ndarray[{{ctype}}, ndim=2] result
+ ndarray[take_t, ndim=2] result
object val
N, K = (<object> values).shape
- result = {{init_result}}
+
+ if take_t is object:
+ # evaluated at compile-time
+ result = values.copy()
+ else:
+ result = np.empty_like(values)
+
for i in range(N):
for j in range(K):
result[i, j] = values[i, indexer[i, j]]
return result
-{{endfor}}
+
+_take_2d_object = _take_2d[object]
+_take_2d_float64 = _take_2d[float64_t]
+_take_2d_int64 = _take_2d[int64_t]
+_take_2d_uint64 = _take_2d[uint64_t]
diff --git a/pandas/_libs/join_func_helper.pxi.in b/pandas/_libs/join_func_helper.pxi.in
index 73d231b8588dc..a72b113a6fdb6 100644
--- a/pandas/_libs/join_func_helper.pxi.in
+++ b/pandas/_libs/join_func_helper.pxi.in
@@ -68,21 +68,21 @@ def asof_join_backward_{{on_dtype}}_by_{{by_dtype}}(
# find last position in right whose value is less than left's
if allow_exact_matches:
- while right_pos < right_size and\
- right_values[right_pos] <= left_values[left_pos]:
+ while (right_pos < right_size and
+ right_values[right_pos] <= left_values[left_pos]):
hash_table.set_item(right_by_values[right_pos], right_pos)
right_pos += 1
else:
- while right_pos < right_size and\
- right_values[right_pos] < left_values[left_pos]:
+ while (right_pos < right_size and
+ right_values[right_pos] < left_values[left_pos]):
hash_table.set_item(right_by_values[right_pos], right_pos)
right_pos += 1
right_pos -= 1
# save positions as the desired index
by_value = left_by_values[left_pos]
- found_right_pos = hash_table.get_item(by_value)\
- if by_value in hash_table else -1
+ found_right_pos = (hash_table.get_item(by_value)
+ if by_value in hash_table else -1)
left_indexer[left_pos] = left_pos
right_indexer[left_pos] = found_right_pos
@@ -133,21 +133,21 @@ def asof_join_forward_{{on_dtype}}_by_{{by_dtype}}(
# find first position in right whose value is greater than left's
if allow_exact_matches:
- while right_pos >= 0 and\
- right_values[right_pos] >= left_values[left_pos]:
+ while (right_pos >= 0 and
+ right_values[right_pos] >= left_values[left_pos]):
hash_table.set_item(right_by_values[right_pos], right_pos)
right_pos -= 1
else:
- while right_pos >= 0 and\
- right_values[right_pos] > left_values[left_pos]:
+ while (right_pos >= 0 and
+ right_values[right_pos] > left_values[left_pos]):
hash_table.set_item(right_by_values[right_pos], right_pos)
right_pos -= 1
right_pos += 1
# save positions as the desired index
by_value = left_by_values[left_pos]
- found_right_pos = hash_table.get_item(by_value)\
- if by_value in hash_table else -1
+ found_right_pos = (hash_table.get_item(by_value)
+ if by_value in hash_table else -1)
left_indexer[left_pos] = left_pos
right_indexer[left_pos] = found_right_pos
@@ -259,12 +259,12 @@ def asof_join_backward_{{on_dtype}}(
# find last position in right whose value is less than left's
if allow_exact_matches:
- while right_pos < right_size and\
- right_values[right_pos] <= left_values[left_pos]:
+ while (right_pos < right_size and
+ right_values[right_pos] <= left_values[left_pos]):
right_pos += 1
else:
- while right_pos < right_size and\
- right_values[right_pos] < left_values[left_pos]:
+ while (right_pos < right_size and
+ right_values[right_pos] < left_values[left_pos]):
right_pos += 1
right_pos -= 1
@@ -313,19 +313,19 @@ def asof_join_forward_{{on_dtype}}(
# find first position in right whose value is greater than left's
if allow_exact_matches:
- while right_pos >= 0 and\
- right_values[right_pos] >= left_values[left_pos]:
+ while (right_pos >= 0 and
+ right_values[right_pos] >= left_values[left_pos]):
right_pos -= 1
else:
- while right_pos >= 0 and\
- right_values[right_pos] > left_values[left_pos]:
+ while (right_pos >= 0 and
+ right_values[right_pos] > left_values[left_pos]):
right_pos -= 1
right_pos += 1
# save positions as the desired index
left_indexer[left_pos] = left_pos
- right_indexer[left_pos] = right_pos\
- if right_pos != right_size else -1
+ right_indexer[left_pos] = (right_pos
+ if right_pos != right_size else -1)
# if needed, verify that tolerance is met
if has_tolerance and right_pos != right_size:
diff --git a/pandas/_libs/join_helper.pxi.in b/pandas/_libs/join_helper.pxi.in
index feb8cfb76a7f0..6ba587a5b04ea 100644
--- a/pandas/_libs/join_helper.pxi.in
+++ b/pandas/_libs/join_helper.pxi.in
@@ -4,42 +4,30 @@ Template for each `dtype` helper function for join
WARNING: DO NOT edit .pxi FILE directly, .pxi is generated from .pxi.in
"""
-#----------------------------------------------------------------------
+# ----------------------------------------------------------------------
# left_join_indexer, inner_join_indexer, outer_join_indexer
-#----------------------------------------------------------------------
+# ----------------------------------------------------------------------
-{{py:
-
-# name, c_type, dtype
-dtypes = [('float64', 'float64_t', 'np.float64'),
- ('float32', 'float32_t', 'np.float32'),
- ('object', 'object', 'object'),
- ('int32', 'int32_t', 'np.int32'),
- ('int64', 'int64_t', 'np.int64'),
- ('uint64', 'uint64_t', 'np.uint64')]
-
-def get_dispatch(dtypes):
-
- for name, c_type, dtype in dtypes:
- yield name, c_type, dtype
-
-}}
+ctypedef fused join_t:
+ float64_t
+ float32_t
+ object
+ int32_t
+ int64_t
+ uint64_t
-{{for name, c_type, dtype in get_dispatch(dtypes)}}
# Joins on ordered, unique indices
# right might contain non-unique values
-
@cython.wraparound(False)
@cython.boundscheck(False)
-def left_join_indexer_unique_{{name}}(ndarray[{{c_type}}] left,
- ndarray[{{c_type}}] right):
+def left_join_indexer_unique(ndarray[join_t] left, ndarray[join_t] right):
cdef:
Py_ssize_t i, j, nleft, nright
ndarray[int64_t] indexer
- {{c_type}} lval, rval
+ join_t lval, rval
i = 0
j = 0
@@ -78,6 +66,33 @@ def left_join_indexer_unique_{{name}}(ndarray[{{c_type}}] left,
return indexer
+left_join_indexer_unique_float64 = left_join_indexer_unique["float64_t"]
+left_join_indexer_unique_float32 = left_join_indexer_unique["float32_t"]
+left_join_indexer_unique_object = left_join_indexer_unique["object"]
+left_join_indexer_unique_int32 = left_join_indexer_unique["int32_t"]
+left_join_indexer_unique_int64 = left_join_indexer_unique["int64_t"]
+left_join_indexer_unique_uint64 = left_join_indexer_unique["uint64_t"]
+
+
+{{py:
+
+# name, c_type, dtype
+dtypes = [('float64', 'float64_t', 'np.float64'),
+ ('float32', 'float32_t', 'np.float32'),
+ ('object', 'object', 'object'),
+ ('int32', 'int32_t', 'np.int32'),
+ ('int64', 'int64_t', 'np.int64'),
+ ('uint64', 'uint64_t', 'np.uint64')]
+
+def get_dispatch(dtypes):
+
+ for name, c_type, dtype in dtypes:
+ yield name, c_type, dtype
+
+}}
+
+{{for name, c_type, dtype in get_dispatch(dtypes)}}
+
# @cython.wraparound(False)
# @cython.boundscheck(False)
def left_join_indexer_{{name}}(ndarray[{{c_type}}] left,
| Misc cleanup
For some of the cython code I get unexplained test failures when using fused types. Vaguely hoping to narrow down the set of affected functions so as to make a helpful bug report to cython. | https://api.github.com/repos/pandas-dev/pandas/pulls/22917 | 2018-10-01T01:29:52Z | 2018-10-05T12:18:41Z | 2018-10-05T12:18:41Z | 2018-10-05T13:38:45Z |
CLN: Flake8 E741 | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 986fe347898f5..c2d2e447d1616 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -1,3 +1,5 @@
+# pylint: disable=E1101
+# pylint: disable=W0212,W0703,W0622
"""
DataFrame
---------
@@ -9,11 +11,9 @@
labeling information
"""
from __future__ import division
-# pylint: disable=E1101,E1103
-# pylint: disable=W0212,W0231,W0703,W0622
-import functools
import collections
+import functools
import itertools
import sys
import warnings
@@ -22,7 +22,20 @@
import numpy as np
import numpy.ma as ma
-from pandas.core.accessor import CachedAccessor
+from pandas._libs import lib, algos as libalgos
+
+from pandas.util._decorators import (Appender, Substitution,
+ rewrite_axis_style_signature,
+ deprecate_kwarg)
+from pandas.util._validators import (validate_bool_kwarg,
+ validate_axis_style_args)
+
+from pandas import compat
+from pandas.compat import (range, map, zip, lrange, lmap, lzip, StringIO, u,
+ OrderedDict, PY36, raise_with_traceback,
+ string_and_binary_types)
+from pandas.compat.numpy import function as nv
+
from pandas.core.dtypes.cast import (
maybe_upcast,
cast_scalar_to_array,
@@ -62,46 +75,32 @@
from pandas.core.dtypes.concat import _get_sliced_frame_result_type
from pandas.core.dtypes.missing import isna, notna
-
+from pandas.core import algorithms
+from pandas.core import common as com
+from pandas.core import nanops
+from pandas.core import ops
+from pandas.core.accessor import CachedAccessor
+from pandas.core.arrays import Categorical, ExtensionArray
+from pandas.core.config import get_option
from pandas.core.generic import NDFrame, _shared_docs
from pandas.core.index import (Index, MultiIndex, ensure_index,
ensure_index_from_sequences)
+from pandas.core.indexes import base as ibase
+from pandas.core.indexes.datetimes import DatetimeIndex
+from pandas.core.indexes.period import PeriodIndex
+from pandas.core.indexes.timedeltas import TimedeltaIndex
from pandas.core.indexing import (maybe_droplevels, convert_to_index_sliceable,
check_bool_indexer)
from pandas.core.internals import (BlockManager,
create_block_manager_from_arrays,
create_block_manager_from_blocks)
from pandas.core.series import Series
-from pandas.core.arrays import Categorical, ExtensionArray
-import pandas.core.algorithms as algorithms
-from pandas.compat import (range, map, zip, lrange, lmap, lzip, StringIO, u,
- OrderedDict, raise_with_traceback,
- string_and_binary_types)
-from pandas import compat
-from pandas.compat import PY36
-from pandas.compat.numpy import function as nv
-from pandas.util._decorators import (Appender, Substitution,
- rewrite_axis_style_signature,
- deprecate_kwarg)
-from pandas.util._validators import (validate_bool_kwarg,
- validate_axis_style_args)
-
-from pandas.core.indexes.period import PeriodIndex
-from pandas.core.indexes.datetimes import DatetimeIndex
-from pandas.core.indexes.timedeltas import TimedeltaIndex
-import pandas.core.indexes.base as ibase
-import pandas.core.common as com
-import pandas.core.nanops as nanops
-import pandas.core.ops as ops
-import pandas.io.formats.console as console
-import pandas.io.formats.format as fmt
+from pandas.io.formats import console
+from pandas.io.formats import format as fmt
from pandas.io.formats.printing import pprint_thing
-import pandas.plotting._core as gfx
-
-from pandas._libs import lib, algos as libalgos
-from pandas.core.config import get_option
+import pandas.plotting._core as gfx
# ---------------------------------------------------------------------
# Docstring templates
@@ -1003,7 +1002,7 @@ def dot(self, other):
rvals = np.asarray(other)
if lvals.shape[1] != rvals.shape[0]:
raise ValueError('Dot product shape mismatch, '
- '{l} vs {r}'.format(l=lvals.shape,
+ '{s} vs {r}'.format(s=lvals.shape,
r=rvals.shape))
if isinstance(other, DataFrame):
diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py
index fd8e17c369f5a..a0c3243ddbc3c 100644
--- a/pandas/core/indexes/range.py
+++ b/pandas/core/indexes/range.py
@@ -1,9 +1,16 @@
-from sys import getsizeof
import operator
from datetime import timedelta
+from sys import getsizeof
import numpy as np
+
+from pandas import compat
+
from pandas._libs import index as libindex
+from pandas.util._decorators import Appender, cache_readonly
+
+from pandas.compat import lrange, range, get_range_parameters
+from pandas.compat.numpy import function as nv
from pandas.core.dtypes.common import (
is_integer,
@@ -11,18 +18,12 @@
is_timedelta64_dtype,
is_int64_dtype)
from pandas.core.dtypes.generic import ABCSeries, ABCTimedeltaIndex
-
-from pandas import compat
-from pandas.compat import lrange, range, get_range_parameters
-from pandas.compat.numpy import function as nv
+from pandas.core.dtypes import concat as _concat
import pandas.core.common as com
+import pandas.core.indexes.base as ibase
from pandas.core import ops
from pandas.core.indexes.base import Index, _index_shared_docs
-from pandas.util._decorators import Appender, cache_readonly
-import pandas.core.dtypes.concat as _concat
-import pandas.core.indexes.base as ibase
-
from pandas.core.indexes.numeric import Int64Index
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 150518aadcfd9..b3c913f21dd86 100755
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -1,10 +1,16 @@
# pylint: disable=W0223
import textwrap
import warnings
+
import numpy as np
-from pandas.compat import range, zip
+from pandas._libs.indexing import _NDFrameIndexerBase
+from pandas.util._decorators import Appender
+
+from pandas.errors import AbstractMethodError
+
import pandas.compat as compat
-from pandas.core.dtypes.generic import ABCDataFrame, ABCPanel, ABCSeries
+from pandas.compat import range, zip
+
from pandas.core.dtypes.common import (
is_integer_dtype,
is_integer, is_float,
@@ -14,14 +20,11 @@
is_scalar,
is_sparse,
ensure_platform_int)
+from pandas.core.dtypes.generic import ABCDataFrame, ABCPanel, ABCSeries
from pandas.core.dtypes.missing import isna, _infer_fill_value
-from pandas.errors import AbstractMethodError
-from pandas.util._decorators import Appender
-
-from pandas.core.index import Index, MultiIndex
import pandas.core.common as com
-from pandas._libs.indexing import _NDFrameIndexerBase
+from pandas.core.index import Index, MultiIndex
# the supported indexers
@@ -304,8 +307,7 @@ def _setitem_with_indexer(self, indexer, value):
self._has_valid_setitem_indexer(indexer)
# also has the side effect of consolidating in-place
- # TODO: Panel, DataFrame are not imported, remove?
- from pandas import Panel, DataFrame, Series # noqa
+ from pandas import Series
info_axis = self.obj._info_axis_number
# maybe partial set
@@ -553,14 +555,14 @@ def can_do_equal_len():
is_scalar(plane_indexer[0])):
return False
- l = len(value)
item = labels[0]
index = self.obj[item].index
+ values_len = len(value)
# equal len list/ndarray
- if len(index) == l:
+ if len(index) == values_len:
return True
- elif lplane_indexer == l:
+ elif lplane_indexer == values_len:
return True
return False
@@ -717,8 +719,8 @@ def ravel(i):
# single indexer
if len(indexer) > 1 and not multiindex_indexer:
- l = len(indexer[1])
- ser = np.tile(ser, l).reshape(l, -1).T
+ len_indexer = len(indexer[1])
+ ser = np.tile(ser, len_indexer).reshape(len_indexer, -1).T
return ser
@@ -2077,9 +2079,9 @@ def _validate_key(self, key, axis):
elif is_list_like_indexer(key):
# check that the key does not exceed the maximum size of the index
arr = np.array(key)
- l = len(self.obj._get_axis(axis))
+ len_axis = len(self.obj._get_axis(axis))
- if len(arr) and (arr.max() >= l or arr.min() < -l):
+ if len(arr) and (arr.max() >= len_axis or arr.min() < -len_axis):
raise IndexError("positional indexers are out-of-bounds")
else:
raise ValueError("Can only index by location with "
@@ -2136,9 +2138,8 @@ def _validate_integer(self, key, axis):
If 'key' is not a valid position in axis 'axis'
"""
- ax = self.obj._get_axis(axis)
- l = len(ax)
- if key >= l or key < -l:
+ len_axis = len(self.obj._get_axis(axis))
+ if key >= len_axis or key < -len_axis:
raise IndexError("single positional indexer is out-of-bounds")
def _getitem_tuple(self, tup):
@@ -2425,18 +2426,18 @@ def length_of_indexer(indexer, target=None):
"""return the length of a single non-tuple indexer which could be a slice
"""
if target is not None and isinstance(indexer, slice):
- l = len(target)
+ target_len = len(target)
start = indexer.start
stop = indexer.stop
step = indexer.step
if start is None:
start = 0
elif start < 0:
- start += l
- if stop is None or stop > l:
- stop = l
+ start += target_len
+ if stop is None or stop > target_len:
+ stop = target_len
elif stop < 0:
- stop += l
+ stop += target_len
if step is None:
step = 1
elif step < 0:
diff --git a/pandas/io/packers.py b/pandas/io/packers.py
index 7a1e72637f4ce..e27a1a623adb5 100644
--- a/pandas/io/packers.py
+++ b/pandas/io/packers.py
@@ -38,39 +38,41 @@
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
-from datetime import datetime, date, timedelta
-from dateutil.parser import parse
import os
-from textwrap import dedent
import warnings
+from datetime import datetime, date, timedelta
+from textwrap import dedent
import numpy as np
+from dateutil.parser import parse
+
from pandas import compat
+from pandas import (Timestamp, Period, Series, DataFrame, # noqa:F401
+ Index, MultiIndex, Float64Index, Int64Index,
+ Panel, RangeIndex, PeriodIndex, DatetimeIndex, NaT,
+ Categorical, CategoricalIndex, IntervalIndex, Interval,
+ TimedeltaIndex)
+
+from pandas.util._move import (
+ BadMove as _BadMove,
+ move_into_mutable_buffer as _move_into_mutable_buffer,
+)
+from pandas.errors import PerformanceWarning
+
from pandas.compat import u, u_safe
from pandas.core.dtypes.common import (
is_categorical_dtype, is_object_dtype,
needs_i8_conversion, pandas_dtype)
-from pandas import (Timestamp, Period, Series, DataFrame, # noqa
- Index, MultiIndex, Float64Index, Int64Index,
- Panel, RangeIndex, PeriodIndex, DatetimeIndex, NaT,
- Categorical, CategoricalIndex, IntervalIndex, Interval,
- TimedeltaIndex)
+from pandas.core import internals
from pandas.core.arrays import IntervalArray
+from pandas.core.generic import NDFrame
+from pandas.core.internals import BlockManager, make_block, _safe_reshape
from pandas.core.sparse.api import SparseSeries, SparseDataFrame
from pandas.core.sparse.array import BlockIndex, IntIndex
-from pandas.core.generic import NDFrame
-from pandas.errors import PerformanceWarning
from pandas.io.common import get_filepath_or_buffer, _stringify_path
-from pandas.core.internals import BlockManager, make_block, _safe_reshape
-import pandas.core.internals as internals
-
from pandas.io.msgpack import Unpacker as _Unpacker, Packer as _Packer, ExtType
-from pandas.util._move import (
- BadMove as _BadMove,
- move_into_mutable_buffer as _move_into_mutable_buffer,
-)
# check which compression libs we have installed
try:
@@ -187,16 +189,16 @@ def read_msgpack(path_or_buf, encoding='utf-8', iterator=False, **kwargs):
return Iterator(path_or_buf)
def read(fh):
- l = list(unpack(fh, encoding=encoding, **kwargs))
- if len(l) == 1:
- return l[0]
+ unpacked_obj = list(unpack(fh, encoding=encoding, **kwargs))
+ if len(unpacked_obj) == 1:
+ return unpacked_obj[0]
if should_close:
try:
path_or_buf.close()
except: # noqa: flake8
pass
- return l
+ return unpacked_obj
# see if we have an actual file
if isinstance(path_or_buf, compat.string_types):
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py
index fc9e415ed38f7..ff37036533b4f 100644
--- a/pandas/io/pytables.py
+++ b/pandas/io/pytables.py
@@ -1,26 +1,31 @@
+# pylint: disable-msg=E1101,W0613,W0603
"""
High level interface to PyTables for reading and writing pandas data structures
to disk
"""
-# pylint: disable-msg=E1101,W0613,W0603
-from datetime import datetime, date
-import time
-import re
import copy
import itertools
-import warnings
import os
+import re
+import time
+import warnings
+
+from datetime import datetime, date
from distutils.version import LooseVersion
import numpy as np
+from pandas import (Series, DataFrame, Panel, Index,
+ MultiIndex, Int64Index, isna, concat, to_datetime,
+ SparseSeries, SparseDataFrame, PeriodIndex,
+ DatetimeIndex, TimedeltaIndex)
+from pandas import compat
from pandas._libs import algos, lib, writers as libwriters
from pandas._libs.tslibs import timezones
from pandas.errors import PerformanceWarning
-from pandas import compat
-from pandas.compat import u_safe as u, PY3, range, lrange, string_types, filter
+from pandas.compat import PY3, range, lrange, string_types, filter
from pandas.core.dtypes.common import (
is_list_like,
@@ -34,27 +39,22 @@
from pandas.core.dtypes.missing import array_equivalent
from pandas.core import config
-from pandas.core.config import get_option
-from pandas.core.sparse.array import BlockIndex, IntIndex
-from pandas.core.base import StringMixin
import pandas.core.common as com
from pandas.core.algorithms import match, unique
from pandas.core.arrays.categorical import (Categorical,
_factorize_from_iterables)
+from pandas.core.base import StringMixin
+from pandas.core.computation.pytables import Expr, maybe_expression
+from pandas.core.config import get_option
+from pandas.core.index import ensure_index
from pandas.core.internals import (BlockManager, make_block,
_block2d_to_blocknd,
_factor_indexer, _block_shape)
-from pandas.core.index import ensure_index
-from pandas.core.computation.pytables import Expr, maybe_expression
+from pandas.core.sparse.array import BlockIndex, IntIndex
from pandas.io.common import _stringify_path
from pandas.io.formats.printing import adjoin, pprint_thing
-from pandas import (Series, DataFrame, Panel, Index,
- MultiIndex, Int64Index, isna, concat, to_datetime,
- SparseSeries, SparseDataFrame, PeriodIndex,
- DatetimeIndex, TimedeltaIndex)
-
# versioning attribute
_version = '0.15.2'
@@ -161,10 +161,10 @@ class DuplicateWarning(Warning):
# formats
_FORMAT_MAP = {
- u('f'): 'fixed',
- u('fixed'): 'fixed',
- u('t'): 'table',
- u('table'): 'table',
+ u'f': 'fixed',
+ u'fixed': 'fixed',
+ u't': 'table',
+ u'table': 'table',
}
format_deprecate_doc = """
@@ -179,36 +179,36 @@ class DuplicateWarning(Warning):
# map object types
_TYPE_MAP = {
- Series: u('series'),
- SparseSeries: u('sparse_series'),
- DataFrame: u('frame'),
- SparseDataFrame: u('sparse_frame'),
- Panel: u('wide'),
+ Series: u'series',
+ SparseSeries: u'sparse_series',
+ DataFrame: u'frame',
+ SparseDataFrame: u'sparse_frame',
+ Panel: u'wide',
}
# storer class map
_STORER_MAP = {
- u('Series'): 'LegacySeriesFixed',
- u('DataFrame'): 'LegacyFrameFixed',
- u('DataMatrix'): 'LegacyFrameFixed',
- u('series'): 'SeriesFixed',
- u('sparse_series'): 'SparseSeriesFixed',
- u('frame'): 'FrameFixed',
- u('sparse_frame'): 'SparseFrameFixed',
- u('wide'): 'PanelFixed',
+ u'Series': 'LegacySeriesFixed',
+ u'DataFrame': 'LegacyFrameFixed',
+ u'DataMatrix': 'LegacyFrameFixed',
+ u'series': 'SeriesFixed',
+ u'sparse_series': 'SparseSeriesFixed',
+ u'frame': 'FrameFixed',
+ u'sparse_frame': 'SparseFrameFixed',
+ u'wide': 'PanelFixed',
}
# table class map
_TABLE_MAP = {
- u('generic_table'): 'GenericTable',
- u('appendable_series'): 'AppendableSeriesTable',
- u('appendable_multiseries'): 'AppendableMultiSeriesTable',
- u('appendable_frame'): 'AppendableFrameTable',
- u('appendable_multiframe'): 'AppendableMultiFrameTable',
- u('appendable_panel'): 'AppendablePanelTable',
- u('worm'): 'WORMTable',
- u('legacy_frame'): 'LegacyFrameTable',
- u('legacy_panel'): 'LegacyPanelTable',
+ u'generic_table': 'GenericTable',
+ u'appendable_series': 'AppendableSeriesTable',
+ u'appendable_multiseries': 'AppendableMultiSeriesTable',
+ u'appendable_frame': 'AppendableFrameTable',
+ u'appendable_multiframe': 'AppendableMultiFrameTable',
+ u'appendable_panel': 'AppendablePanelTable',
+ u'worm': 'WORMTable',
+ u'legacy_frame': 'LegacyFrameTable',
+ u'legacy_panel': 'LegacyPanelTable',
}
# axes map
@@ -1104,7 +1104,7 @@ def groups(self):
(getattr(g._v_attrs, 'pandas_type', None) or
getattr(g, 'table', None) or
(isinstance(g, _table_mod.table.Table) and
- g._v_name != u('table'))))
+ g._v_name != u'table')))
]
def walk(self, where="/"):
@@ -1297,8 +1297,8 @@ def error(t):
_tables()
if (getattr(group, 'table', None) or
isinstance(group, _table_mod.table.Table)):
- pt = u('frame_table')
- tt = u('generic_table')
+ pt = u'frame_table'
+ tt = u'generic_table'
else:
raise TypeError(
"cannot create a storer if the object is not existing "
@@ -1312,10 +1312,10 @@ def error(t):
# we are actually a table
if format == 'table':
- pt += u('_table')
+ pt += u'_table'
# a storer node
- if u('table') not in pt:
+ if u'table' not in pt:
try:
return globals()[_STORER_MAP[pt]](self, group, **kwargs)
except KeyError:
@@ -1327,33 +1327,33 @@ def error(t):
# if we are a writer, determine the tt
if value is not None:
- if pt == u('series_table'):
+ if pt == u'series_table':
index = getattr(value, 'index', None)
if index is not None:
if index.nlevels == 1:
- tt = u('appendable_series')
+ tt = u'appendable_series'
elif index.nlevels > 1:
- tt = u('appendable_multiseries')
- elif pt == u('frame_table'):
+ tt = u'appendable_multiseries'
+ elif pt == u'frame_table':
index = getattr(value, 'index', None)
if index is not None:
if index.nlevels == 1:
- tt = u('appendable_frame')
+ tt = u'appendable_frame'
elif index.nlevels > 1:
- tt = u('appendable_multiframe')
- elif pt == u('wide_table'):
- tt = u('appendable_panel')
- elif pt == u('ndim_table'):
- tt = u('appendable_ndim')
+ tt = u'appendable_multiframe'
+ elif pt == u'wide_table':
+ tt = u'appendable_panel'
+ elif pt == u'ndim_table':
+ tt = u'appendable_ndim'
else:
# distiguish between a frame/table
- tt = u('legacy_panel')
+ tt = u'legacy_panel'
try:
fields = group.table._v_attrs.fields
- if len(fields) == 1 and fields[0] == u('value'):
- tt = u('legacy_frame')
+ if len(fields) == 1 and fields[0] == u'value':
+ tt = u'legacy_frame'
except IndexError:
pass
@@ -1699,7 +1699,7 @@ def maybe_set_size(self, min_itemsize=None, **kwargs):
""" maybe set a string col itemsize:
min_itemsize can be an integer or a dict with this columns name
with an integer size """
- if _ensure_decoded(self.kind) == u('string'):
+ if _ensure_decoded(self.kind) == u'string':
if isinstance(min_itemsize, dict):
min_itemsize = min_itemsize.get(self.name)
@@ -1726,7 +1726,7 @@ def validate_col(self, itemsize=None):
""" validate this column: return the compared against itemsize """
# validate this column for string truncation (or reset to the max size)
- if _ensure_decoded(self.kind) == u('string'):
+ if _ensure_decoded(self.kind) == u'string':
c = self.col
if c is not None:
if itemsize is None:
@@ -1881,9 +1881,9 @@ def __init__(self, values=None, kind=None, typ=None,
super(DataCol, self).__init__(values=values, kind=kind, typ=typ,
cname=cname, **kwargs)
self.dtype = None
- self.dtype_attr = u("%s_dtype" % self.name)
+ self.dtype_attr = u'{}_dtype'.format(self.name)
self.meta = meta
- self.meta_attr = u("%s_meta" % self.name)
+ self.meta_attr = u'{}_meta'.format(self.name)
self.set_data(data)
self.set_metadata(metadata)
@@ -1929,19 +1929,19 @@ def set_kind(self):
if self.dtype is not None:
dtype = _ensure_decoded(self.dtype)
- if dtype.startswith(u('string')) or dtype.startswith(u('bytes')):
+ if dtype.startswith(u'string') or dtype.startswith(u'bytes'):
self.kind = 'string'
- elif dtype.startswith(u('float')):
+ elif dtype.startswith(u'float'):
self.kind = 'float'
- elif dtype.startswith(u('complex')):
+ elif dtype.startswith(u'complex'):
self.kind = 'complex'
- elif dtype.startswith(u('int')) or dtype.startswith(u('uint')):
+ elif dtype.startswith(u'int') or dtype.startswith(u'uint'):
self.kind = 'integer'
- elif dtype.startswith(u('date')):
+ elif dtype.startswith(u'date'):
self.kind = 'datetime'
- elif dtype.startswith(u('timedelta')):
+ elif dtype.startswith(u'timedelta'):
self.kind = 'timedelta'
- elif dtype.startswith(u('bool')):
+ elif dtype.startswith(u'bool'):
self.kind = 'bool'
else:
raise AssertionError(
@@ -2184,14 +2184,14 @@ def convert(self, values, nan_rep, encoding, errors):
dtype = _ensure_decoded(self.dtype)
# reverse converts
- if dtype == u('datetime64'):
+ if dtype == u'datetime64':
# recreate with tz if indicated
self.data = _set_tz(self.data, self.tz, coerce=True)
- elif dtype == u('timedelta64'):
+ elif dtype == u'timedelta64':
self.data = np.asarray(self.data, dtype='m8[ns]')
- elif dtype == u('date'):
+ elif dtype == u'date':
try:
self.data = np.asarray(
[date.fromordinal(v) for v in self.data], dtype=object)
@@ -2199,12 +2199,12 @@ def convert(self, values, nan_rep, encoding, errors):
self.data = np.asarray(
[date.fromtimestamp(v) for v in self.data],
dtype=object)
- elif dtype == u('datetime'):
+ elif dtype == u'datetime':
self.data = np.asarray(
[datetime.fromtimestamp(v) for v in self.data],
dtype=object)
- elif meta == u('category'):
+ elif meta == u'category':
# we have a categorical
categories = self.metadata
@@ -2237,7 +2237,7 @@ def convert(self, values, nan_rep, encoding, errors):
self.data = self.data.astype('O', copy=False)
# convert nans / decode
- if _ensure_decoded(self.kind) == u('string'):
+ if _ensure_decoded(self.kind) == u'string':
self.data = _unconvert_string_array(
self.data, nan_rep=nan_rep, encoding=encoding, errors=errors)
@@ -2547,12 +2547,12 @@ def read_array(self, key, start=None, stop=None):
else:
ret = node[start:stop]
- if dtype == u('datetime64'):
+ if dtype == u'datetime64':
# reconstruct a timezone if indicated
ret = _set_tz(ret, getattr(attrs, 'tz', None), coerce=True)
- elif dtype == u('timedelta64'):
+ elif dtype == u'timedelta64':
ret = np.asarray(ret, dtype='m8[ns]')
if transposed:
@@ -2563,13 +2563,13 @@ def read_array(self, key, start=None, stop=None):
def read_index(self, key, **kwargs):
variety = _ensure_decoded(getattr(self.attrs, '%s_variety' % key))
- if variety == u('multi'):
+ if variety == u'multi':
return self.read_multi_index(key, **kwargs)
- elif variety == u('block'):
+ elif variety == u'block':
return self.read_block_index(key, **kwargs)
- elif variety == u('sparseint'):
+ elif variety == u'sparseint':
return self.read_sparse_intindex(key, **kwargs)
- elif variety == u('regular'):
+ elif variety == u'regular':
_, index = self.read_index_node(getattr(self.group, key), **kwargs)
return index
else: # pragma: no cover
@@ -2686,13 +2686,13 @@ def read_index_node(self, node, start=None, stop=None):
factory = self._get_index_factory(index_class)
kwargs = {}
- if u('freq') in node._v_attrs:
+ if u'freq' in node._v_attrs:
kwargs['freq'] = node._v_attrs['freq']
- if u('tz') in node._v_attrs:
+ if u'tz' in node._v_attrs:
kwargs['tz'] = node._v_attrs['tz']
- if kind in (u('date'), u('datetime')):
+ if kind in (u'date', u'datetime'):
index = factory(_unconvert_index(data, kind,
encoding=self.encoding,
errors=self.errors),
@@ -2837,7 +2837,7 @@ def read(self, **kwargs):
class SeriesFixed(GenericFixed):
- pandas_kind = u('series')
+ pandas_kind = u'series'
attributes = ['name']
@property
@@ -2874,7 +2874,7 @@ def validate_read(self, kwargs):
class SparseSeriesFixed(SparseFixed):
- pandas_kind = u('sparse_series')
+ pandas_kind = u'sparse_series'
attributes = ['name', 'fill_value', 'kind']
def read(self, **kwargs):
@@ -2883,7 +2883,7 @@ def read(self, **kwargs):
sp_values = self.read_array('sp_values')
sp_index = self.read_index('sp_index')
return SparseSeries(sp_values, index=index, sparse_index=sp_index,
- kind=self.kind or u('block'),
+ kind=self.kind or u'block',
fill_value=self.fill_value,
name=self.name)
@@ -2898,7 +2898,7 @@ def write(self, obj, **kwargs):
class SparseFrameFixed(SparseFixed):
- pandas_kind = u('sparse_frame')
+ pandas_kind = u'sparse_frame'
attributes = ['default_kind', 'default_fill_value']
def read(self, **kwargs):
@@ -3015,12 +3015,12 @@ def write(self, obj, **kwargs):
class FrameFixed(BlockManagerFixed):
- pandas_kind = u('frame')
+ pandas_kind = u'frame'
obj_type = DataFrame
class PanelFixed(BlockManagerFixed):
- pandas_kind = u('wide')
+ pandas_kind = u'wide'
obj_type = Panel
is_shape_reversed = True
@@ -3054,7 +3054,7 @@ class Table(Fixed):
metadata : the names of the metadata columns
"""
- pandas_kind = u('wide_table')
+ pandas_kind = u'wide_table'
table_type = None
levels = 1
is_table = True
@@ -3158,7 +3158,7 @@ def nrows_expected(self):
@property
def is_exists(self):
""" has this table been created """
- return u('table') in self.group
+ return u'table' in self.group
@property
def storable(self):
@@ -3837,7 +3837,7 @@ class WORMTable(Table):
table. writing is a one-time operation the data are stored in a format
that allows for searching the data on disk
"""
- table_type = u('worm')
+ table_type = u'worm'
def read(self, **kwargs):
""" read the indices and the indexing array, calculate offset rows and
@@ -3865,7 +3865,7 @@ class LegacyTable(Table):
IndexCol(name='column', axis=2, pos=1, index_kind='columns_kind'),
DataCol(name='fields', cname='values', kind_attr='fields', pos=2)
]
- table_type = u('legacy')
+ table_type = u'legacy'
ndim = 3
def write(self, **kwargs):
@@ -3962,8 +3962,8 @@ def read(self, where=None, columns=None, **kwargs):
class LegacyFrameTable(LegacyTable):
""" support the legacy frame table """
- pandas_kind = u('frame_table')
- table_type = u('legacy_frame')
+ pandas_kind = u'frame_table'
+ table_type = u'legacy_frame'
obj_type = Panel
def read(self, *args, **kwargs):
@@ -3973,7 +3973,7 @@ def read(self, *args, **kwargs):
class LegacyPanelTable(LegacyTable):
""" support the legacy panel table """
- table_type = u('legacy_panel')
+ table_type = u'legacy_panel'
obj_type = Panel
@@ -3981,7 +3981,7 @@ class AppendableTable(LegacyTable):
""" suppor the new appendable table formats """
_indexables = None
- table_type = u('appendable')
+ table_type = u'appendable'
def write(self, obj, axes=None, append=False, complib=None,
complevel=None, fletcher32=None, min_itemsize=None,
@@ -4172,13 +4172,13 @@ def delete(self, where=None, start=None, stop=None, **kwargs):
values = self.selection.select_coords()
# delete the rows in reverse order
- l = Series(values).sort_values()
- ln = len(l)
+ sorted_series = Series(values).sort_values()
+ ln = len(sorted_series)
if ln:
# construct groups of consecutive rows
- diff = l.diff()
+ diff = sorted_series.diff()
groups = list(diff[diff > 1].index)
# 1 group
@@ -4196,7 +4196,7 @@ def delete(self, where=None, start=None, stop=None, **kwargs):
# we must remove in reverse order!
pg = groups.pop()
for g in reversed(groups):
- rows = l.take(lrange(g, pg))
+ rows = sorted_series.take(lrange(g, pg))
table.remove_rows(start=rows[rows.index[0]
], stop=rows[rows.index[-1]] + 1)
pg = g
@@ -4210,8 +4210,8 @@ def delete(self, where=None, start=None, stop=None, **kwargs):
class AppendableFrameTable(AppendableTable):
""" suppor the new appendable table formats """
- pandas_kind = u('frame_table')
- table_type = u('appendable_frame')
+ pandas_kind = u'frame_table'
+ table_type = u'appendable_frame'
ndim = 2
obj_type = DataFrame
@@ -4276,8 +4276,8 @@ def read(self, where=None, columns=None, **kwargs):
class AppendableSeriesTable(AppendableFrameTable):
""" support the new appendable table formats """
- pandas_kind = u('series_table')
- table_type = u('appendable_series')
+ pandas_kind = u'series_table'
+ table_type = u'appendable_series'
ndim = 2
obj_type = Series
storage_obj_type = DataFrame
@@ -4319,8 +4319,8 @@ def read(self, columns=None, **kwargs):
class AppendableMultiSeriesTable(AppendableSeriesTable):
""" support the new appendable table formats """
- pandas_kind = u('series_table')
- table_type = u('appendable_multiseries')
+ pandas_kind = u'series_table'
+ table_type = u'appendable_multiseries'
def write(self, obj, **kwargs):
""" we are going to write this as a frame table """
@@ -4334,8 +4334,8 @@ def write(self, obj, **kwargs):
class GenericTable(AppendableFrameTable):
""" a table that read/writes the generic pytables table format """
- pandas_kind = u('frame_table')
- table_type = u('generic_table')
+ pandas_kind = u'frame_table'
+ table_type = u'generic_table'
ndim = 2
obj_type = DataFrame
@@ -4384,14 +4384,14 @@ def write(self, **kwargs):
class AppendableMultiFrameTable(AppendableFrameTable):
""" a frame with a multi-index """
- table_type = u('appendable_multiframe')
+ table_type = u'appendable_multiframe'
obj_type = DataFrame
ndim = 2
_re_levels = re.compile(r"^level_\d+$")
@property
def table_type_short(self):
- return u('appendable_multi')
+ return u'appendable_multi'
def write(self, obj, data_columns=None, **kwargs):
if data_columns is None:
@@ -4421,7 +4421,7 @@ def read(self, **kwargs):
class AppendablePanelTable(AppendableTable):
""" suppor the new appendable table formats """
- table_type = u('appendable_panel')
+ table_type = u'appendable_panel'
ndim = 3
obj_type = Panel
@@ -4592,26 +4592,26 @@ def _convert_index(index, encoding=None, errors='strict', format_type=None):
def _unconvert_index(data, kind, encoding=None, errors='strict'):
kind = _ensure_decoded(kind)
- if kind == u('datetime64'):
+ if kind == u'datetime64':
index = DatetimeIndex(data)
- elif kind == u('timedelta64'):
+ elif kind == u'timedelta64':
index = TimedeltaIndex(data)
- elif kind == u('datetime'):
+ elif kind == u'datetime':
index = np.asarray([datetime.fromtimestamp(v) for v in data],
dtype=object)
- elif kind == u('date'):
+ elif kind == u'date':
try:
index = np.asarray(
[date.fromordinal(v) for v in data], dtype=object)
except (ValueError):
index = np.asarray(
[date.fromtimestamp(v) for v in data], dtype=object)
- elif kind in (u('integer'), u('float')):
+ elif kind in (u'integer', u'float'):
index = np.asarray(data)
- elif kind in (u('string')):
+ elif kind in (u'string'):
index = _unconvert_string_array(data, nan_rep=None, encoding=encoding,
errors=errors)
- elif kind == u('object'):
+ elif kind == u'object':
index = np.asarray(data[0])
else: # pragma: no cover
raise ValueError('unrecognized index type %s' % kind)
@@ -4621,11 +4621,11 @@ def _unconvert_index(data, kind, encoding=None, errors='strict'):
def _unconvert_index_legacy(data, kind, legacy=False, encoding=None,
errors='strict'):
kind = _ensure_decoded(kind)
- if kind == u('datetime'):
+ if kind == u'datetime':
index = to_datetime(data)
- elif kind in (u('integer')):
+ elif kind in (u'integer'):
index = np.asarray(data, dtype=object)
- elif kind in (u('string')):
+ elif kind in (u'string'):
index = _unconvert_string_array(data, nan_rep=None, encoding=encoding,
errors=errors)
else: # pragma: no cover
@@ -4730,7 +4730,7 @@ def _get_converter(kind, encoding, errors):
def _need_convert(kind):
kind = _ensure_decoded(kind)
- if kind in (u('datetime'), u('datetime64'), u('string')):
+ if kind in (u'datetime', u'datetime64', u'string'):
return True
return False
| - [x] towards #22122 ( test files still remaining for E741)
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
Import optimiser, makes things alphabetical and also removes unused eg, `Float64Index`, in `packers.py`. Do people prefer this or not? | https://api.github.com/repos/pandas-dev/pandas/pulls/22913 | 2018-09-30T19:20:07Z | 2018-10-09T15:43:40Z | 2018-10-09T15:43:40Z | 2018-10-09T19:34:29Z |
API/DEPR: 'periods' argument instead of 'n' for PeriodIndex.shift() | diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt
index a1a0857fe6365..62a2a358d3ba9 100644
--- a/doc/source/whatsnew/v0.24.0.txt
+++ b/doc/source/whatsnew/v0.24.0.txt
@@ -637,7 +637,7 @@ Deprecations
- :meth:`Series.str.cat` has deprecated using arbitrary list-likes *within* list-likes. A list-like container may still contain
many ``Series``, ``Index`` or 1-dimensional ``np.ndarray``, or alternatively, only scalar values. (:issue:`21950`)
- :meth:`FrozenNDArray.searchsorted` has deprecated the ``v`` parameter in favor of ``value`` (:issue:`14645`)
-- :func:`DatetimeIndex.shift` now accepts ``periods`` argument instead of ``n`` for consistency with :func:`Index.shift` and :func:`Series.shift`. Using ``n`` throws a deprecation warning (:issue:`22458`)
+- :func:`DatetimeIndex.shift` and :func:`PeriodIndex.shift` now accept ``periods`` argument instead of ``n`` for consistency with :func:`Index.shift` and :func:`Series.shift`. Using ``n`` throws a deprecation warning (:issue:`22458`, :issue:`22912`)
.. _whatsnew_0240.prior_deprecations:
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 1ce60510c6a69..e4ace2bfe1509 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -552,6 +552,7 @@ def shift(self, periods, freq=None):
See Also
--------
Index.shift : Shift values of Index.
+ PeriodIndex.shift : Shift values of PeriodIndex.
"""
return self._time_shift(periods=periods, freq=freq)
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index 92803ab5f52e0..96a18a628fcf9 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -14,7 +14,7 @@
from pandas._libs.tslibs.fields import isleapyear_arr
from pandas import compat
-from pandas.util._decorators import cache_readonly
+from pandas.util._decorators import (cache_readonly, deprecate_kwarg)
from pandas.core.dtypes.common import (
is_integer_dtype, is_float_dtype, is_period_dtype)
@@ -319,20 +319,32 @@ def _add_delta(self, other):
ordinal_delta = self._maybe_convert_timedelta(other)
return self._time_shift(ordinal_delta)
- def shift(self, n):
+ @deprecate_kwarg(old_arg_name='n', new_arg_name='periods')
+ def shift(self, periods):
"""
- Specialized shift which produces an Period Array/Index
+ Shift index by desired number of increments.
+
+ This method is for shifting the values of period indexes
+ by a specified time increment.
Parameters
----------
- n : int
- Periods to shift by
+ periods : int
+ Number of periods (or increments) to shift by,
+ can be positive or negative.
+
+ .. versionchanged:: 0.24.0
Returns
-------
- shifted : Period Array/Index
+ pandas.PeriodIndex
+ Shifted index.
+
+ See Also
+ --------
+ DatetimeIndex.shift : Shift values of DatetimeIndex.
"""
- return self._time_shift(n)
+ return self._time_shift(periods)
def _time_shift(self, n):
values = self._ndarray_values + n * self.freq.n
diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index 8de52fbfa79f0..0b5a10283946c 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -8304,6 +8304,7 @@ def mask(self, cond, other=np.nan, inplace=False, axis=None, level=None,
--------
Index.shift : Shift values of Index.
DatetimeIndex.shift : Shift values of DatetimeIndex.
+ PeriodIndex.shift : Shift values of PeriodIndex.
Notes
-----
diff --git a/pandas/tests/indexes/period/test_arithmetic.py b/pandas/tests/indexes/period/test_arithmetic.py
index 3380a1ebc58dc..d9cbb3ea27d7b 100644
--- a/pandas/tests/indexes/period/test_arithmetic.py
+++ b/pandas/tests/indexes/period/test_arithmetic.py
@@ -97,3 +97,12 @@ def test_shift_gh8083(self):
expected = PeriodIndex(['2013-01-02', '2013-01-03', '2013-01-04',
'2013-01-05', '2013-01-06'], freq='D')
tm.assert_index_equal(result, expected)
+
+ def test_shift_periods(self):
+ # GH #22458 : argument 'n' was deprecated in favor of 'periods'
+ idx = PeriodIndex(freq='A', start='1/1/2001', end='12/1/2009')
+ tm.assert_index_equal(idx.shift(periods=0), idx)
+ tm.assert_index_equal(idx.shift(0), idx)
+ with tm.assert_produces_warning(FutureWarning,
+ check_stacklevel=True):
+ tm.assert_index_equal(idx.shift(n=0), idx)
| - [x] closes #22458
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
In order to be consistent with `Index.shift` & `Series.shift` & `DatetimeIndex.shift`, `n` argument was deprecated in favor of `periods`.
```
In [2]: idx = pd.PeriodIndex(freq='A', start='1/1/2001', end='12/1/2009')
In [3]: idx
Out[3]:
PeriodIndex(['2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008',
'2009'],
dtype='period[A-DEC]', freq='A-DEC')
In [4]: idx.shift(1)
Out[4]:
PeriodIndex(['2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009',
'2010'],
dtype='period[A-DEC]', freq='A-DEC')
In [5]: idx.shift(periods=1)
Out[5]:
PeriodIndex(['2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009',
'2010'],
dtype='period[A-DEC]', freq='A-DEC')
In [6]: idx.shift(n=1)
//anaconda/envs/pandas_dev/bin/ipython:1: FutureWarning: the 'n' keyword is deprecated, use 'periods' instead
#!//anaconda/envs/pandas_dev/bin/python
Out[6]:
PeriodIndex(['2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009',
'2010'],
dtype='period[A-DEC]', freq='A-DEC')
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/22912 | 2018-09-30T18:54:54Z | 2018-10-08T19:13:20Z | 2018-10-08T19:13:20Z | 2018-10-08T20:27:15Z |
DEPR/CLN: Clean up to_dense signature deprecations | diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt
index 16f0b9ee99909..83704987abdb7 100644
--- a/doc/source/whatsnew/v0.24.0.txt
+++ b/doc/source/whatsnew/v0.24.0.txt
@@ -440,7 +440,7 @@ In addition to these API breaking changes, many :ref:`performance improvements a
Raise ValueError in ``DataFrame.to_dict(orient='index')``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-Bug in :func:`DataFrame.to_dict` raises ``ValueError`` when used with
+Bug in :func:`DataFrame.to_dict` raises ``ValueError`` when used with
``orient='index'`` and a non-unique index instead of losing data (:issue:`22801`)
.. ipython:: python
@@ -448,7 +448,7 @@ Bug in :func:`DataFrame.to_dict` raises ``ValueError`` when used with
df = pd.DataFrame({'a': [1, 2], 'b': [0.5, 0.75]}, index=['A', 'A'])
df
-
+
df.to_dict(orient='index')
.. _whatsnew_0240.api.datetimelike.normalize:
@@ -747,6 +747,8 @@ Removal of prior version deprecations/changes
- :meth:`Categorical.searchsorted` and :meth:`Series.searchsorted` have renamed the ``v`` argument to ``value`` (:issue:`14645`)
- :meth:`TimedeltaIndex.searchsorted`, :meth:`DatetimeIndex.searchsorted`, and :meth:`PeriodIndex.searchsorted` have renamed the ``key`` argument to ``value`` (:issue:`14645`)
- Removal of the previously deprecated module ``pandas.json`` (:issue:`19944`)
+- :meth:`SparseArray.get_values` and :meth:`SparseArray.to_dense` have dropped the ``fill`` parameter (:issue:`14686`)
+- :meth:`SparseSeries.to_dense` has dropped the ``sparse_only`` parameter (:issue:`14686`)
.. _whatsnew_0240.performance:
diff --git a/pandas/core/arrays/sparse.py b/pandas/core/arrays/sparse.py
index f5e54e4425444..8588d377b6516 100644
--- a/pandas/core/arrays/sparse.py
+++ b/pandas/core/arrays/sparse.py
@@ -1249,31 +1249,19 @@ def map(self, mapper):
return type(self)(sp_values, sparse_index=self.sp_index,
fill_value=fill_value)
- def get_values(self, fill=None):
- """ return a dense representation """
- # TODO: deprecate for to_dense?
- return self.to_dense(fill=fill)
-
- def to_dense(self, fill=None):
+ def to_dense(self):
"""
Convert SparseArray to a NumPy array.
- Parameters
- ----------
- fill: float, default None
- .. deprecated:: 0.20.0
- This argument is not respected by this function.
-
Returns
-------
arr : NumPy array
"""
- if fill is not None:
- warnings.warn(("The 'fill' parameter has been deprecated and "
- "will be removed in a future version."),
- FutureWarning, stacklevel=2)
return np.asarray(self, dtype=self.sp_values.dtype)
+ # TODO: Look into deprecating this in favor of `to_dense`.
+ get_values = to_dense
+
# ------------------------------------------------------------------------
# IO
# ------------------------------------------------------------------------
diff --git a/pandas/core/sparse/series.py b/pandas/core/sparse/series.py
index 35ddd623878d0..5a747c6e4b1d1 100644
--- a/pandas/core/sparse/series.py
+++ b/pandas/core/sparse/series.py
@@ -439,33 +439,16 @@ def _set_values(self, key, value):
kind=self.kind)
self._data = SingleBlockManager(values, self.index)
- def to_dense(self, sparse_only=False):
+ def to_dense(self):
"""
Convert SparseSeries to a Series.
- Parameters
- ----------
- sparse_only : bool, default False
- .. deprecated:: 0.20.0
- This argument will be removed in a future version.
-
- If True, return just the non-sparse values, or the dense version
- of `self.values` if False.
-
Returns
-------
s : Series
"""
- if sparse_only:
- warnings.warn(("The 'sparse_only' parameter has been deprecated "
- "and will be removed in a future version."),
- FutureWarning, stacklevel=2)
- int_index = self.sp_index.to_int_index()
- index = self.index.take(int_index.indices)
- return Series(self.sp_values, index=index, name=self.name)
- else:
- return Series(self.values.to_dense(), index=self.index,
- name=self.name)
+ return Series(self.values.to_dense(), index=self.index,
+ name=self.name)
@property
def density(self):
diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py
index 0257d996228df..440dbc3de83bb 100644
--- a/pandas/tests/arrays/sparse/test_array.py
+++ b/pandas/tests/arrays/sparse/test_array.py
@@ -533,33 +533,21 @@ def test_shape(self, data, shape, dtype):
out = SparseArray(data, dtype=dtype)
assert out.shape == shape
- def test_to_dense(self):
- vals = np.array([1, np.nan, np.nan, 3, np.nan])
- res = SparseArray(vals).to_dense()
- tm.assert_numpy_array_equal(res, vals)
-
- res = SparseArray(vals, fill_value=0).to_dense()
- tm.assert_numpy_array_equal(res, vals)
-
- vals = np.array([1, np.nan, 0, 3, 0])
- res = SparseArray(vals).to_dense()
- tm.assert_numpy_array_equal(res, vals)
-
- res = SparseArray(vals, fill_value=0).to_dense()
- tm.assert_numpy_array_equal(res, vals)
-
- vals = np.array([np.nan, np.nan, np.nan, np.nan, np.nan])
- res = SparseArray(vals).to_dense()
- tm.assert_numpy_array_equal(res, vals)
-
- res = SparseArray(vals, fill_value=0).to_dense()
+ @pytest.mark.parametrize("vals", [
+ [np.nan, np.nan, np.nan, np.nan, np.nan],
+ [1, np.nan, np.nan, 3, np.nan],
+ [1, np.nan, 0, 3, 0],
+ ])
+ @pytest.mark.parametrize("method", ["to_dense", "get_values"])
+ @pytest.mark.parametrize("fill_value", [None, 0])
+ def test_dense_repr(self, vals, fill_value, method):
+ vals = np.array(vals)
+ arr = SparseArray(vals, fill_value=fill_value)
+ dense_func = getattr(arr, method)
+
+ res = dense_func()
tm.assert_numpy_array_equal(res, vals)
- # see gh-14647
- with tm.assert_produces_warning(FutureWarning,
- check_stacklevel=False):
- SparseArray(vals).to_dense(fill=2)
-
def test_getitem(self):
def _checkit(i):
assert_almost_equal(self.arr[i], self.arr.values[i])
diff --git a/pandas/tests/sparse/series/test_series.py b/pandas/tests/sparse/series/test_series.py
index 22fca1e6b05e8..6a5821519866e 100644
--- a/pandas/tests/sparse/series/test_series.py
+++ b/pandas/tests/sparse/series/test_series.py
@@ -192,15 +192,6 @@ def test_sparse_to_dense(self):
series = self.bseries.to_dense()
tm.assert_series_equal(series, Series(arr, name='bseries'))
- # see gh-14647
- with tm.assert_produces_warning(FutureWarning,
- check_stacklevel=False):
- series = self.bseries.to_dense(sparse_only=True)
-
- indexer = np.isfinite(arr)
- exp = Series(arr[indexer], index=index[indexer], name='bseries')
- tm.assert_series_equal(series, exp)
-
series = self.iseries.to_dense()
tm.assert_series_equal(series, Series(arr, name='iseries'))
| Also deprecate `fill` in `.get_values` because its parameter was being passed to `.to_dense`, which
no longer accepts the `fill` parameter.
xref #14686.
| https://api.github.com/repos/pandas-dev/pandas/pulls/22910 | 2018-09-30T18:43:56Z | 2018-10-18T17:30:04Z | 2018-10-18T17:30:04Z | 2018-10-18T18:53:01Z |
TST: solve test failure on 32bit systems | diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py
index 99a909849822b..a753e925b0ed8 100644
--- a/pandas/tests/indexes/test_base.py
+++ b/pandas/tests/indexes/test_base.py
@@ -1379,7 +1379,7 @@ def test_get_indexer_with_NA_values(self, unique_nulls_fixture,
index = pd.Index(arr, dtype=np.object)
result = index.get_indexer([unique_nulls_fixture,
unique_nulls_fixture2, 'Unknown'])
- expected = np.array([0, 1, -1], dtype=np.int64)
+ expected = np.array([0, 1, -1], dtype=np.intp)
tm.assert_numpy_array_equal(result, expected)
@pytest.mark.parametrize("method", [None, 'pad', 'backfill', 'nearest'])
| - [x] closes #22813
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
#22296 introduced a test, where ``dtype=np.int64`` was used, but ``np.intp`` is needed for the test to pass on 32bit systems also. This fixes that.
After this PR, the pandas test suite passes with no failures on my 32bit python installation on Windows 10.
| https://api.github.com/repos/pandas-dev/pandas/pulls/22908 | 2018-09-30T16:03:58Z | 2018-10-11T11:21:39Z | 2018-10-11T11:21:39Z | 2018-10-27T08:15:48Z |
STYLE: Added explicit exceptions | diff --git a/pandas/compat/pickle_compat.py b/pandas/compat/pickle_compat.py
index c1a9a9fc1ed13..713a5b1120beb 100644
--- a/pandas/compat/pickle_compat.py
+++ b/pandas/compat/pickle_compat.py
@@ -33,7 +33,7 @@ def load_reduce(self):
cls = args[0]
stack[-1] = object.__new__(cls)
return
- except:
+ except TypeError:
pass
# try to re-encode the arguments
@@ -44,7 +44,7 @@ def load_reduce(self):
try:
stack[-1] = func(*args)
return
- except:
+ except TypeError:
pass
# unknown exception, re-raise
@@ -182,7 +182,7 @@ def load_newobj_ex(self):
try:
Unpickler.dispatch[pkl.NEWOBJ_EX[0]] = load_newobj_ex
-except:
+except (AttributeError, KeyError):
pass
@@ -210,5 +210,5 @@ def load(fh, encoding=None, compat=False, is_verbose=False):
up.is_verbose = is_verbose
return up.load()
- except:
+ except (ValueError, TypeError):
raise
diff --git a/pandas/tseries/holiday.py b/pandas/tseries/holiday.py
index b9c89c4e314f9..0497a827e2e1b 100644
--- a/pandas/tseries/holiday.py
+++ b/pandas/tseries/holiday.py
@@ -294,7 +294,7 @@ def _apply_rule(self, dates):
def register(cls):
try:
name = cls.name
- except:
+ except AttributeError:
name = cls.__name__
holiday_calendars[name] = cls
@@ -426,7 +426,7 @@ def merge_class(base, other):
"""
try:
other = other.rules
- except:
+ except AttributeError:
pass
if not isinstance(other, list):
@@ -435,7 +435,7 @@ def merge_class(base, other):
try:
base = base.rules
- except:
+ except AttributeError:
pass
if not isinstance(base, list):
diff --git a/pandas/util/_print_versions.py b/pandas/util/_print_versions.py
index 5600834f3b615..03fc82a3acef5 100644
--- a/pandas/util/_print_versions.py
+++ b/pandas/util/_print_versions.py
@@ -21,7 +21,7 @@ def get_sys_info():
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
so, serr = pipe.communicate()
- except:
+ except (OSError, ValueError):
pass
else:
if pipe.returncode == 0:
@@ -50,7 +50,7 @@ def get_sys_info():
("LANG", "{lang}".format(lang=os.environ.get('LANG', "None"))),
("LOCALE", '.'.join(map(str, locale.getlocale()))),
])
- except:
+ except (KeyError, ValueError):
pass
return blob
@@ -108,7 +108,7 @@ def show_versions(as_json=False):
mod = importlib.import_module(modname)
ver = ver_f(mod)
deps_blob.append((modname, ver))
- except:
+ except ImportError:
deps_blob.append((modname, None))
if (as_json):
diff --git a/pandas/util/_validators.py b/pandas/util/_validators.py
index a96563051e7de..e51e0c88e5b95 100644
--- a/pandas/util/_validators.py
+++ b/pandas/util/_validators.py
@@ -59,7 +59,7 @@ def _check_for_default_values(fname, arg_val_dict, compat_args):
# could not compare them directly, so try comparison
# using the 'is' operator
- except:
+ except ValueError:
match = (arg_val_dict[key] is compat_args[key])
if not match:
| - [x] xref #22877
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [x] whatsnew entry
Fixed the following bare excepts:
> pandas/compat/pickle_compat.py:36:13: E722 do not use bare except'
> pandas/compat/pickle_compat.py:47:13: E722 do not use bare except'
> pandas/compat/pickle_compat.py:185:1: E722 do not use bare except'
> pandas/compat/pickle_compat.py:213:5: E722 do not use bare except'
> pandas/tseries/holiday.py:297:5: E722 do not use bare except'
> pandas/tseries/holiday.py:429:9: E722 do not use bare except'
> pandas/tseries/holiday.py:438:9: E722 do not use bare except'
> pandas/util/_print_versions.py:24:9: E722 do not use bare except'
> pandas/util/_print_versions.py:53:5: E722 do not use bare except'
> pandas/util/_print_versions.py:111:9: E722 do not use bare except'
> pandas/util/_validators.py:62:9: E722 do not use bare except'
| https://api.github.com/repos/pandas-dev/pandas/pulls/22907 | 2018-09-30T08:53:53Z | 2018-10-01T11:52:56Z | 2018-10-01T11:52:56Z | 2018-10-01T14:57:19Z |
DOC: #22899, Fixed docstring of itertuples in pandas/core/frame.py | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index d5b273f37a3a2..8c6b216ad196e 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -883,43 +883,66 @@ def iterrows(self):
def itertuples(self, index=True, name="Pandas"):
"""
- Iterate over DataFrame rows as namedtuples, with index value as first
- element of the tuple.
+ Iterate over DataFrame rows as namedtuples.
Parameters
----------
- index : boolean, default True
+ index : bool, default True
If True, return the index as the first element of the tuple.
- name : string, default "Pandas"
+ name : str, default "Pandas"
The name of the returned namedtuples or None to return regular
tuples.
+ Yields
+ -------
+ collections.namedtuple
+ Yields a namedtuple for each row in the DataFrame with the first
+ field possibly being the index and following fields being the
+ column values.
+
Notes
-----
The column names will be renamed to positional names if they are
invalid Python identifiers, repeated, or start with an underscore.
With a large number of columns (>255), regular tuples are returned.
- See also
+ See Also
--------
- iterrows : Iterate over DataFrame rows as (index, Series) pairs.
- iteritems : Iterate over (column name, Series) pairs.
+ DataFrame.iterrows : Iterate over DataFrame rows as (index, Series)
+ pairs.
+ DataFrame.iteritems : Iterate over (column name, Series) pairs.
Examples
--------
-
- >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [0.1, 0.2]},
- index=['a', 'b'])
+ >>> df = pd.DataFrame({'num_legs': [4, 2], 'num_wings': [0, 2]},
+ ... index=['dog', 'hawk'])
>>> df
- col1 col2
- a 1 0.1
- b 2 0.2
+ num_legs num_wings
+ dog 4 0
+ hawk 2 2
>>> for row in df.itertuples():
... print(row)
...
- Pandas(Index='a', col1=1, col2=0.10000000000000001)
- Pandas(Index='b', col1=2, col2=0.20000000000000001)
+ Pandas(Index='dog', num_legs=4, num_wings=0)
+ Pandas(Index='hawk', num_legs=2, num_wings=2)
+
+ By setting the `index` parameter to False we can remove the index
+ as the first element of the tuple:
+
+ >>> for row in df.itertuples(index=False):
+ ... print(row)
+ ...
+ Pandas(num_legs=4, num_wings=0)
+ Pandas(num_legs=2, num_wings=2)
+
+ With the `name` parameter set we set a custom name for the yielded
+ namedtuples:
+ >>> for row in df.itertuples(name='Animal'):
+ ... print(row)
+ ...
+ Animal(Index='dog', num_legs=4, num_wings=0)
+ Animal(Index='hawk', num_legs=2, num_wings=2)
"""
arrays = []
fields = []
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
#22899
I went ahead and followed the docstring conventions mentioned here:
https://pandas.pydata.org/pandas-docs/stable/contributing_docstring.html
The fixes I made were for the following errors:
<img width="891" alt="screen shot 2018-09-29 at 19 17 59" src="https://user-images.githubusercontent.com/16315857/46252338-740df400-c41c-11e8-9c29-ff955c9b9705.png">
<img width="618" alt="screen shot 2018-09-29 at 19 18 08" src="https://user-images.githubusercontent.com/16315857/46252339-76704e00-c41c-11e8-89d5-adab168dc329.png">
- Fixed whitespace between closing line and end of docstring
- Converted summary into single line
- Added `Returns` section (Not sure if done correctly!)
- Fixed examples to pass test by adding `...` at line 914
- Fixed namedtuple return values at 922 and 923
Please let me know if there are any issues and I will try my best to fix them ASAP.
Thank you!~ | https://api.github.com/repos/pandas-dev/pandas/pulls/22902 | 2018-09-30T02:21:18Z | 2018-10-07T22:40:48Z | 2018-10-07T22:40:48Z | 2018-10-07T22:40:51Z |
CLN GH22873 Replace base excepts in pandas/core | diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt
index 851c1a3fbd6e9..f83185173c3e3 100644
--- a/doc/source/whatsnew/v0.24.0.txt
+++ b/doc/source/whatsnew/v0.24.0.txt
@@ -834,4 +834,3 @@ Other
- :meth:`DataFrame.nlargest` and :meth:`DataFrame.nsmallest` now returns the correct n values when keep != 'all' also when tied on the first columns (:issue:`22752`)
- :meth:`~pandas.io.formats.style.Styler.bar` now also supports tablewise application (in addition to rowwise and columnwise) with ``axis=None`` and setting clipping range with ``vmin`` and ``vmax`` (:issue:`21548` and :issue:`21526`). ``NaN`` values are also handled properly.
- Logical operations ``&, |, ^`` between :class:`Series` and :class:`Index` will no longer raise ``ValueError`` (:issue:`22092`)
--
diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py
index 2bd1b0c5b3507..e08df3e340138 100644
--- a/pandas/core/computation/pytables.py
+++ b/pandas/core/computation/pytables.py
@@ -411,7 +411,7 @@ def visit_Subscript(self, node, **kwargs):
slobj = self.visit(node.slice)
try:
value = value.value
- except:
+ except AttributeError:
pass
try:
diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index e2b9e246aee50..5f0b71d4505c2 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -467,7 +467,7 @@ def is_timedelta64_dtype(arr_or_dtype):
return False
try:
tipo = _get_dtype_type(arr_or_dtype)
- except:
+ except (TypeError, ValueError, SyntaxError):
return False
return issubclass(tipo, np.timedelta64)
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py
index d879ded4f0f09..fe5cc9389a8ba 100644
--- a/pandas/core/dtypes/dtypes.py
+++ b/pandas/core/dtypes/dtypes.py
@@ -358,11 +358,11 @@ def construct_from_string(cls, string):
try:
if string == 'category':
return cls()
- except:
+ else:
+ raise TypeError("cannot construct a CategoricalDtype")
+ except AttributeError:
pass
- raise TypeError("cannot construct a CategoricalDtype")
-
@staticmethod
def validate_ordered(ordered):
"""
@@ -519,7 +519,7 @@ def __new__(cls, unit=None, tz=None):
if m is not None:
unit = m.groupdict()['unit']
tz = m.groupdict()['tz']
- except:
+ except TypeError:
raise ValueError("could not construct DatetimeTZDtype")
elif isinstance(unit, compat.string_types):
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index b4e8b4e3a6bec..dfd0b1624f9d6 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -3260,7 +3260,7 @@ def _ensure_valid_index(self, value):
if not len(self.index) and is_list_like(value):
try:
value = Series(value)
- except:
+ except (ValueError, NotImplementedError, TypeError):
raise ValueError('Cannot set a frame with no defined index '
'and a value that cannot be converted to a '
'Series')
@@ -7747,7 +7747,7 @@ def convert(v):
values = np.array([convert(v) for v in values])
else:
values = convert(values)
- except:
+ except (ValueError, TypeError):
values = convert(values)
else:
diff --git a/pandas/core/indexes/frozen.py b/pandas/core/indexes/frozen.py
index 5a37e03b700f9..289970aaf3a82 100644
--- a/pandas/core/indexes/frozen.py
+++ b/pandas/core/indexes/frozen.py
@@ -139,7 +139,7 @@ def searchsorted(self, value, side="left", sorter=None):
# xref: https://github.com/numpy/numpy/issues/5370
try:
value = self.dtype.type(value)
- except:
+ except ValueError:
pass
return super(FrozenNDArray, self).searchsorted(
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 3e6b934e1e863..119a607fc0e68 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -6,6 +6,7 @@
import numpy as np
from pandas._libs import algos as libalgos, index as libindex, lib, Timestamp
+from pandas._libs import tslibs
from pandas.compat import range, zip, lrange, lzip, map
from pandas.compat.numpy import function as nv
@@ -1002,12 +1003,13 @@ def _try_mi(k):
return _try_mi(key)
except (KeyError):
raise
- except:
+ except (IndexError, ValueError, TypeError):
pass
try:
return _try_mi(Timestamp(key))
- except:
+ except (KeyError, TypeError,
+ IndexError, ValueError, tslibs.OutOfBoundsDatetime):
pass
raise InvalidIndexError(key)
@@ -1686,7 +1688,7 @@ def append(self, other):
# if all(isinstance(x, MultiIndex) for x in other):
try:
return MultiIndex.from_tuples(new_tuples, names=self.names)
- except:
+ except (TypeError, IndexError):
return Index(new_tuples)
def argsort(self, *args, **kwargs):
@@ -2315,7 +2317,7 @@ def maybe_droplevels(indexer, levels, drop_level):
for i in sorted(levels, reverse=True):
try:
new_index = new_index.droplevel(i)
- except:
+ except ValueError:
# no dropping here
return orig_index
@@ -2818,7 +2820,7 @@ def _convert_can_do_setop(self, other):
msg = 'other must be a MultiIndex or a list of tuples'
try:
other = MultiIndex.from_tuples(other)
- except:
+ except TypeError:
raise TypeError(msg)
else:
result_names = self.names if self.names == other.names else None
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index b63f874abff85..150518aadcfd9 100755
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -2146,7 +2146,7 @@ def _getitem_tuple(self, tup):
self._has_valid_tuple(tup)
try:
return self._getitem_lowerdim(tup)
- except:
+ except IndexingError:
pass
retval = self.obj
@@ -2705,13 +2705,13 @@ def maybe_droplevels(index, key):
for _ in key:
try:
index = index.droplevel(0)
- except:
+ except ValueError:
# we have dropped too much, so back out
return original_index
else:
try:
index = index.droplevel(0)
- except:
+ except ValueError:
pass
return index
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index 6576db9f642a6..0e57dd33b1c4e 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -666,7 +666,7 @@ def _astype(self, dtype, copy=False, errors='raise', values=None,
newb = make_block(values, placement=self.mgr_locs,
klass=klass, ndim=self.ndim)
- except:
+ except Exception: # noqa: E722
if errors == 'raise':
raise
newb = self.copy() if copy else self
@@ -1142,7 +1142,7 @@ def check_int_bool(self, inplace):
# a fill na type method
try:
m = missing.clean_fill_method(method)
- except:
+ except ValueError:
m = None
if m is not None:
@@ -1157,7 +1157,7 @@ def check_int_bool(self, inplace):
# try an interp method
try:
m = missing.clean_interp_method(method, **kwargs)
- except:
+ except ValueError:
m = None
if m is not None:
@@ -2438,7 +2438,7 @@ def set(self, locs, values, check=False):
try:
if (self.values[locs] == values).all():
return
- except:
+ except (IndexError, ValueError):
pass
try:
self.values[locs] = values
@@ -3172,7 +3172,7 @@ def _astype(self, dtype, copy=False, errors='raise', values=None,
def __len__(self):
try:
return self.sp_index.length
- except:
+ except AttributeError:
return 0
def copy(self, deep=True, mgr=None):
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py
index 7619d47cbc8f9..232d030da7f1e 100644
--- a/pandas/core/nanops.py
+++ b/pandas/core/nanops.py
@@ -503,7 +503,8 @@ def reduction(values, axis=None, skipna=True):
try:
result = getattr(values, meth)(axis, dtype=dtype_max)
result.fill(np.nan)
- except:
+ except (AttributeError, TypeError,
+ ValueError, np.core._internal.AxisError):
result = np.nan
else:
result = getattr(values, meth)(axis)
@@ -815,7 +816,7 @@ def _ensure_numeric(x):
elif is_object_dtype(x):
try:
x = x.astype(np.complex128)
- except:
+ except (TypeError, ValueError):
x = x.astype(np.float64)
else:
if not np.any(x.imag):
diff --git a/pandas/core/ops.py b/pandas/core/ops.py
index 70fe7de0a973e..ad187b08e0742 100644
--- a/pandas/core/ops.py
+++ b/pandas/core/ops.py
@@ -1545,7 +1545,8 @@ def na_op(x, y):
y = bool(y)
try:
result = libops.scalar_binop(x, y, op)
- except:
+ except (TypeError, ValueError, AttributeError,
+ OverflowError, NotImplementedError):
raise TypeError("cannot compare a dtyped [{dtype}] array "
"with a scalar of type [{typ}]"
.format(dtype=x.dtype,
diff --git a/pandas/core/sparse/array.py b/pandas/core/sparse/array.py
index eb07e5ef6c85f..186a2490a5f2e 100644
--- a/pandas/core/sparse/array.py
+++ b/pandas/core/sparse/array.py
@@ -306,7 +306,7 @@ def __setstate__(self, state):
def __len__(self):
try:
return self.sp_index.length
- except:
+ except AttributeError:
return 0
def __unicode__(self):
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py
index 4a5290a90313d..eb8d2b0b6c809 100644
--- a/pandas/core/tools/datetimes.py
+++ b/pandas/core/tools/datetimes.py
@@ -244,7 +244,7 @@ def _convert_listlike_datetimes(arg, box, format, name=None, tz=None,
if format == '%Y%m%d':
try:
result = _attempt_YYYYMMDD(arg, errors=errors)
- except:
+ except (ValueError, TypeError, tslibs.OutOfBoundsDatetime):
raise ValueError("cannot convert the input to "
"'%Y%m%d' date format")
@@ -334,7 +334,7 @@ def _adjust_to_origin(arg, origin, unit):
raise ValueError("unit must be 'D' for origin='julian'")
try:
arg = arg - j0
- except:
+ except TypeError:
raise ValueError("incompatible 'arg' type for given "
"'origin'='julian'")
@@ -731,21 +731,21 @@ def calc_with_mask(carg, mask):
# try intlike / strings that are ints
try:
return calc(arg.astype(np.int64))
- except:
+ except ValueError:
pass
# a float with actual np.nan
try:
carg = arg.astype(np.float64)
return calc_with_mask(carg, notna(carg))
- except:
+ except ValueError:
pass
# string with NaN-like
try:
mask = ~algorithms.isin(arg, list(tslib.nat_strings))
return calc_with_mask(arg, mask)
- except:
+ except ValueError:
pass
return None
diff --git a/pandas/core/window.py b/pandas/core/window.py
index 5cdf62d5a5537..4281d66a640e3 100644
--- a/pandas/core/window.py
+++ b/pandas/core/window.py
@@ -2504,7 +2504,7 @@ def _offset(window, center):
offset = (window - 1) / 2. if center else 0
try:
return int(offset)
- except:
+ except TypeError:
return offset.astype(int)
| This cleaning fix adds specific exception classes to bare except statements to correct PEP8 linting errors. The classes were chosen by a mixture of educated guessing (i.e. if a statement gets the `length` property, it might raise an `AttributeError`), trying out functions on known edge cases (i.e. giving a datetime input that is too large gives `tslibs.OutOfBoundsDatetime`), and inspecting functions in the `try` block to see what kind of errors they raise.
- [x] xref #22873
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry | https://api.github.com/repos/pandas-dev/pandas/pulls/22901 | 2018-09-30T00:08:17Z | 2018-10-02T21:16:26Z | 2018-10-02T21:16:26Z | 2018-10-03T13:15:40Z |
DOC: updated the docstring of Series.dot | diff --git a/pandas/core/series.py b/pandas/core/series.py
index a613b22ea9046..141d738d0c3bf 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2080,16 +2080,53 @@ def autocorr(self, lag=1):
def dot(self, other):
"""
- Matrix multiplication with DataFrame or inner-product with Series
- objects. Can also be called using `self @ other` in Python >= 3.5.
+ Compute the dot product between the Series and the columns of other.
+
+ This method computes the dot product between the Series and another
+ one, or the Series and each columns of a DataFrame, or the Series and
+ each columns of an array.
+
+ It can also be called using `self @ other` in Python >= 3.5.
Parameters
----------
- other : Series or DataFrame
+ other : Series, DataFrame or array-like
+ The other object to compute the dot product with its columns.
Returns
-------
- dot_product : scalar or Series
+ scalar, Series or numpy.ndarray
+ Return the dot product of the Series and other if other is a
+ Series, the Series of the dot product of Series and each rows of
+ other if other is a DataFrame or a numpy.ndarray between the Series
+ and each columns of the numpy array.
+
+ See Also
+ --------
+ DataFrame.dot: Compute the matrix product with the DataFrame.
+ Series.mul: Multiplication of series and other, element-wise.
+
+ Notes
+ -----
+ The Series and other has to share the same index if other is a Series
+ or a DataFrame.
+
+ Examples
+ --------
+ >>> s = pd.Series([0, 1, 2, 3])
+ >>> other = pd.Series([-1, 2, -3, 4])
+ >>> s.dot(other)
+ 8
+ >>> s @ other
+ 8
+ >>> df = pd.DataFrame([[0 ,1], [-2, 3], [4, -5], [6, 7]])
+ >>> s.dot(df)
+ 0 24
+ 1 14
+ dtype: int64
+ >>> arr = np.array([[0, 1], [-2, 3], [4, -5], [6, 7]])
+ >>> s.dot(arr)
+ array([24, 14])
"""
from pandas.core.frame import DataFrame
if isinstance(other, (Series, DataFrame)):
| - [ ] closes #xxxx
- [ ] tests added / passed
- [x ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/22890 | 2018-09-29T18:54:54Z | 2018-11-03T07:04:42Z | 2018-11-03T07:04:42Z | 2018-11-03T07:04:52Z |
BLD: minor break ci/requirements-optional-pip.txt | diff --git a/ci/requirements-optional-pip.txt b/ci/requirements-optional-pip.txt
index 2e1bf0ca22bcf..09ce8e59a3b46 100644
--- a/ci/requirements-optional-pip.txt
+++ b/ci/requirements-optional-pip.txt
@@ -14,7 +14,7 @@ lxml
matplotlib
nbsphinx
numexpr
-openpyxl=2.5.5
+openpyxl==2.5.5
pyarrow
pymysql
tables
@@ -28,4 +28,4 @@ statsmodels
xarray
xlrd
xlsxwriter
-xlwt
+xlwt
\ No newline at end of file
diff --git a/scripts/convert_deps.py b/scripts/convert_deps.py
index aabeb24a0c3c8..3ff157e0a0d7b 100755
--- a/scripts/convert_deps.py
+++ b/scripts/convert_deps.py
@@ -1,6 +1,7 @@
"""
Convert the conda environment.yaml to a pip requirements.txt
"""
+import re
import yaml
exclude = {'python=3'}
@@ -15,6 +16,7 @@
required = dev['dependencies']
required = [rename.get(dep, dep) for dep in required if dep not in exclude]
optional = [rename.get(dep, dep) for dep in optional if dep not in exclude]
+optional = [re.sub("(?<=[^<>])=", '==', dep) for dep in optional]
with open("ci/requirements_dev.txt", 'wt') as f:
| - [x] closes #22595
- [x] tests added / passed
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
- [ ] whatsnew entry
When adding optional dependencies, below error appears from
> Invalid requirement: 'openpyxl=2.5.5'
> = is not a valid operator. Did you mean == ?
To core dev, should we fix the version or simply specify lower bound (i.e. >=)? | https://api.github.com/repos/pandas-dev/pandas/pulls/22889 | 2018-09-29T18:27:48Z | 2018-09-30T13:59:47Z | 2018-09-30T13:59:47Z | 2018-09-30T14:08:55Z |
[ArrowStringArray] Use `utf8_is_*` functions from Apache Arrow if available | diff --git a/asv_bench/benchmarks/strings.py b/asv_bench/benchmarks/strings.py
index 76257e1b40f1a..5d9b1c135d7ae 100644
--- a/asv_bench/benchmarks/strings.py
+++ b/asv_bench/benchmarks/strings.py
@@ -50,91 +50,126 @@ def peakmem_cat_frame_construction(self, dtype):
class Methods:
- def setup(self):
- self.s = Series(tm.makeStringIndex(10 ** 5))
+ params = ["str", "string", "arrow_string"]
+ param_names = ["dtype"]
+
+ def setup(self, dtype):
+ from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401
+
+ try:
+ self.s = Series(tm.makeStringIndex(10 ** 5), dtype=dtype)
+ except ImportError:
+ raise NotImplementedError
- def time_center(self):
+ def time_center(self, dtype):
self.s.str.center(100)
- def time_count(self):
+ def time_count(self, dtype):
self.s.str.count("A")
- def time_endswith(self):
+ def time_endswith(self, dtype):
self.s.str.endswith("A")
- def time_extract(self):
+ def time_extract(self, dtype):
with warnings.catch_warnings(record=True):
self.s.str.extract("(\\w*)A(\\w*)")
- def time_findall(self):
+ def time_findall(self, dtype):
self.s.str.findall("[A-Z]+")
- def time_find(self):
+ def time_find(self, dtype):
self.s.str.find("[A-Z]+")
- def time_rfind(self):
+ def time_rfind(self, dtype):
self.s.str.rfind("[A-Z]+")
- def time_get(self):
+ def time_get(self, dtype):
self.s.str.get(0)
- def time_len(self):
+ def time_len(self, dtype):
self.s.str.len()
- def time_join(self):
+ def time_join(self, dtype):
self.s.str.join(" ")
- def time_match(self):
+ def time_match(self, dtype):
self.s.str.match("A")
- def time_normalize(self):
+ def time_normalize(self, dtype):
self.s.str.normalize("NFC")
- def time_pad(self):
+ def time_pad(self, dtype):
self.s.str.pad(100, side="both")
- def time_partition(self):
+ def time_partition(self, dtype):
self.s.str.partition("A")
- def time_rpartition(self):
+ def time_rpartition(self, dtype):
self.s.str.rpartition("A")
- def time_replace(self):
+ def time_replace(self, dtype):
self.s.str.replace("A", "\x01\x01")
- def time_translate(self):
+ def time_translate(self, dtype):
self.s.str.translate({"A": "\x01\x01"})
- def time_slice(self):
+ def time_slice(self, dtype):
self.s.str.slice(5, 15, 2)
- def time_startswith(self):
+ def time_startswith(self, dtype):
self.s.str.startswith("A")
- def time_strip(self):
+ def time_strip(self, dtype):
self.s.str.strip("A")
- def time_rstrip(self):
+ def time_rstrip(self, dtype):
self.s.str.rstrip("A")
- def time_lstrip(self):
+ def time_lstrip(self, dtype):
self.s.str.lstrip("A")
- def time_title(self):
+ def time_title(self, dtype):
self.s.str.title()
- def time_upper(self):
+ def time_upper(self, dtype):
self.s.str.upper()
- def time_lower(self):
+ def time_lower(self, dtype):
self.s.str.lower()
- def time_wrap(self):
+ def time_wrap(self, dtype):
self.s.str.wrap(10)
- def time_zfill(self):
+ def time_zfill(self, dtype):
self.s.str.zfill(10)
+ def time_isalnum(self, dtype):
+ self.s.str.isalnum()
+
+ def time_isalpha(self, dtype):
+ self.s.str.isalpha()
+
+ def time_isdecimal(self, dtype):
+ self.s.str.isdecimal()
+
+ def time_isdigit(self, dtype):
+ self.s.str.isdigit()
+
+ def time_islower(self, dtype):
+ self.s.str.islower()
+
+ def time_isnumeric(self, dtype):
+ self.s.str.isnumeric()
+
+ def time_isspace(self, dtype):
+ self.s.str.isspace()
+
+ def time_istitle(self, dtype):
+ self.s.str.istitle()
+
+ def time_isupper(self, dtype):
+ self.s.str.isupper()
+
class Repeat:
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index dd09ef4e585ce..55cb350d3d27c 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -39,6 +39,7 @@
from pandas.core import missing
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays.base import ExtensionArray
+from pandas.core.arrays.boolean import BooleanDtype
from pandas.core.indexers import (
check_array_indexer,
validate_indices,
@@ -758,6 +759,69 @@ def _str_map(self, f, na_value=None, dtype: Dtype | None = None):
# -> We don't know the result type. E.g. `.get` can return anything.
return lib.map_infer_mask(arr, f, mask.view("uint8"))
+ def _str_isalnum(self):
+ if hasattr(pc, "utf8_is_alnum"):
+ result = pc.utf8_is_alnum(self._data)
+ return BooleanDtype().__from_arrow__(result)
+ else:
+ return super()._str_isalnum()
+
+ def _str_isalpha(self):
+ if hasattr(pc, "utf8_is_alpha"):
+ result = pc.utf8_is_alpha(self._data)
+ return BooleanDtype().__from_arrow__(result)
+ else:
+ return super()._str_isalpha()
+
+ def _str_isdecimal(self):
+ if hasattr(pc, "utf8_is_decimal"):
+ result = pc.utf8_is_decimal(self._data)
+ return BooleanDtype().__from_arrow__(result)
+ else:
+ return super()._str_isdecimal()
+
+ def _str_isdigit(self):
+ if hasattr(pc, "utf8_is_digit"):
+ result = pc.utf8_is_digit(self._data)
+ return BooleanDtype().__from_arrow__(result)
+ else:
+ return super()._str_isdigit()
+
+ def _str_islower(self):
+ if hasattr(pc, "utf8_is_lower"):
+ result = pc.utf8_is_lower(self._data)
+ return BooleanDtype().__from_arrow__(result)
+ else:
+ return super()._str_islower()
+
+ def _str_isnumeric(self):
+ if hasattr(pc, "utf8_is_numeric"):
+ result = pc.utf8_is_numeric(self._data)
+ return BooleanDtype().__from_arrow__(result)
+ else:
+ return super()._str_isnumeric()
+
+ def _str_isspace(self):
+ if hasattr(pc, "utf8_is_space"):
+ result = pc.utf8_is_space(self._data)
+ return BooleanDtype().__from_arrow__(result)
+ else:
+ return super()._str_isspace()
+
+ def _str_istitle(self):
+ if hasattr(pc, "utf8_is_title"):
+ result = pc.utf8_is_title(self._data)
+ return BooleanDtype().__from_arrow__(result)
+ else:
+ return super()._str_istitle()
+
+ def _str_isupper(self):
+ if hasattr(pc, "utf8_is_upper"):
+ result = pc.utf8_is_upper(self._data)
+ return BooleanDtype().__from_arrow__(result)
+ else:
+ return super()._str_isupper()
+
def _str_lower(self):
return type(self)(pc.utf8_lower(self._data))
diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py
index 0b5613e302175..85a58d3d99795 100644
--- a/pandas/core/strings/accessor.py
+++ b/pandas/core/strings/accessor.py
@@ -3002,8 +3002,9 @@ def _result_dtype(arr):
# ideally we just pass `dtype=arr.dtype` unconditionally, but this fails
# when the list of values is empty.
from pandas.core.arrays.string_ import StringDtype
+ from pandas.core.arrays.string_arrow import ArrowStringDtype
- if isinstance(arr.dtype, StringDtype):
+ if isinstance(arr.dtype, (StringDtype, ArrowStringDtype)):
return arr.dtype.name
else:
return object
diff --git a/pandas/tests/strings/test_string_array.py b/pandas/tests/strings/test_string_array.py
index 02ccb3a930557..f90d219159c7e 100644
--- a/pandas/tests/strings/test_string_array.py
+++ b/pandas/tests/strings/test_string_array.py
@@ -13,19 +13,11 @@
)
-def test_string_array(nullable_string_dtype, any_string_method, request):
+def test_string_array(nullable_string_dtype, any_string_method):
method_name, args, kwargs = any_string_method
if method_name == "decode":
pytest.skip("decode requires bytes.")
- if nullable_string_dtype == "arrow_string" and method_name in {
- "extract",
- "extractall",
- }:
- reason = "extract/extractall does not yet dispatch to array"
- mark = pytest.mark.xfail(reason=reason)
- request.node.add_marker(mark)
-
data = ["a", "bb", np.nan, "ccc"]
a = Series(data, dtype=object)
b = Series(data, dtype=nullable_string_dtype)
@@ -93,15 +85,10 @@ def test_string_array_boolean_array(nullable_string_dtype, method, expected):
tm.assert_series_equal(result, expected)
-def test_string_array_extract(nullable_string_dtype, request):
+def test_string_array_extract(nullable_string_dtype):
# https://github.com/pandas-dev/pandas/issues/30969
# Only expand=False & multiple groups was failing
- if nullable_string_dtype == "arrow_string":
- reason = "extract does not yet dispatch to array"
- mark = pytest.mark.xfail(reason=reason)
- request.node.add_marker(mark)
-
a = Series(["a1", "b2", "cc"], dtype=nullable_string_dtype)
b = Series(["a1", "b2", "cc"], dtype="object")
pat = r"(\w)(\d)"
diff --git a/pandas/tests/strings/test_strings.py b/pandas/tests/strings/test_strings.py
index 06b22f00a38cf..2a52b3ba3f9e1 100644
--- a/pandas/tests/strings/test_strings.py
+++ b/pandas/tests/strings/test_strings.py
@@ -6,6 +6,8 @@
import numpy as np
import pytest
+import pandas.util._test_decorators as td
+
from pandas import (
DataFrame,
Index,
@@ -17,6 +19,27 @@
import pandas._testing as tm
+@pytest.fixture(
+ params=[
+ "object",
+ "string",
+ pytest.param(
+ "arrow_string", marks=td.skip_if_no("pyarrow", min_version="1.0.0")
+ ),
+ ]
+)
+def any_string_dtype(request):
+ """
+ Parametrized fixture for string dtypes.
+ * 'object'
+ * 'string'
+ * 'arrow_string'
+ """
+ from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401
+
+ return request.param
+
+
def assert_series_or_index_equal(left, right):
if isinstance(left, Series):
tm.assert_series_equal(left, right)
@@ -149,10 +172,15 @@ def test_repeat_with_null(nullable_string_dtype):
tm.assert_series_equal(result, expected)
-def test_empty_str_methods():
- empty_str = empty = Series(dtype=object)
- empty_int = Series(dtype="int64")
- empty_bool = Series(dtype=bool)
+def test_empty_str_methods(any_string_dtype):
+ empty_str = empty = Series(dtype=any_string_dtype)
+ if any_string_dtype == "object":
+ empty_int = Series(dtype="int64")
+ empty_bool = Series(dtype=bool)
+ else:
+ empty_int = Series(dtype="Int64")
+ empty_bool = Series(dtype="boolean")
+ empty_object = Series(dtype=object)
empty_bytes = Series(dtype=object)
# GH7241
@@ -184,15 +212,15 @@ def test_empty_str_methods():
tm.assert_frame_equal(DataFrame(dtype=str), empty.str.get_dummies())
tm.assert_series_equal(empty_str, empty_str.str.join(""))
tm.assert_series_equal(empty_int, empty.str.len())
- tm.assert_series_equal(empty_str, empty_str.str.findall("a"))
+ tm.assert_series_equal(empty_object, empty_str.str.findall("a"))
tm.assert_series_equal(empty_int, empty.str.find("a"))
tm.assert_series_equal(empty_int, empty.str.rfind("a"))
tm.assert_series_equal(empty_str, empty.str.pad(42))
tm.assert_series_equal(empty_str, empty.str.center(42))
- tm.assert_series_equal(empty_str, empty.str.split("a"))
- tm.assert_series_equal(empty_str, empty.str.rsplit("a"))
- tm.assert_series_equal(empty_str, empty.str.partition("a", expand=False))
- tm.assert_series_equal(empty_str, empty.str.rpartition("a", expand=False))
+ tm.assert_series_equal(empty_object, empty.str.split("a"))
+ tm.assert_series_equal(empty_object, empty.str.rsplit("a"))
+ tm.assert_series_equal(empty_object, empty.str.partition("a", expand=False))
+ tm.assert_series_equal(empty_object, empty.str.rpartition("a", expand=False))
tm.assert_series_equal(empty_str, empty.str.slice(stop=1))
tm.assert_series_equal(empty_str, empty.str.slice(step=1))
tm.assert_series_equal(empty_str, empty.str.strip())
@@ -200,7 +228,7 @@ def test_empty_str_methods():
tm.assert_series_equal(empty_str, empty.str.rstrip())
tm.assert_series_equal(empty_str, empty.str.wrap(42))
tm.assert_series_equal(empty_str, empty.str.get(0))
- tm.assert_series_equal(empty_str, empty_bytes.str.decode("ascii"))
+ tm.assert_series_equal(empty_object, empty_bytes.str.decode("ascii"))
tm.assert_series_equal(empty_bytes, empty.str.encode("ascii"))
# ismethods should always return boolean (GH 29624)
tm.assert_series_equal(empty_bool, empty.str.isalnum())
@@ -227,9 +255,9 @@ def test_empty_str_methods_to_frame():
tm.assert_frame_equal(empty_df, empty.str.rpartition("a"))
-def test_ismethods():
+def test_ismethods(any_string_dtype):
values = ["A", "b", "Xy", "4", "3A", "", "TT", "55", "-", " "]
- str_s = Series(values)
+ str_s = Series(values, dtype=any_string_dtype)
alnum_e = [True, True, True, True, True, False, True, True, False, False]
alpha_e = [True, True, True, False, False, False, True, False, False, False]
digit_e = [False, False, False, True, False, False, False, True, False, False]
@@ -253,13 +281,14 @@ def test_ismethods():
upper_e = [True, False, False, False, True, False, True, False, False, False]
title_e = [True, False, True, False, True, False, False, False, False, False]
- tm.assert_series_equal(str_s.str.isalnum(), Series(alnum_e))
- tm.assert_series_equal(str_s.str.isalpha(), Series(alpha_e))
- tm.assert_series_equal(str_s.str.isdigit(), Series(digit_e))
- tm.assert_series_equal(str_s.str.isspace(), Series(space_e))
- tm.assert_series_equal(str_s.str.islower(), Series(lower_e))
- tm.assert_series_equal(str_s.str.isupper(), Series(upper_e))
- tm.assert_series_equal(str_s.str.istitle(), Series(title_e))
+ dtype = "bool" if any_string_dtype == "object" else "boolean"
+ tm.assert_series_equal(str_s.str.isalnum(), Series(alnum_e, dtype=dtype))
+ tm.assert_series_equal(str_s.str.isalpha(), Series(alpha_e, dtype=dtype))
+ tm.assert_series_equal(str_s.str.isdigit(), Series(digit_e, dtype=dtype))
+ tm.assert_series_equal(str_s.str.isspace(), Series(space_e, dtype=dtype))
+ tm.assert_series_equal(str_s.str.islower(), Series(lower_e, dtype=dtype))
+ tm.assert_series_equal(str_s.str.isupper(), Series(upper_e, dtype=dtype))
+ tm.assert_series_equal(str_s.str.istitle(), Series(title_e, dtype=dtype))
assert str_s.str.isalnum().tolist() == [v.isalnum() for v in values]
assert str_s.str.isalpha().tolist() == [v.isalpha() for v in values]
@@ -270,28 +299,30 @@ def test_ismethods():
assert str_s.str.istitle().tolist() == [v.istitle() for v in values]
-def test_isnumeric():
+def test_isnumeric(any_string_dtype):
# 0x00bc: ¼ VULGAR FRACTION ONE QUARTER
# 0x2605: ★ not number
# 0x1378: ፸ ETHIOPIC NUMBER SEVENTY
# 0xFF13: 3 Em 3
values = ["A", "3", "¼", "★", "፸", "3", "four"]
- s = Series(values)
+ s = Series(values, dtype=any_string_dtype)
numeric_e = [False, True, True, False, True, True, False]
decimal_e = [False, True, False, False, False, True, False]
- tm.assert_series_equal(s.str.isnumeric(), Series(numeric_e))
- tm.assert_series_equal(s.str.isdecimal(), Series(decimal_e))
+ dtype = "bool" if any_string_dtype == "object" else "boolean"
+ tm.assert_series_equal(s.str.isnumeric(), Series(numeric_e, dtype=dtype))
+ tm.assert_series_equal(s.str.isdecimal(), Series(decimal_e, dtype=dtype))
unicodes = ["A", "3", "¼", "★", "፸", "3", "four"]
assert s.str.isnumeric().tolist() == [v.isnumeric() for v in unicodes]
assert s.str.isdecimal().tolist() == [v.isdecimal() for v in unicodes]
values = ["A", np.nan, "¼", "★", np.nan, "3", "four"]
- s = Series(values)
+ s = Series(values, dtype=any_string_dtype)
numeric_e = [False, np.nan, True, False, np.nan, True, False]
decimal_e = [False, np.nan, False, False, np.nan, True, False]
- tm.assert_series_equal(s.str.isnumeric(), Series(numeric_e))
- tm.assert_series_equal(s.str.isdecimal(), Series(decimal_e))
+ dtype = "object" if any_string_dtype == "object" else "boolean"
+ tm.assert_series_equal(s.str.isnumeric(), Series(numeric_e, dtype=dtype))
+ tm.assert_series_equal(s.str.isdecimal(), Series(decimal_e, dtype=dtype))
def test_get_dummies():
| xref https://github.com/xhochy/fletcher/pull/203
marked as draft since AFAICT there is performance issues with BooleanDtype().__from_arrow__ | https://api.github.com/repos/pandas-dev/pandas/pulls/41041 | 2021-04-19T13:47:43Z | 2021-04-25T13:17:15Z | 2021-04-25T13:17:15Z | 2021-04-25T15:48:12Z |
CI: Combined the doctests checks | diff --git a/ci/code_checks.sh b/ci/code_checks.sh
index d4b6c0d6ff09d..a2a108924a0f2 100755
--- a/ci/code_checks.sh
+++ b/ci/code_checks.sh
@@ -106,84 +106,31 @@ fi
### DOCTESTS ###
if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then
- # Individual files
-
- MSG='Doctests accessor.py' ; echo $MSG
- pytest -q --doctest-modules pandas/core/accessor.py
- RET=$(($RET + $?)) ; echo $MSG "DONE"
-
- MSG='Doctests aggregation.py' ; echo $MSG
- pytest -q --doctest-modules pandas/core/aggregation.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 frame.py' ; echo $MSG
- pytest -q --doctest-modules pandas/core/frame.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"
-
- MSG='Doctests series.py' ; echo $MSG
- pytest -q --doctest-modules pandas/core/series.py
- RET=$(($RET + $?)) ; echo $MSG "DONE"
-
- MSG='Doctests strings.py' ; echo $MSG
- pytest -q --doctest-modules pandas/core/strings/
- RET=$(($RET + $?)) ; echo $MSG "DONE"
-
- MSG='Doctests sql.py' ; echo $MSG
- pytest -q --doctest-modules pandas/io/sql.py
- RET=$(($RET + $?)) ; echo $MSG "DONE"
-
- # Directories
-
- MSG='Doctests arrays'; echo $MSG
- pytest -q --doctest-modules pandas/core/arrays/
- RET=$(($RET + $?)) ; echo $MSG "DONE"
-
- MSG='Doctests computation' ; echo $MSG
- pytest -q --doctest-modules pandas/core/computation/
- RET=$(($RET + $?)) ; echo $MSG "DONE"
-
- MSG='Doctests dtypes'; echo $MSG
- pytest -q --doctest-modules pandas/core/dtypes/
- RET=$(($RET + $?)) ; echo $MSG "DONE"
-
- MSG='Doctests groupby' ; echo $MSG
- pytest -q --doctest-modules pandas/core/groupby/
- RET=$(($RET + $?)) ; echo $MSG "DONE"
-
- MSG='Doctests indexes' ; echo $MSG
- pytest -q --doctest-modules pandas/core/indexes/
- RET=$(($RET + $?)) ; echo $MSG "DONE"
-
- MSG='Doctests ops' ; echo $MSG
- pytest -q --doctest-modules pandas/core/ops/
- RET=$(($RET + $?)) ; echo $MSG "DONE"
-
- MSG='Doctests reshape' ; echo $MSG
- pytest -q --doctest-modules pandas/core/reshape/
- RET=$(($RET + $?)) ; echo $MSG "DONE"
-
- MSG='Doctests tools' ; echo $MSG
- pytest -q --doctest-modules pandas/core/tools/
- RET=$(($RET + $?)) ; echo $MSG "DONE"
-
- MSG='Doctests window' ; echo $MSG
- pytest -q --doctest-modules pandas/core/window/
- RET=$(($RET + $?)) ; echo $MSG "DONE"
-
- MSG='Doctests tseries' ; echo $MSG
- pytest -q --doctest-modules pandas/tseries/
+ MSG='Doctests for individual files' ; echo $MSG
+ pytest -q --doctest-modules \
+ pandas/core/accessor.py \
+ pandas/core/aggregation.py \
+ pandas/core/base.py \
+ pandas/core/construction.py \
+ pandas/core/frame.py \
+ pandas/core/generic.py \
+ pandas/core/series.py \
+ pandas/io/sql.py
+ RET=$(($RET + $?)) ; echo $MSG "DONE"
+
+ MSG='Doctests for directories' ; echo $MSG
+ pytest -q --doctest-modules \
+ pandas/core/arrays/ \
+ pandas/core/computation/ \
+ pandas/core/dtypes/ \
+ pandas/core/groupby/ \
+ pandas/core/indexes/ \
+ pandas/core/ops/ \
+ pandas/core/reshape/ \
+ pandas/core/strings/ \
+ pandas/core/tools/ \
+ pandas/core/window/ \
+ pandas/tseries/
RET=$(($RET + $?)) ; echo $MSG "DONE"
fi
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
Doing as was asked [here](https://github.com/pandas-dev/pandas/pull/40903#discussion_r612486254)
| https://api.github.com/repos/pandas-dev/pandas/pulls/41039 | 2021-04-19T13:21:30Z | 2021-04-26T18:25:05Z | 2021-04-26T18:25:05Z | 2021-04-26T19:34:02Z |
DOC: add example for plotting asymmetrical error bars | diff --git a/doc/source/user_guide/visualization.rst b/doc/source/user_guide/visualization.rst
index 8b41cc24829c5..2143d7ea75f6e 100644
--- a/doc/source/user_guide/visualization.rst
+++ b/doc/source/user_guide/visualization.rst
@@ -1455,8 +1455,6 @@ Horizontal and vertical error bars can be supplied to the ``xerr`` and ``yerr``
* As a ``str`` indicating which of the columns of plotting :class:`DataFrame` contain the error values.
* As raw values (``list``, ``tuple``, or ``np.ndarray``). Must be the same length as the plotting :class:`DataFrame`/:class:`Series`.
-Asymmetrical error bars are also supported, however raw error values must be provided in this case. For a ``N`` length :class:`Series`, a ``2xN`` array should be provided indicating lower and upper (or left and right) errors. For a ``MxN`` :class:`DataFrame`, asymmetrical errors should be in a ``Mx2xN`` array.
-
Here is an example of one way to easily plot group means with standard deviations from the raw data.
.. ipython:: python
@@ -1464,16 +1462,16 @@ Here is an example of one way to easily plot group means with standard deviation
# Generate the data
ix3 = pd.MultiIndex.from_arrays(
[
- ["a", "a", "a", "a", "b", "b", "b", "b"],
- ["foo", "foo", "bar", "bar", "foo", "foo", "bar", "bar"],
+ ["a", "a", "a", "a", "a", "b", "b", "b", "b", "b"],
+ ["foo", "foo", "foo", "bar", "bar", "foo", "foo", "bar", "bar", "bar"],
],
names=["letter", "word"],
)
df3 = pd.DataFrame(
{
- "data1": [3, 2, 4, 3, 2, 4, 3, 2],
- "data2": [6, 5, 7, 5, 4, 5, 6, 5],
+ "data1": [9, 3, 2, 4, 3, 2, 4, 6, 3, 2],
+ "data2": [9, 6, 5, 7, 5, 4, 5, 6, 5, 1],
},
index=ix3,
)
@@ -1496,6 +1494,28 @@ Here is an example of one way to easily plot group means with standard deviation
plt.close("all")
+Asymmetrical error bars are also supported, however raw error values must be provided in this case. For a ``N`` length :class:`Series`, a ``2xN`` array should be provided indicating lower and upper (or left and right) errors. For a ``MxN`` :class:`DataFrame`, asymmetrical errors should be in a ``Mx2xN`` array.
+
+Here is an example of one way to plot the min/max range using asymmetrical error bars.
+
+.. ipython:: python
+
+ mins = gp3.min()
+ maxs = gp3.max()
+
+ # errors should be positive, and defined in the order of lower, upper
+ errors = [[means[c] - mins[c], maxs[c] - means[c]] for c in df3.columns]
+
+ # Plot
+ fig, ax = plt.subplots()
+ @savefig errorbar_asymmetrical_example.png
+ means.plot.bar(yerr=errors, ax=ax, capsize=4, rot=0);
+
+.. ipython:: python
+ :suppress:
+
+ plt.close("all")
+
.. _visualization.table:
Plotting tables
| - [x] closes #41034
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41035 | 2021-04-19T07:32:11Z | 2021-04-21T04:27:08Z | 2021-04-21T04:27:08Z | 2021-04-21T04:27:21Z |
⬆️ UPGRADE: Autoupdate pre-commit config | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 5b11490479088..2f46190ef5eb7 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -35,7 +35,7 @@ repos:
exclude: ^pandas/_libs/src/(klib|headers)/
args: [--quiet, '--extensions=c,h', '--headers=h', --recursive, '--filter=-readability/casting,-runtime/int,-build/include_subdir']
- repo: https://gitlab.com/pycqa/flake8
- rev: 3.9.0
+ rev: 3.9.1
hooks:
- id: flake8
additional_dependencies:
@@ -75,7 +75,7 @@ repos:
hooks:
- id: yesqa
additional_dependencies:
- - flake8==3.9.0
+ - flake8==3.9.1
- flake8-comprehensions==3.1.0
- flake8-bugbear==21.3.2
- pandas-dev-flaker==0.2.0
diff --git a/environment.yml b/environment.yml
index 146bf6db08d8b..0d03ad8e0a46a 100644
--- a/environment.yml
+++ b/environment.yml
@@ -20,7 +20,7 @@ dependencies:
# code checks
- black=20.8b1
- cpplint
- - flake8=3.9.0
+ - flake8=3.9.1
- flake8-bugbear=21.3.2 # used by flake8, find likely bugs
- flake8-comprehensions=3.1.0 # used by flake8, linting of unnecessary comprehensions
- isort>=5.2.1 # check that imports are in the right order
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 33deeef9f1f82..ea7ca43742934 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -8,7 +8,7 @@ asv
cython>=0.29.21
black==20.8b1
cpplint
-flake8==3.9.0
+flake8==3.9.1
flake8-bugbear==21.3.2
flake8-comprehensions==3.1.0
isort>=5.2.1
| <!-- START pr-commits -->
<!-- END pr-commits -->
## Base PullRequest
default branch (https://github.com/pandas-dev/pandas/tree/master)
## Command results
<details>
<summary>Details: </summary>
<details>
<summary><em>add path</em></summary>
```Shell
/home/runner/work/_actions/technote-space/create-pr-action/v2/node_modules/npm-check-updates/bin
```
</details>
<details>
<summary><em>pip install pre-commit</em></summary>
```Shell
Collecting pre-commit
Downloading pre_commit-2.12.1-py2.py3-none-any.whl (189 kB)
Collecting nodeenv>=0.11.1
Downloading nodeenv-1.6.0-py2.py3-none-any.whl (21 kB)
Collecting identify>=1.0.0
Downloading identify-2.2.3-py2.py3-none-any.whl (98 kB)
Collecting toml
Using cached toml-0.10.2-py2.py3-none-any.whl (16 kB)
Collecting cfgv>=2.0.0
Using cached cfgv-3.2.0-py2.py3-none-any.whl (7.3 kB)
Collecting pyyaml>=5.1
Downloading PyYAML-5.4.1-cp39-cp39-manylinux1_x86_64.whl (630 kB)
Collecting virtualenv>=20.0.8
Downloading virtualenv-20.4.3-py2.py3-none-any.whl (7.2 MB)
Collecting six<2,>=1.9.0
Using cached six-1.15.0-py2.py3-none-any.whl (10 kB)
Collecting appdirs<2,>=1.4.3
Using cached appdirs-1.4.4-py2.py3-none-any.whl (9.6 kB)
Collecting distlib<1,>=0.3.1
Using cached distlib-0.3.1-py2.py3-none-any.whl (335 kB)
Collecting filelock<4,>=3.0.0
Using cached filelock-3.0.12-py3-none-any.whl (7.6 kB)
Installing collected packages: six, filelock, distlib, appdirs, virtualenv, toml, pyyaml, nodeenv, identify, cfgv, pre-commit
Successfully installed appdirs-1.4.4 cfgv-3.2.0 distlib-0.3.1 filelock-3.0.12 identify-2.2.3 nodeenv-1.6.0 pre-commit-2.12.1 pyyaml-5.4.1 six-1.15.0 toml-0.10.2 virtualenv-20.4.3
```
</details>
<details>
<summary><em>pre-commit autoupdate || (exit 0);</em></summary>
```Shell
Updating https://github.com/MarcoGorelli/absolufy-imports ... [INFO] Initializing environment for https://github.com/MarcoGorelli/absolufy-imports.
already up to date.
Updating https://github.com/python/black ... already up to date.
Updating https://github.com/codespell-project/codespell ... [INFO] Initializing environment for https://github.com/codespell-project/codespell.
already up to date.
Updating https://github.com/pre-commit/pre-commit-hooks ... [INFO] Initializing environment for https://github.com/pre-commit/pre-commit-hooks.
already up to date.
Updating https://github.com/cpplint/cpplint ... [INFO] Initializing environment for https://github.com/cpplint/cpplint.
=====> /home/runner/.cache/pre-commit/repof0nncua3/.pre-commit-hooks.yaml does not exist
Updating https://gitlab.com/pycqa/flake8 ... [INFO] Initializing environment for https://gitlab.com/pycqa/flake8.
updating 3.9.0 -> 3.9.1.
Updating https://github.com/PyCQA/isort ... [INFO] Initializing environment for https://github.com/PyCQA/isort.
already up to date.
Updating https://github.com/asottile/pyupgrade ... [INFO] Initializing environment for https://github.com/asottile/pyupgrade.
already up to date.
Updating https://github.com/pre-commit/pygrep-hooks ... [INFO] Initializing environment for https://github.com/pre-commit/pygrep-hooks.
already up to date.
Updating https://github.com/asottile/yesqa ... already up to date.
```
</details>
<details>
<summary><em>pre-commit run -a || (exit 0);</em></summary>
```Shell
[INFO] Initializing environment for https://github.com/cpplint/cpplint.
[INFO] Initializing environment for https://gitlab.com/pycqa/flake8:flake8-bugbear==21.3.2,flake8-comprehensions==3.1.0,pandas-dev-flaker==0.2.0.
[INFO] Initializing environment for https://github.com/asottile/yesqa:flake8-bugbear==21.3.2,flake8-comprehensions==3.1.0,flake8==3.9.0,pandas-dev-flaker==0.2.0.
[INFO] Installing environment for https://github.com/MarcoGorelli/absolufy-imports.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
[INFO] Installing environment for https://github.com/python/black.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
[INFO] Installing environment for https://github.com/codespell-project/codespell.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
[INFO] Installing environment for https://github.com/pre-commit/pre-commit-hooks.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
[INFO] Installing environment for https://github.com/cpplint/cpplint.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
[INFO] Installing environment for https://gitlab.com/pycqa/flake8.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
[INFO] Installing environment for https://gitlab.com/pycqa/flake8.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
[INFO] Installing environment for https://github.com/PyCQA/isort.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
[INFO] Installing environment for https://github.com/asottile/pyupgrade.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
[INFO] Installing environment for https://github.com/asottile/yesqa.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
[INFO] Installing environment for local.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
[INFO] Installing environment for local.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
[INFO] Installing environment for local.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
absolufy-imports...............................................................................Passed
black..........................................................................................Passed
codespell......................................................................................Passed
Fix End of Files...............................................................................Passed
Trim Trailing Whitespace.......................................................................Passed
cpplint........................................................................................Passed
flake8.........................................................................................Passed
flake8 (cython)................................................................................Passed
flake8 (cython template).......................................................................Passed
isort..........................................................................................Passed
pyupgrade......................................................................................Passed
rst ``code`` is two backticks..................................................................Passed
rst directives end with two colons.............................................................Passed
rst ``inline code`` next to normal text........................................................Passed
Strip unnecessary `# noqa`s....................................................................Passed
flake8-rst.....................................................................................Passed
Unwanted patterns..............................................................................Passed
Generate pip dependency from conda.............................................................Passed
Check flake8 version is synced across flake8, yesqa, and environment.yml.......................Failed
- hook id: sync-flake8-versions
- exit code: 1
flake8 in 'environment.yml' does not match in 'flake8' from 'pre-commit'
Validate correct capitalization among titles in documentation..................................Passed
Import pandas.array as pd_array in core........................................................Passed
Use bool_t instead of bool in pandas/core/generic.py...........................................Passed
```
</details>
</details>
## Changed files
<details>
<summary>Changed file: </summary>
- .pre-commit-config.yaml
</details>
<hr>
[:octocat: Repo](https://github.com/technote-space/create-pr-action) | [:memo: Issues](https://github.com/technote-space/create-pr-action/issues) | [:department_store: Marketplace](https://github.com/marketplace/actions/create-pr-action) | https://api.github.com/repos/pandas-dev/pandas/pulls/41033 | 2021-04-19T07:14:08Z | 2021-04-19T19:38:04Z | 2021-04-19T19:38:03Z | 2021-05-13T22:26:29Z |
REF: remove Categorical._shallow_copy | diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py
index 9e2dd846f0379..6f906cf8879ff 100644
--- a/pandas/core/algorithms.py
+++ b/pandas/core/algorithms.py
@@ -1876,29 +1876,33 @@ def _sort_tuples(values: np.ndarray) -> np.ndarray:
return values[indexer]
-def union_with_duplicates(lvals: np.ndarray, rvals: np.ndarray) -> np.ndarray:
+def union_with_duplicates(lvals: ArrayLike, rvals: ArrayLike) -> ArrayLike:
"""
Extracts the union from lvals and rvals with respect to duplicates and nans in
both arrays.
Parameters
----------
- lvals: np.ndarray
+ lvals: np.ndarray or ExtensionArray
left values which is ordered in front.
- rvals: np.ndarray
+ rvals: np.ndarray or ExtensionArray
right values ordered after lvals.
Returns
-------
- np.ndarray containing the unsorted union of both arrays
+ np.ndarray or ExtensionArray
+ Containing the unsorted union of both arrays.
"""
indexer = []
l_count = value_counts(lvals, dropna=False)
r_count = value_counts(rvals, dropna=False)
l_count, r_count = l_count.align(r_count, fill_value=0)
unique_array = unique(np.append(lvals, rvals))
- if is_extension_array_dtype(lvals) or is_extension_array_dtype(rvals):
- unique_array = pd_array(unique_array)
+ if not isinstance(lvals, np.ndarray):
+ # i.e. ExtensionArray
+ # Note: we only get here with lvals.dtype == rvals.dtype
+ # TODO: are there any cases where union won't be type/dtype preserving?
+ unique_array = type(lvals)._from_sequence(unique_array, dtype=lvals.dtype)
for i, value in enumerate(unique_array):
indexer += [i] * int(max(l_count[value], r_count[value]))
return unique_array.take(indexer)
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 310ee4c3a63e3..6cf6c18dbe350 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -2982,12 +2982,7 @@ def _union(self, other: Index, sort):
elif not other.is_unique:
# other has duplicates
-
- # error: Argument 1 to "union_with_duplicates" has incompatible type
- # "Union[ExtensionArray, ndarray]"; expected "ndarray"
- # error: Argument 2 to "union_with_duplicates" has incompatible type
- # "Union[ExtensionArray, ndarray]"; expected "ndarray"
- result = algos.union_with_duplicates(lvals, rvals) # type: ignore[arg-type]
+ result = algos.union_with_duplicates(lvals, rvals)
return _maybe_try_sort(result, sort)
# Self may have duplicates
@@ -3002,9 +2997,7 @@ def _union(self, other: Index, sort):
other_diff = rvals.take(missing)
result = concat_compat((lvals, other_diff))
else:
- # error: Incompatible types in assignment (expression has type
- # "Union[ExtensionArray, ndarray]", variable has type "ndarray")
- result = lvals # type: ignore[assignment]
+ result = lvals
if not self.is_monotonic or not other.is_monotonic:
result = _maybe_try_sort(result, sort)
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index 5b98b956e33e6..8d15b460a79df 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -11,7 +11,6 @@
from pandas._config import get_option
from pandas._libs import index as libindex
-from pandas._libs.lib import no_default
from pandas._typing import (
ArrayLike,
Dtype,
@@ -234,22 +233,6 @@ def __new__(
# --------------------------------------------------------------------
- @doc(Index._shallow_copy)
- def _shallow_copy(
- self,
- values: Categorical,
- name: Hashable = no_default,
- ) -> CategoricalIndex:
- name = self._name if name is no_default else name
-
- if values is not None:
- # In tests we only get here with Categorical objects that
- # have matching .ordered, and values.categories a subset of
- # our own. However we do _not_ have a dtype match in general.
- values = Categorical(values, dtype=self.dtype)
-
- return super()._shallow_copy(values=values, name=name)
-
def _is_dtype_compat(self, other) -> Categorical:
"""
*this is an internal non-public method*
diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py
index b11ec06120e0c..d28bcd6c5497a 100644
--- a/pandas/core/indexes/extension.py
+++ b/pandas/core/indexes/extension.py
@@ -331,7 +331,7 @@ def _get_unique_index(self):
return self
result = self._data.unique()
- return self._shallow_copy(result)
+ return type(self)._simple_new(result, name=self.name)
@doc(Index.map)
def map(self, mapper, na_action=None):
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
@phofl parts of this may be worth doing in #40967 | https://api.github.com/repos/pandas-dev/pandas/pulls/41030 | 2021-04-19T04:01:55Z | 2021-04-19T13:38:44Z | 2021-04-19T13:38:44Z | 2021-04-19T14:48:38Z |
TYP: aggregations.pyx | diff --git a/pandas/_libs/window/aggregations.pyi b/pandas/_libs/window/aggregations.pyi
new file mode 100644
index 0000000000000..3391edac84224
--- /dev/null
+++ b/pandas/_libs/window/aggregations.pyi
@@ -0,0 +1,126 @@
+from typing import (
+ Any,
+ Callable,
+ Literal,
+)
+
+import numpy as np
+
+def roll_sum(
+ values: np.ndarray, # const float64_t[:]
+ start: np.ndarray, # np.ndarray[np.int64]
+ end: np.ndarray, # np.ndarray[np.int64]
+ minp: int, # int64_t
+) -> np.ndarray: ... # np.ndarray[float]
+
+def roll_mean(
+ values: np.ndarray, # const float64_t[:]
+ start: np.ndarray, # np.ndarray[np.int64]
+ end: np.ndarray, # np.ndarray[np.int64]
+ minp: int, # int64_t
+) -> np.ndarray: ... # np.ndarray[float]
+
+def roll_var(
+ values: np.ndarray, # const float64_t[:]
+ start: np.ndarray, # np.ndarray[np.int64]
+ end: np.ndarray, # np.ndarray[np.int64]
+ minp: int, # int64_t
+ ddof: int = ...,
+) -> np.ndarray: ... # np.ndarray[float]
+
+def roll_skew(
+ values: np.ndarray, # np.ndarray[np.float64]
+ start: np.ndarray, # np.ndarray[np.int64]
+ end: np.ndarray, # np.ndarray[np.int64]
+ minp: int, # int64_t
+) -> np.ndarray: ... # np.ndarray[float]
+
+def roll_kurt(
+ values: np.ndarray, # np.ndarray[np.float64]
+ start: np.ndarray, # np.ndarray[np.int64]
+ end: np.ndarray, # np.ndarray[np.int64]
+ minp: int, # int64_t
+) -> np.ndarray: ... # np.ndarray[float]
+
+def roll_median_c(
+ values: np.ndarray, # np.ndarray[np.float64]
+ start: np.ndarray, # np.ndarray[np.int64]
+ end: np.ndarray, # np.ndarray[np.int64]
+ minp: int, # int64_t
+) -> np.ndarray: ... # np.ndarray[float]
+
+def roll_max(
+ values: np.ndarray, # np.ndarray[np.float64]
+ start: np.ndarray, # np.ndarray[np.int64]
+ end: np.ndarray, # np.ndarray[np.int64]
+ minp: int, # int64_t
+) -> np.ndarray: ... # np.ndarray[float]
+
+def roll_min(
+ values: np.ndarray, # np.ndarray[np.float64]
+ start: np.ndarray, # np.ndarray[np.int64]
+ end: np.ndarray, # np.ndarray[np.int64]
+ minp: int, # int64_t
+) -> np.ndarray: ... # np.ndarray[float]
+
+def roll_quantile(
+ values: np.ndarray, # const float64_t[:]
+ start: np.ndarray, # np.ndarray[np.int64]
+ end: np.ndarray, # np.ndarray[np.int64]
+ minp: int, # int64_t
+ quantile: float, # float64_t
+ interpolation: Literal["linear", "lower", "higher", "nearest", "midpoint"],
+) -> np.ndarray: ... # np.ndarray[float]
+
+def roll_apply(
+ obj: object,
+ start: np.ndarray, # np.ndarray[np.int64]
+ end: np.ndarray, # np.ndarray[np.int64]
+ minp: int, # int64_t
+ function: Callable[..., Any],
+ raw: bool,
+ args: tuple[Any, ...],
+ kwargs: dict[str, Any],
+) -> np.ndarray: ... # np.ndarray[float] # FIXME: could also be type(obj) if n==0
+
+def roll_weighted_sum(
+ values: np.ndarray, # const float64_t[:]
+ weights: np.ndarray, # const float64_t[:]
+ minp: int,
+) -> np.ndarray: ... # np.ndarray[np.float64]
+
+def roll_weighted_mean(
+ values: np.ndarray, # const float64_t[:]
+ weights: np.ndarray, # const float64_t[:]
+ minp: int,
+) -> np.ndarray: ... # np.ndarray[np.float64]
+
+def roll_weighted_var(
+ values: np.ndarray, # const float64_t[:]
+ weights: np.ndarray, # const float64_t[:]
+ minp: int, # int64_t
+ ddof: int, # unsigned int
+) -> np.ndarray: ... # np.ndarray[np.float64]
+
+def ewma(
+ vals: np.ndarray, # const float64_t[:]
+ start: np.ndarray, # const int64_t[:]
+ end: np.ndarray, # const int64_t[:]
+ minp: int,
+ com: float, # float64_t
+ adjust: bool,
+ ignore_na: bool,
+ deltas: np.ndarray, # const float64_t[:]
+) -> np.ndarray: ... # np.ndarray[np.float64]
+
+def ewmcov(
+ input_x: np.ndarray, # const float64_t[:]
+ start: np.ndarray, # const int64_t[:]
+ end: np.ndarray, # const int64_t[:]
+ minp: int,
+ input_y: np.ndarray, # const float64_t[:]
+ com: float, # float64_t
+ adjust: bool,
+ ignore_na: bool,
+ bias: bool,
+) -> np.ndarray: ... # np.ndarray[np.float64]
diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx
index 8d6f899d6f3ca..3d3a19a1c7a40 100644
--- a/pandas/_libs/window/aggregations.pyx
+++ b/pandas/_libs/window/aggregations.pyx
@@ -116,7 +116,7 @@ cdef inline void remove_sum(float64_t val, int64_t *nobs, float64_t *sum_x,
def roll_sum(const float64_t[:] values, ndarray[int64_t] start,
- ndarray[int64_t] end, int64_t minp):
+ ndarray[int64_t] end, int64_t minp) -> np.ndarray:
cdef:
Py_ssize_t i, j
float64_t sum_x = 0, compensation_add = 0, compensation_remove = 0
@@ -128,7 +128,7 @@ def roll_sum(const float64_t[:] values, ndarray[int64_t] start,
is_monotonic_increasing_bounds = is_monotonic_increasing_start_end_bounds(
start, end
)
- output = np.empty(N, dtype=float)
+ output = np.empty(N, dtype=np.float64)
with nogil:
@@ -221,7 +221,7 @@ cdef inline void remove_mean(float64_t val, Py_ssize_t *nobs, float64_t *sum_x,
def roll_mean(const float64_t[:] values, ndarray[int64_t] start,
- ndarray[int64_t] end, int64_t minp):
+ ndarray[int64_t] end, int64_t minp) -> np.ndarray:
cdef:
float64_t val, compensation_add = 0, compensation_remove = 0, sum_x = 0
int64_t s, e
@@ -232,7 +232,7 @@ def roll_mean(const float64_t[:] values, ndarray[int64_t] start,
is_monotonic_increasing_bounds = is_monotonic_increasing_start_end_bounds(
start, end
)
- output = np.empty(N, dtype=float)
+ output = np.empty(N, dtype=np.float64)
with nogil:
@@ -338,7 +338,7 @@ cdef inline void remove_var(float64_t val, float64_t *nobs, float64_t *mean_x,
def roll_var(const float64_t[:] values, ndarray[int64_t] start,
- ndarray[int64_t] end, int64_t minp, int ddof=1):
+ ndarray[int64_t] end, int64_t minp, int ddof=1) -> np.ndarray:
"""
Numerically stable implementation using Welford's method.
"""
@@ -355,7 +355,7 @@ def roll_var(const float64_t[:] values, ndarray[int64_t] start,
is_monotonic_increasing_bounds = is_monotonic_increasing_start_end_bounds(
start, end
)
- output = np.empty(N, dtype=float)
+ output = np.empty(N, dtype=np.float64)
with nogil:
@@ -490,7 +490,7 @@ cdef inline void remove_skew(float64_t val, int64_t *nobs,
def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start,
- ndarray[int64_t] end, int64_t minp):
+ ndarray[int64_t] end, int64_t minp) -> np.ndarray:
cdef:
Py_ssize_t i, j
float64_t val, prev, min_val, mean_val, sum_val = 0
@@ -507,7 +507,7 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start,
is_monotonic_increasing_bounds = is_monotonic_increasing_start_end_bounds(
start, end
)
- output = np.empty(N, dtype=float)
+ output = np.empty(N, dtype=np.float64)
min_val = np.nanmin(values)
values_copy = np.copy(values)
@@ -672,7 +672,7 @@ cdef inline void remove_kurt(float64_t val, int64_t *nobs,
def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start,
- ndarray[int64_t] end, int64_t minp):
+ ndarray[int64_t] end, int64_t minp) -> np.ndarray:
cdef:
Py_ssize_t i, j
float64_t val, prev, mean_val, min_val, sum_val = 0
@@ -689,7 +689,7 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start,
is_monotonic_increasing_bounds = is_monotonic_increasing_start_end_bounds(
start, end
)
- output = np.empty(N, dtype=float)
+ output = np.empty(N, dtype=np.float64)
values_copy = np.copy(values)
min_val = np.nanmin(values)
@@ -753,7 +753,7 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start,
def roll_median_c(const float64_t[:] values, ndarray[int64_t] start,
- ndarray[int64_t] end, int64_t minp):
+ ndarray[int64_t] end, int64_t minp) -> np.ndarray:
cdef:
Py_ssize_t i, j
bint err = False, is_monotonic_increasing_bounds
@@ -769,7 +769,7 @@ def roll_median_c(const float64_t[:] values, ndarray[int64_t] start,
# we use the Fixed/Variable Indexer here as the
# actual skiplist ops outweigh any window computation costs
- output = np.empty(N, dtype=float)
+ output = np.empty(N, dtype=np.float64)
if (end - start).max() == 0:
output[:] = NaN
@@ -889,7 +889,7 @@ cdef inline numeric calc_mm(int64_t minp, Py_ssize_t nobs,
def roll_max(ndarray[float64_t] values, ndarray[int64_t] start,
- ndarray[int64_t] end, int64_t minp):
+ ndarray[int64_t] end, int64_t minp) -> np.ndarray:
"""
Moving max of 1d array of any numeric type along axis=0 ignoring NaNs.
@@ -904,12 +904,16 @@ def roll_max(ndarray[float64_t] values, ndarray[int64_t] start,
closed : 'right', 'left', 'both', 'neither'
make the interval closed on the right, left,
both or neither endpoints
+
+ Returns
+ -------
+ np.ndarray[float]
"""
return _roll_min_max(values, start, end, minp, is_max=1)
def roll_min(ndarray[float64_t] values, ndarray[int64_t] start,
- ndarray[int64_t] end, int64_t minp):
+ ndarray[int64_t] end, int64_t minp) -> np.ndarray:
"""
Moving min of 1d array of any numeric type along axis=0 ignoring NaNs.
@@ -921,6 +925,10 @@ def roll_min(ndarray[float64_t] values, ndarray[int64_t] start,
is below this, output a NaN
index : ndarray, optional
index for window computation
+
+ Returns
+ -------
+ np.ndarray[float]
"""
return _roll_min_max(values, start, end, minp, is_max=0)
@@ -938,7 +946,7 @@ cdef _roll_min_max(ndarray[numeric] values,
deque W[int64_t] # track the whole window for nobs compute
ndarray[float64_t, ndim=1] output
- output = np.empty(N, dtype=float)
+ output = np.empty(N, dtype=np.float64)
Q = deque[int64_t]()
W = deque[int64_t]()
@@ -1011,7 +1019,7 @@ interpolation_types = {
def roll_quantile(const float64_t[:] values, ndarray[int64_t] start,
ndarray[int64_t] end, int64_t minp,
- float64_t quantile, str interpolation):
+ float64_t quantile, str interpolation) -> np.ndarray:
"""
O(N log(window)) implementation using skip list
"""
@@ -1038,7 +1046,7 @@ def roll_quantile(const float64_t[:] values, ndarray[int64_t] start,
)
# we use the Fixed/Variable Indexer here as the
# actual skiplist ops outweigh any window computation costs
- output = np.empty(N, dtype=float)
+ output = np.empty(N, dtype=np.float64)
win = (end - start).max()
if win == 0:
@@ -1132,7 +1140,7 @@ def roll_apply(object obj,
ndarray[int64_t] start, ndarray[int64_t] end,
int64_t minp,
object function, bint raw,
- tuple args, dict kwargs):
+ tuple args, dict kwargs) -> np.ndarray:
cdef:
ndarray[float64_t] output, counts
ndarray[float64_t, cast=True] arr
@@ -1149,7 +1157,7 @@ def roll_apply(object obj,
counts = roll_sum(np.isfinite(arr).astype(float), start, end, minp)
- output = np.empty(N, dtype=float)
+ output = np.empty(N, dtype=np.float64)
for i in range(N):
@@ -1171,11 +1179,15 @@ def roll_apply(object obj,
# Rolling sum and mean for weighted window
-def roll_weighted_sum(const float64_t[:] values, const float64_t[:] weights, int minp):
+def roll_weighted_sum(
+ const float64_t[:] values, const float64_t[:] weights, int minp
+) -> np.ndaray:
return _roll_weighted_sum_mean(values, weights, minp, avg=0)
-def roll_weighted_mean(const float64_t[:] values, const float64_t[:] weights, int minp):
+def roll_weighted_mean(
+ const float64_t[:] values, const float64_t[:] weights, int minp
+) -> np.ndaray:
return _roll_weighted_sum_mean(values, weights, minp, avg=1)
@@ -1434,7 +1446,7 @@ def roll_weighted_var(const float64_t[:] values, const float64_t[:] weights,
n = len(values)
win_n = len(weights)
- output = np.empty(n, dtype=float)
+ output = np.empty(n, dtype=np.float64)
with nogil:
@@ -1474,7 +1486,7 @@ def roll_weighted_var(const float64_t[:] values, const float64_t[:] weights,
def ewma(const float64_t[:] vals, const int64_t[:] start, const int64_t[:] end,
int minp, float64_t com, bint adjust, bint ignore_na,
- const float64_t[:] deltas):
+ const float64_t[:] deltas) -> np.ndarray:
"""
Compute exponentially-weighted moving average using center-of-mass.
@@ -1491,13 +1503,13 @@ def ewma(const float64_t[:] vals, const int64_t[:] start, const int64_t[:] end,
Returns
-------
- ndarray
+ np.ndarray[float64_t]
"""
cdef:
Py_ssize_t i, j, s, e, nobs, win_size, N = len(vals), M = len(start)
const float64_t[:] sub_deltas, sub_vals
- ndarray[float64_t] sub_output, output = np.empty(N, dtype=float)
+ ndarray[float64_t] sub_output, output = np.empty(N, dtype=np.float64)
float64_t alpha, old_wt_factor, new_wt, weighted_avg, old_wt, cur
bint is_observation
@@ -1516,7 +1528,7 @@ def ewma(const float64_t[:] vals, const int64_t[:] start, const int64_t[:] end,
# conjunction with vals[i+1]
sub_deltas = deltas[s:e - 1]
win_size = len(sub_vals)
- sub_output = np.empty(win_size, dtype=float)
+ sub_output = np.empty(win_size, dtype=np.float64)
weighted_avg = sub_vals[0]
is_observation = weighted_avg == weighted_avg
@@ -1559,7 +1571,7 @@ def ewma(const float64_t[:] vals, const int64_t[:] start, const int64_t[:] end,
def ewmcov(const float64_t[:] input_x, const int64_t[:] start, const int64_t[:] end,
int minp, const float64_t[:] input_y, float64_t com, bint adjust,
- bint ignore_na, bint bias):
+ bint ignore_na, bint bias) -> np.ndarray:
"""
Compute exponentially-weighted moving variance using center-of-mass.
@@ -1577,7 +1589,7 @@ def ewmcov(const float64_t[:] input_x, const int64_t[:] start, const int64_t[:]
Returns
-------
- ndarray
+ np.ndarray[float64_t]
"""
cdef:
@@ -1587,7 +1599,7 @@ def ewmcov(const float64_t[:] input_x, const int64_t[:] start, const int64_t[:]
float64_t sum_wt, sum_wt2, old_wt, cur_x, cur_y, old_mean_x, old_mean_y
float64_t numerator, denominator
const float64_t[:] sub_x_vals, sub_y_vals
- ndarray[float64_t] sub_out, output = np.empty(N, dtype=float)
+ ndarray[float64_t] sub_out, output = np.empty(N, dtype=np.float64)
bint is_observation
if M != N:
@@ -1606,7 +1618,7 @@ def ewmcov(const float64_t[:] input_x, const int64_t[:] start, const int64_t[:]
sub_x_vals = input_x[s:e]
sub_y_vals = input_y[s:e]
win_size = len(sub_x_vals)
- sub_out = np.empty(win_size, dtype=float)
+ sub_out = np.empty(win_size, dtype=np.float64)
mean_x = sub_x_vals[0]
mean_y = sub_y_vals[0]
diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py
index 9208ec615557e..4a210d8b47e9b 100644
--- a/pandas/core/window/ewm.py
+++ b/pandas/core/window/ewm.py
@@ -449,7 +449,7 @@ def vol(self, bias: bool = False, *args, **kwargs):
def var(self, bias: bool = False, *args, **kwargs):
nv.validate_window_func("var", args, kwargs)
window_func = window_aggregations.ewmcov
- window_func = partial(
+ wfunc = partial(
window_func,
com=self._com,
adjust=self.adjust,
@@ -458,7 +458,7 @@ def var(self, bias: bool = False, *args, **kwargs):
)
def var_func(values, begin, end, min_periods):
- return window_func(values, begin, end, min_periods, values)
+ return wfunc(values, begin, end, min_periods, values)
return self._apply(var_func)
@@ -518,7 +518,9 @@ def cov_func(x, y):
x_array,
start,
end,
- self.min_periods,
+ # error: Argument 4 to "ewmcov" has incompatible type
+ # "Optional[int]"; expected "int"
+ self.min_periods, # type: ignore[arg-type]
y_array,
self._com,
self.adjust,
@@ -584,12 +586,12 @@ def _cov(X, Y):
X,
start,
end,
- self.min_periods,
+ min_periods,
Y,
self._com,
self.adjust,
self.ignore_na,
- 1,
+ True,
)
with np.errstate(all="ignore"):
diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py
index e4710254d9311..31b09dc8e5973 100644
--- a/pandas/core/window/rolling.py
+++ b/pandas/core/window/rolling.py
@@ -1051,7 +1051,10 @@ def aggregate(self, func, *args, **kwargs):
def sum(self, *args, **kwargs):
nv.validate_window_func("sum", args, kwargs)
window_func = window_aggregations.roll_weighted_sum
- return self._apply(window_func, name="sum", **kwargs)
+ # error: Argument 1 to "_apply" of "Window" has incompatible type
+ # "Callable[[ndarray, ndarray, int], ndarray]"; expected
+ # "Callable[[ndarray, int, int], ndarray]"
+ return self._apply(window_func, name="sum", **kwargs) # type: ignore[arg-type]
@doc(
template_header,
@@ -1068,7 +1071,10 @@ def sum(self, *args, **kwargs):
def mean(self, *args, **kwargs):
nv.validate_window_func("mean", args, kwargs)
window_func = window_aggregations.roll_weighted_mean
- return self._apply(window_func, name="mean", **kwargs)
+ # error: Argument 1 to "_apply" of "Window" has incompatible type
+ # "Callable[[ndarray, ndarray, int], ndarray]"; expected
+ # "Callable[[ndarray, int, int], ndarray]"
+ return self._apply(window_func, name="mean", **kwargs) # type: ignore[arg-type]
@doc(
template_header,
| @mroeschke the type:ignores added in ewm.py look like potential bugs. any thoughts? | https://api.github.com/repos/pandas-dev/pandas/pulls/41029 | 2021-04-19T03:52:38Z | 2021-04-28T00:46:56Z | 2021-04-28T00:46:56Z | 2021-04-28T01:06:37Z |
[ArrowStringArray] implement ArrowStringArray._str_contains | diff --git a/asv_bench/benchmarks/strings.py b/asv_bench/benchmarks/strings.py
index 5d9b1c135d7ae..45a9053954569 100644
--- a/asv_bench/benchmarks/strings.py
+++ b/asv_bench/benchmarks/strings.py
@@ -213,13 +213,18 @@ def time_cat(self, other_cols, sep, na_rep, na_frac):
class Contains:
- params = [True, False]
- param_names = ["regex"]
+ params = (["str", "string", "arrow_string"], [True, False])
+ param_names = ["dtype", "regex"]
+
+ def setup(self, dtype, regex):
+ from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401
- def setup(self, regex):
- self.s = Series(tm.makeStringIndex(10 ** 5))
+ try:
+ self.s = Series(tm.makeStringIndex(10 ** 5), dtype=dtype)
+ except ImportError:
+ raise NotImplementedError
- def time_contains(self, regex):
+ def time_contains(self, dtype, regex):
self.s.str.contains("A", regex=regex)
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index 55cb350d3d27c..b7a0e70180ae4 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -759,6 +759,16 @@ def _str_map(self, f, na_value=None, dtype: Dtype | None = None):
# -> We don't know the result type. E.g. `.get` can return anything.
return lib.map_infer_mask(arr, f, mask.view("uint8"))
+ def _str_contains(self, pat, case=True, flags=0, na=np.nan, regex=True):
+ if not regex and case:
+ result = pc.match_substring(self._data, pat)
+ result = BooleanDtype().__from_arrow__(result)
+ if not isna(na):
+ result[isna(result)] = bool(na)
+ return result
+ else:
+ return super()._str_contains(pat, case, flags, na, regex)
+
def _str_isalnum(self):
if hasattr(pc, "utf8_is_alnum"):
result = pc.utf8_is_alnum(self._data)
diff --git a/pandas/tests/strings/test_find_replace.py b/pandas/tests/strings/test_find_replace.py
index ab95b2071ae10..d801d3457027f 100644
--- a/pandas/tests/strings/test_find_replace.py
+++ b/pandas/tests/strings/test_find_replace.py
@@ -4,6 +4,8 @@
import numpy as np
import pytest
+import pandas.util._test_decorators as td
+
import pandas as pd
from pandas import (
Index,
@@ -12,79 +14,118 @@
)
-def test_contains():
+@pytest.fixture(
+ params=[
+ "object",
+ "string",
+ pytest.param(
+ "arrow_string", marks=td.skip_if_no("pyarrow", min_version="1.0.0")
+ ),
+ ]
+)
+def any_string_dtype(request):
+ """
+ Parametrized fixture for string dtypes.
+ * 'object'
+ * 'string'
+ * 'arrow_string'
+ """
+ from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401
+
+ return request.param
+
+
+def test_contains(any_string_dtype):
values = np.array(
["foo", np.nan, "fooommm__foo", "mmm_", "foommm[_]+bar"], dtype=np.object_
)
- values = Series(values)
+ values = Series(values, dtype=any_string_dtype)
pat = "mmm[_]+"
result = values.str.contains(pat)
- expected = Series(np.array([False, np.nan, True, True, False], dtype=np.object_))
+ expected_dtype = "object" if any_string_dtype == "object" else "boolean"
+ expected = Series(
+ np.array([False, np.nan, True, True, False], dtype=np.object_),
+ dtype=expected_dtype,
+ )
tm.assert_series_equal(result, expected)
result = values.str.contains(pat, regex=False)
- expected = Series(np.array([False, np.nan, False, False, True], dtype=np.object_))
+ expected = Series(
+ np.array([False, np.nan, False, False, True], dtype=np.object_),
+ dtype=expected_dtype,
+ )
tm.assert_series_equal(result, expected)
- values = Series(np.array(["foo", "xyz", "fooommm__foo", "mmm_"], dtype=object))
+ values = Series(
+ np.array(["foo", "xyz", "fooommm__foo", "mmm_"], dtype=object),
+ dtype=any_string_dtype,
+ )
result = values.str.contains(pat)
- expected = Series(np.array([False, False, True, True]))
- assert result.dtype == np.bool_
+ expected_dtype = np.bool_ if any_string_dtype == "object" else "boolean"
+ expected = Series(np.array([False, False, True, True]), dtype=expected_dtype)
tm.assert_series_equal(result, expected)
# case insensitive using regex
- values = Series(np.array(["Foo", "xYz", "fOOomMm__fOo", "MMM_"], dtype=object))
+ values = Series(
+ np.array(["Foo", "xYz", "fOOomMm__fOo", "MMM_"], dtype=object),
+ dtype=any_string_dtype,
+ )
result = values.str.contains("FOO|mmm", case=False)
- expected = Series(np.array([True, False, True, True]))
+ expected = Series(np.array([True, False, True, True]), dtype=expected_dtype)
tm.assert_series_equal(result, expected)
# case insensitive without regex
- result = Series(values).str.contains("foo", regex=False, case=False)
- expected = Series(np.array([True, False, True, False]))
+ result = values.str.contains("foo", regex=False, case=False)
+ expected = Series(np.array([True, False, True, False]), dtype=expected_dtype)
tm.assert_series_equal(result, expected)
- # mixed
+ # unicode
+ values = Series(
+ np.array(["foo", np.nan, "fooommm__foo", "mmm_"], dtype=np.object_),
+ dtype=any_string_dtype,
+ )
+ pat = "mmm[_]+"
+
+ result = values.str.contains(pat)
+ expected_dtype = "object" if any_string_dtype == "object" else "boolean"
+ expected = Series(
+ np.array([False, np.nan, True, True], dtype=np.object_), dtype=expected_dtype
+ )
+ tm.assert_series_equal(result, expected)
+
+ result = values.str.contains(pat, na=False)
+ expected_dtype = np.bool_ if any_string_dtype == "object" else "boolean"
+ expected = Series(np.array([False, False, True, True]), dtype=expected_dtype)
+ tm.assert_series_equal(result, expected)
+
+ values = Series(
+ np.array(["foo", "xyz", "fooommm__foo", "mmm_"], dtype=np.object_),
+ dtype=any_string_dtype,
+ )
+ result = values.str.contains(pat)
+ expected = Series(np.array([False, False, True, True]), dtype=expected_dtype)
+ tm.assert_series_equal(result, expected)
+
+
+def test_contains_object_mixed():
mixed = Series(
np.array(
["a", np.nan, "b", True, datetime.today(), "foo", None, 1, 2.0],
dtype=object,
)
)
- rs = mixed.str.contains("o")
- xp = Series(
+ result = mixed.str.contains("o")
+ expected = Series(
np.array(
[False, np.nan, False, np.nan, np.nan, True, np.nan, np.nan, np.nan],
dtype=np.object_,
)
)
- tm.assert_series_equal(rs, xp)
-
- rs = mixed.str.contains("o")
- xp = Series([False, np.nan, False, np.nan, np.nan, True, np.nan, np.nan, np.nan])
- assert isinstance(rs, Series)
- tm.assert_series_equal(rs, xp)
-
- # unicode
- values = Series(np.array(["foo", np.nan, "fooommm__foo", "mmm_"], dtype=np.object_))
- pat = "mmm[_]+"
-
- result = values.str.contains(pat)
- expected = Series(np.array([False, np.nan, True, True], dtype=np.object_))
- tm.assert_series_equal(result, expected)
-
- result = values.str.contains(pat, na=False)
- expected = Series(np.array([False, False, True, True]))
- tm.assert_series_equal(result, expected)
-
- values = Series(np.array(["foo", "xyz", "fooommm__foo", "mmm_"], dtype=np.object_))
- result = values.str.contains(pat)
- expected = Series(np.array([False, False, True, True]))
- assert result.dtype == np.bool_
tm.assert_series_equal(result, expected)
-def test_contains_for_object_category():
+def test_contains_na_kwarg_for_object_category():
# gh 22158
# na for category
@@ -108,6 +149,29 @@ def test_contains_for_object_category():
tm.assert_series_equal(result, expected)
+@pytest.mark.parametrize(
+ "na, expected",
+ [
+ (None, pd.NA),
+ (True, True),
+ (False, False),
+ (0, False),
+ (3, True),
+ (np.nan, pd.NA),
+ ],
+)
+@pytest.mark.parametrize("regex", [True, False])
+def test_contains_na_kwarg_for_nullable_string_dtype(
+ nullable_string_dtype, na, expected, regex
+):
+ # https://github.com/pandas-dev/pandas/pull/41025#issuecomment-824062416
+
+ values = Series(["a", "b", "c", "a", np.nan], dtype=nullable_string_dtype)
+ result = values.str.contains("a", na=na, regex=regex)
+ expected = Series([True, False, False, True, expected], dtype="boolean")
+ tm.assert_series_equal(result, expected)
+
+
@pytest.mark.parametrize("dtype", [None, "category"])
@pytest.mark.parametrize("null_value", [None, np.nan, pd.NA])
@pytest.mark.parametrize("na", [True, False])
@@ -508,59 +572,73 @@ def _check(result, expected):
tm.assert_series_equal(result, expected)
-def test_contains_moar():
+def test_contains_moar(any_string_dtype):
# PR #1179
- s = Series(["A", "B", "C", "Aaba", "Baca", "", np.nan, "CABA", "dog", "cat"])
+ s = Series(
+ ["A", "B", "C", "Aaba", "Baca", "", np.nan, "CABA", "dog", "cat"],
+ dtype=any_string_dtype,
+ )
result = s.str.contains("a")
+ expected_dtype = "object" if any_string_dtype == "object" else "boolean"
expected = Series(
- [False, False, False, True, True, False, np.nan, False, False, True]
+ [False, False, False, True, True, False, np.nan, False, False, True],
+ dtype=expected_dtype,
)
tm.assert_series_equal(result, expected)
result = s.str.contains("a", case=False)
expected = Series(
- [True, False, False, True, True, False, np.nan, True, False, True]
+ [True, False, False, True, True, False, np.nan, True, False, True],
+ dtype=expected_dtype,
)
tm.assert_series_equal(result, expected)
result = s.str.contains("Aa")
expected = Series(
- [False, False, False, True, False, False, np.nan, False, False, False]
+ [False, False, False, True, False, False, np.nan, False, False, False],
+ dtype=expected_dtype,
)
tm.assert_series_equal(result, expected)
result = s.str.contains("ba")
expected = Series(
- [False, False, False, True, False, False, np.nan, False, False, False]
+ [False, False, False, True, False, False, np.nan, False, False, False],
+ dtype=expected_dtype,
)
tm.assert_series_equal(result, expected)
result = s.str.contains("ba", case=False)
expected = Series(
- [False, False, False, True, True, False, np.nan, True, False, False]
+ [False, False, False, True, True, False, np.nan, True, False, False],
+ dtype=expected_dtype,
)
tm.assert_series_equal(result, expected)
-def test_contains_nan():
+def test_contains_nan(any_string_dtype):
# PR #14171
- s = Series([np.nan, np.nan, np.nan], dtype=np.object_)
+ s = Series([np.nan, np.nan, np.nan], dtype=any_string_dtype)
result = s.str.contains("foo", na=False)
- expected = Series([False, False, False], dtype=np.bool_)
+ expected_dtype = np.bool_ if any_string_dtype == "object" else "boolean"
+ expected = Series([False, False, False], dtype=expected_dtype)
tm.assert_series_equal(result, expected)
result = s.str.contains("foo", na=True)
- expected = Series([True, True, True], dtype=np.bool_)
+ expected = Series([True, True, True], dtype=expected_dtype)
tm.assert_series_equal(result, expected)
result = s.str.contains("foo", na="foo")
- expected = Series(["foo", "foo", "foo"], dtype=np.object_)
+ if any_string_dtype == "object":
+ expected = Series(["foo", "foo", "foo"], dtype=np.object_)
+ else:
+ expected = Series([True, True, True], dtype="boolean")
tm.assert_series_equal(result, expected)
result = s.str.contains("foo")
- expected = Series([np.nan, np.nan, np.nan], dtype=np.object_)
+ expected_dtype = "object" if any_string_dtype == "object" else "boolean"
+ expected = Series([np.nan, np.nan, np.nan], dtype=expected_dtype)
tm.assert_series_equal(result, expected)
@@ -609,14 +687,14 @@ def test_replace_moar():
tm.assert_series_equal(result, expected)
-def test_match_findall_flags():
+def test_flags_kwarg(any_string_dtype):
data = {
"Dave": "dave@google.com",
"Steve": "steve@gmail.com",
"Rob": "rob@gmail.com",
"Wes": np.nan,
}
- data = Series(data)
+ data = Series(data, dtype=any_string_dtype)
pat = r"([A-Z0-9._%+-]+)@([A-Z0-9.-]+)\.([A-Z]{2,4})"
| not yet dealt with `na`. no tests are failing so we need tests for this.
we can either use the fallback when `na` is specified or handle `na` in the array method, which may be more performant.
should we replicate StringArray:
```
>>> s = pd.Series(["Mouse", "dog", "house and parrot", "23", np.NaN], dtype="string")
>>>
>>> s.str.contains("og", na=3, regex=False)
0 False
1 True
2 False
3 False
4 True
dtype: boolean
>>>
>>> s.str.contains("og", na=np.nan, regex=False)
0 False
1 True
2 False
3 False
4 <NA>
dtype: boolean
>>>
```
or return an object array to preserve `na` if not pd.NA, True or False instead of coercing to bool/null? | https://api.github.com/repos/pandas-dev/pandas/pulls/41025 | 2021-04-18T19:41:59Z | 2021-04-26T12:15:39Z | 2021-04-26T12:15:39Z | 2021-05-01T15:51:56Z |
REF: pass arguments to Index._foo_indexer correctly | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 310ee4c3a63e3..7f969ea5a26af 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -302,23 +302,47 @@ class Index(IndexOpsMixin, PandasObject):
# for why we need to wrap these instead of making them class attributes
# Moreover, cython will choose the appropriate-dtyped sub-function
# given the dtypes of the passed arguments
- def _left_indexer_unique(self, left: np.ndarray, right: np.ndarray) -> np.ndarray:
- return libjoin.left_join_indexer_unique(left, right)
+ @final
+ def _left_indexer_unique(self: _IndexT, other: _IndexT) -> np.ndarray:
+ # -> np.ndarray[np.intp]
+ # Caller is responsible for ensuring other.dtype == self.dtype
+ sv = self._get_join_target()
+ ov = other._get_join_target()
+ return libjoin.left_join_indexer_unique(sv, ov)
+
+ @final
def _left_indexer(
- self, left: np.ndarray, right: np.ndarray
- ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
- return libjoin.left_join_indexer(left, right)
+ self: _IndexT, other: _IndexT
+ ) -> tuple[ArrayLike, np.ndarray, np.ndarray]:
+ # Caller is responsible for ensuring other.dtype == self.dtype
+ sv = self._get_join_target()
+ ov = other._get_join_target()
+ joined_ndarray, lidx, ridx = libjoin.left_join_indexer(sv, ov)
+ joined = self._from_join_target(joined_ndarray)
+ return joined, lidx, ridx
+ @final
def _inner_indexer(
- self, left: np.ndarray, right: np.ndarray
- ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
- return libjoin.inner_join_indexer(left, right)
+ self: _IndexT, other: _IndexT
+ ) -> tuple[ArrayLike, np.ndarray, np.ndarray]:
+ # Caller is responsible for ensuring other.dtype == self.dtype
+ sv = self._get_join_target()
+ ov = other._get_join_target()
+ joined_ndarray, lidx, ridx = libjoin.inner_join_indexer(sv, ov)
+ joined = self._from_join_target(joined_ndarray)
+ return joined, lidx, ridx
+ @final
def _outer_indexer(
- self, left: np.ndarray, right: np.ndarray
- ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
- return libjoin.outer_join_indexer(left, right)
+ self: _IndexT, other: _IndexT
+ ) -> tuple[ArrayLike, np.ndarray, np.ndarray]:
+ # Caller is responsible for ensuring other.dtype == self.dtype
+ sv = self._get_join_target()
+ ov = other._get_join_target()
+ joined_ndarray, lidx, ridx = libjoin.outer_join_indexer(sv, ov)
+ joined = self._from_join_target(joined_ndarray)
+ return joined, lidx, ridx
_typ = "index"
_data: ExtensionArray | np.ndarray
@@ -2965,11 +2989,7 @@ def _union(self, other: Index, sort):
):
# Both are unique and monotonic, so can use outer join
try:
- # error: Argument 1 to "_outer_indexer" of "Index" has incompatible type
- # "Union[ExtensionArray, ndarray]"; expected "ndarray"
- # error: Argument 2 to "_outer_indexer" of "Index" has incompatible type
- # "Union[ExtensionArray, ndarray]"; expected "ndarray"
- return self._outer_indexer(lvals, rvals)[0] # type: ignore[arg-type]
+ return self._outer_indexer(other)[0]
except (TypeError, IncompatibleFrequency):
# incomparable objects
value_list = list(lvals)
@@ -3090,13 +3110,10 @@ def _intersection(self, other: Index, sort=False):
"""
# TODO(EA): setops-refactor, clean all this up
lvals = self._values
- rvals = other._values
if self.is_monotonic and other.is_monotonic:
try:
- # error: Argument 1 to "_inner_indexer" of "Index" has incompatible type
- # "Union[ExtensionArray, ndarray]"; expected "ndarray"
- result = self._inner_indexer(lvals, rvals)[0] # type: ignore[arg-type]
+ result = self._inner_indexer(other)[0]
except TypeError:
pass
else:
@@ -4095,8 +4112,8 @@ def _join_non_unique(self, other, how="left"):
# We only get here if dtypes match
assert self.dtype == other.dtype
- lvalues = self._get_engine_target()
- rvalues = other._get_engine_target()
+ lvalues = self._get_join_target()
+ rvalues = other._get_join_target()
left_idx, right_idx = get_join_indexers(
[lvalues], [rvalues], how=how, sort=True
@@ -4109,7 +4126,8 @@ def _join_non_unique(self, other, how="left"):
mask = left_idx == -1
np.putmask(join_array, mask, rvalues.take(right_idx))
- join_index = self._wrap_joined_index(join_array, other)
+ join_arraylike = self._from_join_target(join_array)
+ join_index = self._wrap_joined_index(join_arraylike, other)
return join_index, left_idx, right_idx
@@ -4267,9 +4285,6 @@ def _join_monotonic(self, other: Index, how="left"):
ret_index = other if how == "right" else self
return ret_index, None, None
- sv = self._get_engine_target()
- ov = other._get_engine_target()
-
ridx: np.ndarray | None
lidx: np.ndarray | None
@@ -4278,26 +4293,26 @@ def _join_monotonic(self, other: Index, how="left"):
if how == "left":
join_index = self
lidx = None
- ridx = self._left_indexer_unique(sv, ov)
+ ridx = self._left_indexer_unique(other)
elif how == "right":
join_index = other
- lidx = self._left_indexer_unique(ov, sv)
+ lidx = other._left_indexer_unique(self)
ridx = None
elif how == "inner":
- join_array, lidx, ridx = self._inner_indexer(sv, ov)
+ join_array, lidx, ridx = self._inner_indexer(other)
join_index = self._wrap_joined_index(join_array, other)
elif how == "outer":
- join_array, lidx, ridx = self._outer_indexer(sv, ov)
+ join_array, lidx, ridx = self._outer_indexer(other)
join_index = self._wrap_joined_index(join_array, other)
else:
if how == "left":
- join_array, lidx, ridx = self._left_indexer(sv, ov)
+ join_array, lidx, ridx = self._left_indexer(other)
elif how == "right":
- join_array, ridx, lidx = self._left_indexer(ov, sv)
+ join_array, ridx, lidx = other._left_indexer(self)
elif how == "inner":
- join_array, lidx, ridx = self._inner_indexer(sv, ov)
+ join_array, lidx, ridx = self._inner_indexer(other)
elif how == "outer":
- join_array, lidx, ridx = self._outer_indexer(sv, ov)
+ join_array, lidx, ridx = self._outer_indexer(other)
join_index = self._wrap_joined_index(join_array, other)
@@ -4305,9 +4320,7 @@ def _join_monotonic(self, other: Index, how="left"):
ridx = None if ridx is None else ensure_platform_int(ridx)
return join_index, lidx, ridx
- def _wrap_joined_index(
- self: _IndexT, joined: np.ndarray, other: _IndexT
- ) -> _IndexT:
+ def _wrap_joined_index(self: _IndexT, joined: ArrayLike, other: _IndexT) -> _IndexT:
assert other.dtype == self.dtype
if isinstance(self, ABCMultiIndex):
@@ -4385,6 +4398,19 @@ def _get_engine_target(self) -> np.ndarray:
# ndarray]", expected "ndarray")
return self._values # type: ignore[return-value]
+ def _get_join_target(self) -> np.ndarray:
+ """
+ Get the ndarray that we will pass to libjoin functions.
+ """
+ return self._get_engine_target()
+
+ def _from_join_target(self, result: np.ndarray) -> ArrayLike:
+ """
+ Cast the ndarray returned from one of the libjoin.foo_indexer functions
+ back to type(self)._data.
+ """
+ return result
+
@doc(IndexOpsMixin._memory_usage)
def memory_usage(self, deep: bool = False) -> int:
result = self._memory_usage(deep=deep)
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index 7bc0655ea9529..b2d2c98c08f68 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -20,7 +20,6 @@
NaT,
Timedelta,
iNaT,
- join as libjoin,
lib,
)
from pandas._libs.tslibs import (
@@ -75,36 +74,6 @@
_T = TypeVar("_T", bound="DatetimeIndexOpsMixin")
-def _join_i8_wrapper(joinf, with_indexers: bool = True):
- """
- Create the join wrapper methods.
- """
-
- # error: 'staticmethod' used with a non-method
- @staticmethod # type: ignore[misc]
- def wrapper(left, right):
- # Note: these only get called with left.dtype == right.dtype
- orig_left = left
-
- left = left.view("i8")
- right = right.view("i8")
-
- results = joinf(left, right)
- if with_indexers:
-
- join_index, left_indexer, right_indexer = results
- if not isinstance(orig_left, np.ndarray):
- # When called from Index._intersection/_union, we have the EA
- join_index = join_index.view(orig_left._ndarray.dtype)
- join_index = orig_left._from_backing_data(join_index)
-
- return join_index, left_indexer, right_indexer
-
- return results
-
- return wrapper
-
-
@inherit_names(
["inferred_freq", "_resolution_obj", "resolution"],
DatetimeLikeArrayMixin,
@@ -603,13 +572,6 @@ def insert(self, loc: int, item):
# --------------------------------------------------------------------
# Join/Set Methods
- _inner_indexer = _join_i8_wrapper(libjoin.inner_join_indexer)
- _outer_indexer = _join_i8_wrapper(libjoin.outer_join_indexer)
- _left_indexer = _join_i8_wrapper(libjoin.left_join_indexer)
- _left_indexer_unique = _join_i8_wrapper(
- libjoin.left_join_indexer_unique, with_indexers=False
- )
-
def _get_join_freq(self, other):
"""
Get the freq to attach to the result of a join operation.
@@ -621,14 +583,22 @@ def _get_join_freq(self, other):
freq = self.freq if self._can_fast_union(other) else None
return freq
- def _wrap_joined_index(self, joined: np.ndarray, other):
+ def _wrap_joined_index(self, joined, other):
assert other.dtype == self.dtype, (other.dtype, self.dtype)
- assert joined.dtype == "i8" or joined.dtype == self.dtype, joined.dtype
- joined = joined.view(self._data._ndarray.dtype)
result = super()._wrap_joined_index(joined, other)
result._data._freq = self._get_join_freq(other)
return result
+ def _get_join_target(self) -> np.ndarray:
+ return self._data._ndarray.view("i8")
+
+ def _from_join_target(self, result: np.ndarray):
+ # view e.g. i8 back to M8[ns]
+ result = result.view(self._data._ndarray.dtype)
+ return self._data._from_backing_data(result)
+
+ # --------------------------------------------------------------------
+
@doc(Index._convert_arr_indexer)
def _convert_arr_indexer(self, keyarr):
try:
diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py
index b11ec06120e0c..d593ddc640967 100644
--- a/pandas/core/indexes/extension.py
+++ b/pandas/core/indexes/extension.py
@@ -11,6 +11,7 @@
import numpy as np
+from pandas._typing import ArrayLike
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
from pandas.util._decorators import (
@@ -300,6 +301,11 @@ def searchsorted(self, value, side="left", sorter=None) -> np.ndarray:
def _get_engine_target(self) -> np.ndarray:
return np.asarray(self._data)
+ def _from_join_target(self, result: np.ndarray) -> ArrayLike:
+ # ATM this is only for IntervalIndex, implicit assumption
+ # about _get_engine_target
+ return type(self._data)._from_sequence(result, dtype=self.dtype)
+
def delete(self, loc):
"""
Make new Index with passed location(-s) deleted
@@ -410,6 +416,10 @@ def _simple_new(
def _get_engine_target(self) -> np.ndarray:
return self._data._ndarray
+ def _from_join_target(self, result: np.ndarray) -> ArrayLike:
+ assert result.dtype == self._data._ndarray.dtype
+ return self._data._from_backing_data(result)
+
def insert(self: _T, loc: int, item) -> Index:
"""
Make new Index inserting new item at location. Follows
@@ -458,7 +468,11 @@ def putmask(self, mask, value) -> Index:
return type(self)._simple_new(res_values, name=self.name)
- def _wrap_joined_index(self: _T, joined: np.ndarray, other: _T) -> _T:
+ # error: Argument 1 of "_wrap_joined_index" is incompatible with supertype
+ # "Index"; supertype defines the argument type as "Union[ExtensionArray, ndarray]"
+ def _wrap_joined_index( # type: ignore[override]
+ self: _T, joined: NDArrayBackedExtensionArray, other: _T
+ ) -> _T:
name = get_op_result_name(self, other)
- arr = self._data._from_backing_data(joined)
- return type(self)._simple_new(arr, name=name)
+
+ return type(self)._simple_new(joined, name=name)
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 59ff128713aca..794f13bbfb6b1 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -3613,14 +3613,12 @@ def _maybe_match_names(self, other):
def _intersection(self, other, sort=False) -> MultiIndex:
other, result_names = self._convert_can_do_setop(other)
-
- lvals = self._values
- rvals = other._values.astype(object, copy=False)
+ other = other.astype(object, copy=False)
uniq_tuples = None # flag whether _inner_indexer was successful
if self.is_monotonic and other.is_monotonic:
try:
- inner_tuples = self._inner_indexer(lvals, rvals)[0]
+ inner_tuples = self._inner_indexer(other)[0]
sort = False # inner_tuples is already sorted
except TypeError:
pass
diff --git a/pandas/tests/indexes/period/test_join.py b/pandas/tests/indexes/period/test_join.py
index 77dcd38b239ec..b8b15708466cb 100644
--- a/pandas/tests/indexes/period/test_join.py
+++ b/pandas/tests/indexes/period/test_join.py
@@ -15,7 +15,7 @@ class TestJoin:
def test_join_outer_indexer(self):
pi = period_range("1/1/2000", "1/20/2000", freq="D")
- result = pi._outer_indexer(pi._values, pi._values)
+ result = pi._outer_indexer(pi)
tm.assert_extension_array_equal(result[0], pi._values)
tm.assert_numpy_array_equal(result[1], np.arange(len(pi), dtype=np.intp))
tm.assert_numpy_array_equal(result[2], np.arange(len(pi), dtype=np.intp))
| ATM when we call self._inner_indexer in Index._union it raises on CategoricalIndex bc we are calling it incorrectly. Fixing that required moving the unwrapping/wrapping for Index._foo_indexer closer to just around the cython calls. | https://api.github.com/repos/pandas-dev/pandas/pulls/41024 | 2021-04-18T18:27:47Z | 2021-04-19T13:41:50Z | 2021-04-19T13:41:50Z | 2021-04-19T14:55:09Z |
ENH: check for string and convert to list in DataFrame.dropna subset argument | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index 16ee728a4425a..d6ad5eb2003ce 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -177,6 +177,7 @@ Other enhancements
- :meth:`DataFrame.__pos__`, :meth:`DataFrame.__neg__` now retain ``ExtensionDtype`` dtypes (:issue:`43883`)
- The error raised when an optional dependency can't be imported now includes the original exception, for easier investigation (:issue:`43882`)
- Added :meth:`.ExponentialMovingWindow.sum` (:issue:`13297`)
+- :meth:`DataFrame.dropna` now accepts a single label as ``subset`` along with array-like (:issue:`41021`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index c29a67c4942db..2b2c11bc6eeb5 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -5931,7 +5931,7 @@ def dropna(
axis: Axis = 0,
how: str = "any",
thresh=None,
- subset=None,
+ subset: IndexLabel = None,
inplace: bool = False,
):
"""
@@ -5963,7 +5963,7 @@ def dropna(
thresh : int, optional
Require that many non-NA values.
- subset : array-like, optional
+ subset : column label or sequence of labels, optional
Labels along other axis to consider, e.g. if you are dropping rows
these would be a list of columns to include.
inplace : bool, default False
@@ -6047,11 +6047,14 @@ def dropna(
agg_obj = self
if subset is not None:
+ # subset needs to be list
+ if not is_list_like(subset):
+ subset = [subset]
ax = self._get_axis(agg_axis)
indices = ax.get_indexer_for(subset)
check = indices == -1
if check.any():
- raise KeyError(list(np.compress(check, subset)))
+ raise KeyError(np.array(subset)[check].tolist())
agg_obj = self.take(indices, axis=agg_axis)
count = agg_obj.count(axis=agg_axis)
diff --git a/pandas/tests/frame/methods/test_dropna.py b/pandas/tests/frame/methods/test_dropna.py
index bc2b48d3312d7..1207c2763db07 100644
--- a/pandas/tests/frame/methods/test_dropna.py
+++ b/pandas/tests/frame/methods/test_dropna.py
@@ -243,3 +243,27 @@ def test_dropna_pos_args_deprecation(self):
result = df.dropna(1)
expected = DataFrame({"a": [1, 2, 3]})
tm.assert_frame_equal(result, expected)
+
+ def test_set_single_column_subset(self):
+ # GH 41021
+ df = DataFrame({"A": [1, 2, 3], "B": list("abc"), "C": [4, np.NaN, 5]})
+ expected = DataFrame(
+ {"A": [1, 3], "B": list("ac"), "C": [4.0, 5.0]}, index=[0, 2]
+ )
+ result = df.dropna(subset="C")
+ tm.assert_frame_equal(result, expected)
+
+ def test_single_column_not_present_in_axis(self):
+ # GH 41021
+ df = DataFrame({"A": [1, 2, 3]})
+
+ # Column not present
+ with pytest.raises(KeyError, match="['D']"):
+ df.dropna(subset="D", axis=0)
+
+ def test_subset_is_nparray(self):
+ # GH 41021
+ df = DataFrame({"A": [1, 2, np.NaN], "B": list("abc"), "C": [4, np.NaN, 5]})
+ expected = DataFrame({"A": [1.0], "B": ["a"], "C": [4.0]})
+ result = df.dropna(subset=np.array(["A", "C"]))
+ tm.assert_frame_equal(result, expected)
| - [x] closes #41021
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41022 | 2021-04-18T18:04:22Z | 2021-10-18T15:48:48Z | 2021-10-18T15:48:47Z | 2021-10-18T15:48:58Z |
BUG: isna not returning copy for MaskedArray | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 85d9acff353be..1a11fffbf6b4e 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -749,6 +749,7 @@ Missing
- Bug in :class:`Grouper` now correctly propagates ``dropna`` argument and :meth:`DataFrameGroupBy.transform` now correctly handles missing values for ``dropna=True`` (:issue:`35612`)
- Bug in :func:`isna`, and :meth:`Series.isna`, :meth:`Index.isna`, :meth:`DataFrame.isna` (and the corresponding ``notna`` functions) not recognizing ``Decimal("NaN")`` objects (:issue:`39409`)
- Bug in :meth:`DataFrame.fillna` not accepting dictionary for ``downcast`` keyword (:issue:`40809`)
+- Bug in :func:`isna` not returning a copy of the mask for nullable types, causing any subsequent mask modification to change the original array (:issue:`40935`)
MultiIndex
^^^^^^^^^^
diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py
index 93de1cd91d625..11f9f645920ec 100644
--- a/pandas/core/arrays/masked.py
+++ b/pandas/core/arrays/masked.py
@@ -352,7 +352,7 @@ def _hasna(self) -> bool:
return self._mask.any() # type: ignore[return-value]
def isna(self) -> np.ndarray:
- return self._mask
+ return self._mask.copy()
@property
def _na_value(self):
diff --git a/pandas/tests/extension/base/missing.py b/pandas/tests/extension/base/missing.py
index c501694a7c2d5..3d43dc47b5280 100644
--- a/pandas/tests/extension/base/missing.py
+++ b/pandas/tests/extension/base/missing.py
@@ -1,7 +1,9 @@
import numpy as np
+import pytest
import pandas as pd
import pandas._testing as tm
+from pandas.api.types import is_sparse
from pandas.tests.extension.base.base import BaseExtensionTests
@@ -21,6 +23,17 @@ def test_isna(self, data_missing):
expected = pd.Series([], dtype=bool)
self.assert_series_equal(result, expected)
+ @pytest.mark.parametrize("na_func", ["isna", "notna"])
+ def test_isna_returns_copy(self, data_missing, na_func):
+ result = pd.Series(data_missing)
+ expected = result.copy()
+ mask = getattr(result, na_func)()
+ if is_sparse(mask):
+ mask = np.array(mask)
+
+ mask[:] = True
+ self.assert_series_equal(result, expected)
+
def test_dropna_array(self, data_missing):
result = data_missing.dropna()
expected = data_missing[[1]]
| - [x] closes #40935
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
Think further improvements like zero-copy access fall under #34873, so #40935 can be closed. | https://api.github.com/repos/pandas-dev/pandas/pulls/41020 | 2021-04-18T17:52:55Z | 2021-04-20T12:52:12Z | 2021-04-20T12:52:12Z | 2021-04-20T13:04:51Z |
Backport PR #41015 on branch 1.2.x (Revert "Skipt failing tests for numpy dev (#40877)") | diff --git a/pandas/tests/arrays/boolean/test_arithmetic.py b/pandas/tests/arrays/boolean/test_arithmetic.py
index 9b854a81f2def..01de64568a011 100644
--- a/pandas/tests/arrays/boolean/test_arithmetic.py
+++ b/pandas/tests/arrays/boolean/test_arithmetic.py
@@ -66,10 +66,7 @@ def test_div(left_array, right_array):
@pytest.mark.parametrize(
"opname",
[
- pytest.param(
- "floordiv",
- marks=pytest.mark.xfail(reason="NumpyDev GH#40874", strict=False),
- ),
+ "floordiv",
"mod",
pytest.param(
"pow", marks=pytest.mark.xfail(reason="TODO follow int8 behaviour? GH34686")
diff --git a/pandas/tests/arrays/masked/test_arithmetic.py b/pandas/tests/arrays/masked/test_arithmetic.py
index 34686f6052131..148b7092abb56 100644
--- a/pandas/tests/arrays/masked/test_arithmetic.py
+++ b/pandas/tests/arrays/masked/test_arithmetic.py
@@ -3,8 +3,6 @@
import numpy as np
import pytest
-from pandas.compat.numpy import is_numpy_dev
-
import pandas as pd
import pandas._testing as tm
from pandas.core.arrays import ExtensionArray
@@ -51,8 +49,6 @@ def test_array_scalar_like_equivalence(data, all_arithmetic_operators):
def test_array_NA(data, all_arithmetic_operators):
if "truediv" in all_arithmetic_operators:
pytest.skip("division with pd.NA raises")
- if "floordiv" in all_arithmetic_operators and is_numpy_dev:
- pytest.skip("NumpyDev behavior GH#40874")
data, _ = data
op = tm.get_op_from_name(all_arithmetic_operators)
check_skip(data, all_arithmetic_operators)
diff --git a/pandas/tests/extension/test_boolean.py b/pandas/tests/extension/test_boolean.py
index d15c822f22c14..86a0bc9213256 100644
--- a/pandas/tests/extension/test_boolean.py
+++ b/pandas/tests/extension/test_boolean.py
@@ -16,8 +16,6 @@
import numpy as np
import pytest
-from pandas.compat.numpy import is_numpy_dev
-
import pandas as pd
import pandas._testing as tm
from pandas.core.arrays.boolean import BooleanDtype
@@ -141,21 +139,6 @@ def _check_op(self, s, op, other, op_name, exc=NotImplementedError):
with pytest.raises(exc):
op(s, other)
- def test_arith_series_with_scalar(self, data, all_arithmetic_operators):
- if "floordiv" in all_arithmetic_operators and is_numpy_dev:
- pytest.skip("NumpyDev behavior GH#40874")
- super().test_arith_series_with_scalar(data, all_arithmetic_operators)
-
- def test_arith_series_with_array(self, data, all_arithmetic_operators):
- if "floordiv" in all_arithmetic_operators and is_numpy_dev:
- pytest.skip("NumpyDev behavior GH#40874")
- super().test_arith_series_with_scalar(data, all_arithmetic_operators)
-
- def test_divmod_series_array(self, data, data_for_twos):
- if is_numpy_dev:
- pytest.skip("NumpyDev behavior GH#40874")
- super().test_divmod_series_array(data, data_for_twos)
-
def _check_divmod_op(self, s, op, other, exc=None):
# override to not raise an error
super()._check_divmod_op(s, op, other, None)
| Backport pr #41015 | https://api.github.com/repos/pandas-dev/pandas/pulls/41019 | 2021-04-18T16:02:01Z | 2021-04-18T17:50:27Z | 2021-04-18T17:50:27Z | 2021-04-18T17:50:30Z |
[ArrowStringArray] fix test_astype_int, test_astype_float | diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index 219c52c4a65b9..a6835ab1325a0 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -31,14 +31,17 @@
from pandas.util._decorators import doc
from pandas.util._validators import validate_fillna_kwargs
+from pandas.core.dtypes.base import ExtensionDtype
from pandas.core.dtypes.common import (
is_array_like,
is_bool_dtype,
+ is_dtype_equal,
is_integer,
is_integer_dtype,
is_object_dtype,
is_scalar,
is_string_dtype,
+ pandas_dtype,
)
from pandas.core.dtypes.dtypes import register_extension_dtype
from pandas.core.dtypes.missing import isna
@@ -48,6 +51,7 @@
from pandas.core.arrays.base import ExtensionArray
from pandas.core.arrays.boolean import BooleanDtype
from pandas.core.arrays.integer import Int64Dtype
+from pandas.core.arrays.numeric import NumericDtype
from pandas.core.arrays.string_ import StringDtype
from pandas.core.indexers import (
check_array_indexer,
@@ -290,10 +294,14 @@ def to_numpy( # type: ignore[override]
"""
# TODO: copy argument is ignored
- if na_value is lib.no_default:
- na_value = self._dtype.na_value
- result = self._data.__array__(dtype=dtype)
- result[isna(result)] = na_value
+ result = np.array(self._data, dtype=dtype)
+ if self._data.null_count > 0:
+ if na_value is lib.no_default:
+ if dtype and np.issubdtype(dtype, np.floating):
+ return result
+ na_value = self._dtype.na_value
+ mask = self.isna()
+ result[mask] = na_value
return result
def __len__(self) -> int:
@@ -737,6 +745,24 @@ def value_counts(self, dropna: bool = True) -> Series:
return Series(counts, index=index).astype("Int64")
+ def astype(self, dtype, copy=True):
+ dtype = pandas_dtype(dtype)
+
+ if is_dtype_equal(dtype, self.dtype):
+ if copy:
+ return self.copy()
+ return self
+
+ elif isinstance(dtype, NumericDtype):
+ data = self._data.cast(pa.from_numpy_dtype(dtype.numpy_dtype))
+ return dtype.__from_arrow__(data)
+
+ elif isinstance(dtype, ExtensionDtype):
+ cls = dtype.construct_array_type()
+ return cls._from_sequence(self, dtype=dtype, copy=copy)
+
+ return super().astype(dtype, copy)
+
# ------------------------------------------------------------------------
# String methods interface
diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py
index e3b43c544a477..c9533e239abe0 100644
--- a/pandas/tests/arrays/string_/test_string.py
+++ b/pandas/tests/arrays/string_/test_string.py
@@ -3,6 +3,8 @@
Tests for the str accessors are in pandas/tests/strings/test_string_array.py
"""
+import re
+
import numpy as np
import pytest
@@ -325,12 +327,19 @@ def test_from_sequence_no_mutate(copy, cls, request):
tm.assert_numpy_array_equal(nan_arr, expected)
-def test_astype_int(dtype, request):
- if dtype == "arrow_string":
- reason = "Cannot interpret 'Int64Dtype()' as a data type"
- mark = pytest.mark.xfail(raises=TypeError, reason=reason)
- request.node.add_marker(mark)
+def test_astype_int(dtype):
+ arr = pd.array(["1", "2", "3"], dtype=dtype)
+ result = arr.astype("int64")
+ expected = np.array([1, 2, 3], dtype="int64")
+ tm.assert_numpy_array_equal(result, expected)
+
+ arr = pd.array(["1", pd.NA, "3"], dtype=dtype)
+ msg = re.escape("int() argument must be a string, a bytes-like object or a number")
+ with pytest.raises(TypeError, match=msg):
+ arr.astype("int64")
+
+def test_astype_nullable_int(dtype):
arr = pd.array(["1", pd.NA, "3"], dtype=dtype)
result = arr.astype("Int64")
@@ -338,19 +347,9 @@ def test_astype_int(dtype, request):
tm.assert_extension_array_equal(result, expected)
-def test_astype_float(dtype, any_float_allowed_nullable_dtype, request):
+def test_astype_float(dtype, any_float_allowed_nullable_dtype):
# Don't compare arrays (37974)
-
- if dtype == "arrow_string":
- if any_float_allowed_nullable_dtype in {"Float32", "Float64"}:
- reason = "Cannot interpret 'Float32Dtype()' as a data type"
- else:
- reason = "float() argument must be a string or a number, not 'NAType'"
- mark = pytest.mark.xfail(raises=TypeError, reason=reason)
- request.node.add_marker(mark)
-
ser = pd.Series(["1.1", pd.NA, "3.3"], dtype=dtype)
-
result = ser.astype(any_float_allowed_nullable_dtype)
expected = pd.Series([1.1, np.nan, 3.3], dtype=any_float_allowed_nullable_dtype)
tm.assert_series_equal(result, expected)
diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py
index bebe6948cff9c..ffaecf1576364 100644
--- a/pandas/tests/series/methods/test_astype.py
+++ b/pandas/tests/series/methods/test_astype.py
@@ -379,7 +379,9 @@ class TestAstypeString:
# currently no way to parse IntervalArray from a list of strings
],
)
- def test_astype_string_to_extension_dtype_roundtrip(self, data, dtype, request):
+ def test_astype_string_to_extension_dtype_roundtrip(
+ self, data, dtype, request, nullable_string_dtype
+ ):
if dtype == "boolean" or (
dtype in ("period[M]", "datetime64[ns]", "timedelta64[ns]") and NaT in data
):
@@ -389,7 +391,8 @@ def test_astype_string_to_extension_dtype_roundtrip(self, data, dtype, request):
request.node.add_marker(mark)
# GH-40351
s = Series(data, dtype=dtype)
- tm.assert_series_equal(s, s.astype("string").astype(dtype))
+ result = s.astype(nullable_string_dtype).astype(dtype)
+ tm.assert_series_equal(result, s)
class TestAstypeCategorical:
| https://api.github.com/repos/pandas-dev/pandas/pulls/41018 | 2021-04-18T14:11:39Z | 2021-05-31T16:21:07Z | 2021-05-31T16:21:07Z | 2021-05-31T17:23:04Z | |
Fix 33634: If aggregation function returns NaN the order of the index on the resulting df is not maintained | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 1eb22436204a8..6f39dc4917024 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -973,6 +973,7 @@ Other
- Bug in :meth:`DataFrame.equals`, :meth:`Series.equals`, :meth:`Index.equals` with object-dtype containing ``np.datetime64("NaT")`` or ``np.timedelta64("NaT")`` (:issue:`39650`)
- Bug in :func:`pandas.util.show_versions` where console JSON output was not proper JSON (:issue:`39701`)
- Bug in :meth:`DataFrame.convert_dtypes` incorrectly raised ValueError when called on an empty DataFrame (:issue:`40393`)
+- Bug in :meth:`DataFrame.agg()` not sorting the aggregated axis in the order of the provided aggragation functions when one or more aggregation function fails to produce results (:issue:`33634`)
- Bug in :meth:`DataFrame.clip` not interpreting missing values as no threshold (:issue:`40420`)
- Bug in :class:`Series` backed by :class:`DatetimeArray` or :class:`TimedeltaArray` sometimes failing to set the array's ``freq`` to ``None`` (:issue:`41425`)
diff --git a/pandas/core/apply.py b/pandas/core/apply.py
index d0c6a1a841edb..00b49c2f4f951 100644
--- a/pandas/core/apply.py
+++ b/pandas/core/apply.py
@@ -376,12 +376,10 @@ def agg_list_like(self) -> FrameOrSeriesUnion:
raise ValueError("no results")
try:
- return concat(results, keys=keys, axis=1, sort=False)
+ concatenated = concat(results, keys=keys, axis=1, sort=False)
except TypeError as err:
-
# we are concatting non-NDFrame objects,
# e.g. a list of scalars
-
from pandas import Series
result = Series(results, index=keys, name=obj.name)
@@ -390,6 +388,16 @@ def agg_list_like(self) -> FrameOrSeriesUnion:
"cannot combine transform and aggregation operations"
) from err
return result
+ else:
+ # Concat uses the first index to determine the final indexing order.
+ # The union of a shorter first index with the other indices causes
+ # the index sorting to be different from the order of the aggregating
+ # functions. Reindex if this is the case.
+ index_size = concatenated.index.size
+ full_ordered_index = next(
+ result.index for result in results if result.index.size == index_size
+ )
+ return concatenated.reindex(full_ordered_index, copy=False)
def agg_dict_like(self) -> FrameOrSeriesUnion:
"""
diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py
index fcccd0d846d0f..cc91cdae942fd 100644
--- a/pandas/tests/apply/test_frame_apply.py
+++ b/pandas/tests/apply/test_frame_apply.py
@@ -1110,10 +1110,9 @@ def test_agg_multiple_mixed_no_warning():
with tm.assert_produces_warning(None):
result = mdf[["D", "C", "B", "A"]].agg(["sum", "min"])
- # For backwards compatibility, the result's index is
- # still sorted by function name, so it's ['min', 'sum']
- # not ['sum', 'min'].
- expected = expected[["D", "C", "B", "A"]]
+ # GH40420: the result of .agg should have an index that is sorted
+ # according to the arguments provided to agg.
+ expected = expected[["D", "C", "B", "A"]].reindex(["sum", "min"])
tm.assert_frame_equal(result, expected)
@@ -1521,6 +1520,38 @@ def test_apply_np_reducer(float_frame, op, how):
tm.assert_series_equal(result, expected)
+def test_aggregation_func_column_order():
+ # GH40420: the result of .agg should have an index that is sorted
+ # according to the arguments provided to agg.
+ df = DataFrame(
+ [
+ ("1", 1, 0, 0),
+ ("2", 2, 0, 0),
+ ("3", 3, 0, 0),
+ ("4", 4, 5, 4),
+ ("5", 5, 6, 6),
+ ("6", 6, 7, 7),
+ ],
+ columns=("item", "att1", "att2", "att3"),
+ )
+
+ def foo(s):
+ return s.sum() / 2
+
+ aggs = ["sum", foo, "count", "min"]
+ result = df.agg(aggs)
+ expected = DataFrame(
+ {
+ "item": ["123456", np.nan, 6, "1"],
+ "att1": [21.0, 10.5, 6.0, 1.0],
+ "att2": [18.0, 9.0, 6.0, 0.0],
+ "att3": [17.0, 8.5, 6.0, 0.0],
+ },
+ index=["sum", "foo", "count", "min"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+
def test_apply_getitem_axis_1():
# GH 13427
df = DataFrame({"a": [0, 1, 2], "b": [1, 2, 3]})
| - [x] closes #33634
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41017 | 2021-04-18T13:44:15Z | 2021-05-21T01:16:05Z | 2021-05-21T01:16:05Z | 2021-05-21T01:16:15Z |
Revert "Skipt failing tests for numpy dev (#40877)" | diff --git a/pandas/tests/arrays/boolean/test_arithmetic.py b/pandas/tests/arrays/boolean/test_arithmetic.py
index 8e879372cba31..f8f1af4c3da51 100644
--- a/pandas/tests/arrays/boolean/test_arithmetic.py
+++ b/pandas/tests/arrays/boolean/test_arithmetic.py
@@ -69,10 +69,7 @@ def test_div(left_array, right_array):
@pytest.mark.parametrize(
"opname",
[
- pytest.param(
- "floordiv",
- marks=pytest.mark.xfail(reason="NumpyDev GH#40874", strict=False),
- ),
+ "floordiv",
"mod",
pytest.param(
"pow", marks=pytest.mark.xfail(reason="TODO follow int8 behaviour? GH34686")
diff --git a/pandas/tests/arrays/masked/test_arithmetic.py b/pandas/tests/arrays/masked/test_arithmetic.py
index 088a37f8615c0..adb52fce17f8b 100644
--- a/pandas/tests/arrays/masked/test_arithmetic.py
+++ b/pandas/tests/arrays/masked/test_arithmetic.py
@@ -6,8 +6,6 @@
import numpy as np
import pytest
-from pandas.compat import is_numpy_dev
-
import pandas as pd
import pandas._testing as tm
from pandas.core.arrays import ExtensionArray
@@ -54,8 +52,6 @@ def test_array_scalar_like_equivalence(data, all_arithmetic_operators):
def test_array_NA(data, all_arithmetic_operators):
if "truediv" in all_arithmetic_operators:
pytest.skip("division with pd.NA raises")
- if "floordiv" in all_arithmetic_operators and is_numpy_dev:
- pytest.skip("NumpyDev behavior GH#40874")
data, _ = data
op = tm.get_op_from_name(all_arithmetic_operators)
check_skip(data, all_arithmetic_operators)
diff --git a/pandas/tests/extension/test_boolean.py b/pandas/tests/extension/test_boolean.py
index 23ab80f200598..33d82a1d64fb7 100644
--- a/pandas/tests/extension/test_boolean.py
+++ b/pandas/tests/extension/test_boolean.py
@@ -16,8 +16,6 @@
import numpy as np
import pytest
-from pandas.compat import is_numpy_dev
-
import pandas as pd
import pandas._testing as tm
from pandas.core.arrays.boolean import BooleanDtype
@@ -142,26 +140,6 @@ def _check_op(self, obj, op, other, op_name, exc=NotImplementedError):
with pytest.raises(exc):
op(obj, other)
- def test_arith_series_with_scalar(self, data, all_arithmetic_operators):
- if "floordiv" in all_arithmetic_operators and is_numpy_dev:
- pytest.skip("NumpyDev behavior GH#40874")
- super().test_arith_series_with_scalar(data, all_arithmetic_operators)
-
- def test_arith_frame_with_scalar(self, data, all_arithmetic_operators):
- if "floordiv" in all_arithmetic_operators and is_numpy_dev:
- pytest.skip("NumpyDev behavior GH#40874")
- super().test_arith_frame_with_scalar(data, all_arithmetic_operators)
-
- def test_arith_series_with_array(self, data, all_arithmetic_operators):
- if "floordiv" in all_arithmetic_operators and is_numpy_dev:
- pytest.skip("NumpyDev behavior GH#40874")
- super().test_arith_series_with_scalar(data, all_arithmetic_operators)
-
- def test_divmod_series_array(self, data, data_for_twos):
- if is_numpy_dev:
- pytest.skip("NumpyDev behavior GH#40874")
- super().test_divmod_series_array(data, data_for_twos)
-
def _check_divmod_op(self, s, op, other, exc=None):
# override to not raise an error
super()._check_divmod_op(s, op, other, None)
| - [x] closes #40874
new numpy wheel is out, bug was fixed during the week
| https://api.github.com/repos/pandas-dev/pandas/pulls/41015 | 2021-04-18T11:13:42Z | 2021-04-18T15:55:39Z | 2021-04-18T15:55:39Z | 2021-04-18T16:03:01Z |
DOC: update `style.ipynb` user guide for recent enhancements | diff --git a/doc/source/user_guide/style.ipynb b/doc/source/user_guide/style.ipynb
index 765b2929d3014..86696cc909764 100644
--- a/doc/source/user_guide/style.ipynb
+++ b/doc/source/user_guide/style.ipynb
@@ -1006,7 +1006,30 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "We expect certain styling functions to be common enough that we've included a few \"built-in\" to the `Styler`, so you don't have to write them yourself."
+ "Some styling functions are common enough that we've \"built them in\" to the `Styler`, so you don't have to write them and apply them yourself. The current list of such functions is:\n",
+ "\n",
+ " - [.highlight_null][nullfunc]: for use with identifying missing data. \n",
+ " - [.highlight_min][minfunc] and [.highlight_max][maxfunc]: for use with identifying extremeties in data.\n",
+ " - [.highlight_between][betweenfunc] and [.highlight_quantile][quantilefunc]: for use with identifying classes within data.\n",
+ " - [.background_gradient][bgfunc]: a flexible method for highlighting cells based or their, or other, values on a numeric scale.\n",
+ " - [.bar][barfunc]: to display mini-charts within cell backgrounds.\n",
+ " \n",
+ "The individual documentation on each function often gives more examples of their arguments.\n",
+ "\n",
+ "[nullfunc]: ../reference/api/pandas.io.formats.style.Styler.highlight_null.rst\n",
+ "[minfunc]: ../reference/api/pandas.io.formats.style.Styler.highlight_min.rst\n",
+ "[maxfunc]: ../reference/api/pandas.io.formats.style.Styler.highlight_max.rst\n",
+ "[betweenfunc]: ../reference/api/pandas.io.formats.style.Styler.highlight_between.rst\n",
+ "[quantilefunc]: ../reference/api/pandas.io.formats.style.Styler.highlight_quantile.rst\n",
+ "[bgfunc]: ../reference/api/pandas.io.formats.style.Styler.background_gradient.rst\n",
+ "[barfunc]: ../reference/api/pandas.io.formats.style.Styler.bar.rst"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Highlight Null"
]
},
{
@@ -1017,14 +1040,14 @@
"source": [
"df2.iloc[0,2] = np.nan\n",
"df2.iloc[4,3] = np.nan\n",
- "df2.loc[:4].style.highlight_null(null_color='red')"
+ "df2.loc[:4].style.highlight_null(null_color='yellow')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "You can create \"heatmaps\" with the `background_gradient` method. These require matplotlib, and we'll use [Seaborn](https://stanford.edu/~mwaskom/software/seaborn/) to get a nice colormap."
+ "### Highlight Min or Max"
]
},
{
@@ -1033,17 +1056,15 @@
"metadata": {},
"outputs": [],
"source": [
- "import seaborn as sns\n",
- "cm = sns.light_palette(\"green\", as_cmap=True)\n",
- "\n",
- "df2.style.background_gradient(cmap=cm)"
+ "df2.loc[:4].style.highlight_max(axis=1, props='color:white; font-weight:bold; background-color:darkblue;')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "`Styler.background_gradient` takes the keyword arguments `low` and `high`. Roughly speaking these extend the range of your data by `low` and `high` percent so that when we convert the colors, the colormap's entire range isn't used. This is useful so that you can actually read the text still."
+ "### Highlight Between\n",
+ "This method accepts ranges as float, or NumPy arrays or Series provided the indexes match."
]
},
{
@@ -1052,8 +1073,16 @@
"metadata": {},
"outputs": [],
"source": [
- "# Uses the full color range\n",
- "df2.loc[:4].style.background_gradient(cmap='viridis')"
+ "left = pd.Series([1.0, 0.0, 1.0], index=[\"A\", \"B\", \"D\"])\n",
+ "df2.loc[:4].style.highlight_between(left=left, right=1.5, axis=1, props='color:white; background-color:purple;')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Highlight Quantile\n",
+ "Useful for detecting the highest or lowest percentile values"
]
},
{
@@ -1062,17 +1091,21 @@
"metadata": {},
"outputs": [],
"source": [
- "# Compress the color range\n",
- "df2.loc[:4].style\\\n",
- " .background_gradient(cmap='viridis', low=.5, high=0)\\\n",
- " .highlight_null('red')"
+ "df2.loc[:4].style.highlight_quantile(q_left=0.85, axis=None, color='yellow')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Background Gradient"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "There's also `.highlight_min` and `.highlight_max`, which is almost identical to the user defined version we created above, and also a `.highlight_null` method. "
+ "You can create \"heatmaps\" with the `background_gradient` method. These require matplotlib, and we'll use [Seaborn](https://stanford.edu/~mwaskom/software/seaborn/) to get a nice colormap."
]
},
{
@@ -1081,7 +1114,19 @@
"metadata": {},
"outputs": [],
"source": [
- "df2.loc[:4].style.highlight_max(axis=0)"
+ "import seaborn as sns\n",
+ "cm = sns.light_palette(\"green\", as_cmap=True)\n",
+ "\n",
+ "df2.style.background_gradient(cmap=cm)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "[.background_gradient][bgfunc] has a number of keyword arguments to customise the gradients and colors. See its documentation.\n",
+ "\n",
+ "[bgfunc]: ../reference/api/pandas.io.formats.style.Styler.background_gradient.rst"
]
},
{
| I added small changes to the Styler User Guide to exemplify the new builtin highlighting functions.
Also removed some of the longer detail which has been moved to individual documentation pages (for example for `background_gradient`) | https://api.github.com/repos/pandas-dev/pandas/pulls/41013 | 2021-04-18T06:02:13Z | 2021-04-21T18:31:39Z | 2021-04-21T18:31:39Z | 2021-04-22T10:34:56Z |
DOC: Improve describe() documentation | diff --git a/doc/source/getting_started/intro_tutorials/01_table_oriented.rst b/doc/source/getting_started/intro_tutorials/01_table_oriented.rst
index e8e0fef271a74..2dcc8b0abe3b8 100644
--- a/doc/source/getting_started/intro_tutorials/01_table_oriented.rst
+++ b/doc/source/getting_started/intro_tutorials/01_table_oriented.rst
@@ -176,7 +176,7 @@ these are by default not taken into account by the :func:`~DataFrame.describe` m
Many pandas operations return a ``DataFrame`` or a ``Series``. The
:func:`~DataFrame.describe` method is an example of a pandas operation returning a
-pandas ``Series``.
+pandas ``Series`` or a pandas ``DataFrame``.
.. raw:: html
| - [x] closes #40972
- [ ] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
It feels more verbose, but necessary? | https://api.github.com/repos/pandas-dev/pandas/pulls/41012 | 2021-04-18T05:52:26Z | 2021-04-20T04:26:26Z | 2021-04-20T04:26:26Z | 2021-04-20T04:26:36Z |
CLN: remove ensure_int_or_float | diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py
index 59550927299fe..e207dac71752e 100644
--- a/pandas/core/dtypes/common.py
+++ b/pandas/core/dtypes/common.py
@@ -128,51 +128,6 @@ def ensure_str(value: Union[bytes, Any]) -> str:
return value
-def ensure_int_or_float(arr: ArrayLike, copy: bool = False) -> np.ndarray:
- """
- Ensure that an dtype array of some integer dtype
- has an int64 dtype if possible.
- If it's not possible, potentially because of overflow,
- convert the array to float64 instead.
-
- Parameters
- ----------
- arr : array-like
- The array whose data type we want to enforce.
- copy: bool
- Whether to copy the original array or reuse
- it in place, if possible.
-
- Returns
- -------
- out_arr : The input array cast as int64 if
- possible without overflow.
- Otherwise the input array cast to float64.
-
- Notes
- -----
- If the array is explicitly of type uint64 the type
- will remain unchanged.
- """
- # TODO: GH27506 potential bug with ExtensionArrays
- try:
- # error: Unexpected keyword argument "casting" for "astype"
- return arr.astype("int64", copy=copy, casting="safe") # type: ignore[call-arg]
- except TypeError:
- pass
- try:
- # error: Unexpected keyword argument "casting" for "astype"
- return arr.astype("uint64", copy=copy, casting="safe") # type: ignore[call-arg]
- except TypeError:
- if is_extension_array_dtype(arr.dtype):
- # pandas/core/dtypes/common.py:168: error: Item "ndarray" of
- # "Union[ExtensionArray, ndarray]" has no attribute "to_numpy" [union-attr]
- return arr.to_numpy( # type: ignore[union-attr]
- dtype="float64", na_value=np.nan
- )
- return arr.astype("float64", copy=copy)
-
-
def ensure_python_int(value: Union[int, np.integer]) -> int:
"""
Ensure that a value is a python int.
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 702d67b198e8d..da4e165dc5ceb 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -43,7 +43,6 @@
from pandas.core.dtypes.common import (
ensure_float64,
ensure_int64,
- ensure_int_or_float,
ensure_platform_int,
is_bool_dtype,
is_categorical_dtype,
@@ -582,7 +581,7 @@ def _ea_wrap_cython_operation(
elif is_integer_dtype(values.dtype) or is_bool_dtype(values.dtype):
# IntegerArray or BooleanArray
- values = ensure_int_or_float(values)
+ values = values.to_numpy("float64", na_value=np.nan)
res_values = self._cython_operation(
kind, values, how, axis, min_count, **kwargs
)
@@ -660,9 +659,11 @@ def _cython_operation(
values = values.view("int64")
is_numeric = True
elif is_bool_dtype(dtype):
- values = ensure_int_or_float(values)
+ values = values.astype("int64")
elif is_integer_dtype(dtype):
- values = ensure_int_or_float(values)
+ # e.g. uint8 -> uint64, int16 -> int64
+ dtype = dtype.kind + "8"
+ values = values.astype(dtype, copy=False)
elif is_numeric:
if not is_complex_dtype(dtype):
values = ensure_float64(values)
| - [x] closes #27506
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
No need for a try/except; we can reason out which branch we go down in each of the places this is used. | https://api.github.com/repos/pandas-dev/pandas/pulls/41011 | 2021-04-18T04:01:23Z | 2021-04-19T13:51:57Z | 2021-04-19T13:51:57Z | 2021-04-19T14:43:15Z |
BUG: groupby.rank with MaskedArray incorrect casting | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 1a11fffbf6b4e..2487b5fca591b 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -832,6 +832,7 @@ Groupby/resample/rolling
- Bug in :class:`core.window.RollingGroupby` where ``as_index=False`` argument in ``groupby`` was ignored (:issue:`39433`)
- Bug in :meth:`.GroupBy.any` and :meth:`.GroupBy.all` raising ``ValueError`` when using with nullable type columns holding ``NA`` even with ``skipna=True`` (:issue:`40585`)
- Bug in :meth:`GroupBy.cummin` and :meth:`GroupBy.cummax` incorrectly rounding integer values near the ``int64`` implementations bounds (:issue:`40767`)
+- Bug in :meth:`.GroupBy.rank` with nullable dtypes incorrectly raising ``TypeError`` (:issue:`41010`)
Reshaping
^^^^^^^^^
diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py
index 50248d5af8883..6c1d6847a0bde 100644
--- a/pandas/core/groupby/base.py
+++ b/pandas/core/groupby/base.py
@@ -122,8 +122,6 @@ def _gotitem(self, key, ndim, subset=None):
# require postprocessing of the result by transform.
cythonized_kernels = frozenset(["cumprod", "cumsum", "shift", "cummin", "cummax"])
-cython_cast_blocklist = frozenset(["rank", "count", "size", "idxmin", "idxmax"])
-
# List of aggregation/reduction functions.
# These map each group to a single numeric value
reduction_kernels = frozenset(
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index d9bf1adf74a5e..6eddf8e9e8773 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -58,7 +58,6 @@
is_timedelta64_dtype,
needs_i8_conversion,
)
-from pandas.core.dtypes.dtypes import ExtensionDtype
from pandas.core.dtypes.generic import ABCCategoricalIndex
from pandas.core.dtypes.missing import (
isna,
@@ -95,6 +94,10 @@ class WrappedCythonOp:
Dispatch logic for functions defined in _libs.groupby
"""
+ # Functions for which we do _not_ attempt to cast the cython result
+ # back to the original dtype.
+ cast_blocklist = frozenset(["rank", "count", "size", "idxmin", "idxmax"])
+
def __init__(self, kind: str, how: str):
self.kind = kind
self.how = how
@@ -564,11 +567,13 @@ def _ea_wrap_cython_operation(
if is_datetime64tz_dtype(values.dtype) or is_period_dtype(values.dtype):
# All of the functions implemented here are ordinal, so we can
# operate on the tz-naive equivalents
- values = values.view("M8[ns]")
+ npvalues = values.view("M8[ns]")
res_values = self._cython_operation(
- kind, values, how, axis, min_count, **kwargs
+ kind, npvalues, how, axis, min_count, **kwargs
)
if how in ["rank"]:
+ # i.e. how in WrappedCythonOp.cast_blocklist, since
+ # other cast_blocklist methods dont go through cython_operation
# preserve float64 dtype
return res_values
@@ -582,12 +587,16 @@ def _ea_wrap_cython_operation(
res_values = self._cython_operation(
kind, values, how, axis, min_count, **kwargs
)
- dtype = maybe_cast_result_dtype(orig_values.dtype, how)
- if isinstance(dtype, ExtensionDtype):
- cls = dtype.construct_array_type()
- return cls._from_sequence(res_values, dtype=dtype)
+ if how in ["rank"]:
+ # i.e. how in WrappedCythonOp.cast_blocklist, since
+ # other cast_blocklist methods dont go through cython_operation
+ return res_values
- return res_values
+ dtype = maybe_cast_result_dtype(orig_values.dtype, how)
+ # error: Item "dtype[Any]" of "Union[dtype[Any], ExtensionDtype]"
+ # has no attribute "construct_array_type"
+ cls = dtype.construct_array_type() # type: ignore[union-attr]
+ return cls._from_sequence(res_values, dtype=dtype)
elif is_float_dtype(values.dtype):
# FloatingArray
@@ -595,8 +604,16 @@ def _ea_wrap_cython_operation(
res_values = self._cython_operation(
kind, values, how, axis, min_count, **kwargs
)
- result = type(orig_values)._from_sequence(res_values)
- return result
+ if how in ["rank"]:
+ # i.e. how in WrappedCythonOp.cast_blocklist, since
+ # other cast_blocklist methods dont go through cython_operation
+ return res_values
+
+ dtype = maybe_cast_result_dtype(orig_values.dtype, how)
+ # error: Item "dtype[Any]" of "Union[dtype[Any], ExtensionDtype]"
+ # has no attribute "construct_array_type"
+ cls = dtype.construct_array_type() # type: ignore[union-attr]
+ return cls._from_sequence(res_values, dtype=dtype)
raise NotImplementedError(
f"function is not implemented for this dtype: {values.dtype}"
@@ -711,9 +728,9 @@ def _cython_operation(
result = result.T
- if how not in base.cython_cast_blocklist:
+ if how not in cy_op.cast_blocklist:
# e.g. if we are int64 and need to restore to datetime64/timedelta64
- # "rank" is the only member of cython_cast_blocklist we get here
+ # "rank" is the only member of cast_blocklist we get here
dtype = maybe_cast_result_dtype(orig_values.dtype, how)
op_result = maybe_downcast_to_dtype(result, dtype)
else:
diff --git a/pandas/tests/groupby/test_counting.py b/pandas/tests/groupby/test_counting.py
index 1317f0f68216a..73b2d8ac2c1f5 100644
--- a/pandas/tests/groupby/test_counting.py
+++ b/pandas/tests/groupby/test_counting.py
@@ -209,6 +209,7 @@ def test_ngroup_respects_groupby_order(self):
[
[Timestamp(f"2016-05-{i:02d} 20:09:25+00:00") for i in range(1, 4)],
[Timestamp(f"2016-05-{i:02d} 20:09:25") for i in range(1, 4)],
+ [Timestamp(f"2016-05-{i:02d} 20:09:25", tz="UTC") for i in range(1, 4)],
[Timedelta(x, unit="h") for x in range(1, 4)],
[Period(freq="2W", year=2017, month=x) for x in range(1, 4)],
],
diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py
index d7020e2ffd701..46985ff956788 100644
--- a/pandas/tests/groupby/test_function.py
+++ b/pandas/tests/groupby/test_function.py
@@ -495,6 +495,8 @@ def test_idxmin_idxmax_returns_int_types(func, values):
df["c_date_tz"] = df["c_date"].dt.tz_localize("US/Pacific")
df["c_timedelta"] = df["c_date"] - df["c_date"].iloc[0]
df["c_period"] = df["c_date"].dt.to_period("W")
+ df["c_Integer"] = df["c_int"].astype("Int64")
+ df["c_Floating"] = df["c_float"].astype("Float64")
result = getattr(df.groupby("name"), func)()
@@ -502,6 +504,8 @@ def test_idxmin_idxmax_returns_int_types(func, values):
expected["c_date_tz"] = expected["c_date"]
expected["c_timedelta"] = expected["c_date"]
expected["c_period"] = expected["c_date"]
+ expected["c_Integer"] = expected["c_int"]
+ expected["c_Floating"] = expected["c_float"]
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py
index 2dab22910a0c9..c5620d6d8c06c 100644
--- a/pandas/tests/groupby/test_groupby.py
+++ b/pandas/tests/groupby/test_groupby.py
@@ -1732,6 +1732,8 @@ def test_pivot_table_values_key_error():
[to_datetime(0)],
[date_range(0, 1, 1, tz="US/Eastern")],
[pd.array([0], dtype="Int64")],
+ [pd.array([0], dtype="Float64")],
+ [pd.array([False], dtype="boolean")],
],
)
@pytest.mark.parametrize("method", ["attr", "agg", "apply"])
diff --git a/pandas/tests/groupby/test_rank.py b/pandas/tests/groupby/test_rank.py
index 2e666c27386b4..da88ea5f05107 100644
--- a/pandas/tests/groupby/test_rank.py
+++ b/pandas/tests/groupby/test_rank.py
@@ -444,8 +444,19 @@ def test_rank_resets_each_group(pct, exp):
tm.assert_frame_equal(result, exp_df)
-def test_rank_avg_even_vals():
+@pytest.mark.parametrize(
+ "dtype", ["int64", "int32", "uint64", "uint32", "float64", "float32"]
+)
+@pytest.mark.parametrize("upper", [True, False])
+def test_rank_avg_even_vals(dtype, upper):
+ if upper:
+ # use IntegerDtype/FloatingDtype
+ dtype = dtype[0].upper() + dtype[1:]
+ dtype = dtype.replace("Ui", "UI")
df = DataFrame({"key": ["a"] * 4, "val": [1] * 4})
+ df["val"] = df["val"].astype(dtype)
+ assert df["val"].dtype == dtype
+
result = df.groupby("key").rank()
exp_df = DataFrame([2.5, 2.5, 2.5, 2.5], columns=["val"])
tm.assert_frame_equal(result, exp_df)
| - [ ] closes #xxxx
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
In master:
```
df = pd.DataFrame({"key": ["a"] * 4, "val": [1] * 4})
df["val"] = df["val"].astype("Int64")
>>> result = df.groupby("key").rank()
TypeError: cannot safely cast non-equivalent float64 to int64
```
Moves in the direction of sharing/generalizing _ea_wrap_cython_operation.
If I did this right, should avoid overlap with #40651. | https://api.github.com/repos/pandas-dev/pandas/pulls/41010 | 2021-04-18T03:23:27Z | 2021-04-20T22:56:41Z | 2021-04-20T22:56:41Z | 2021-04-20T22:59:10Z |
TYP: core.computation | diff --git a/pandas/core/computation/engines.py b/pandas/core/computation/engines.py
index 5b2dbed7af6ea..7452cf03d0038 100644
--- a/pandas/core/computation/engines.py
+++ b/pandas/core/computation/engines.py
@@ -12,6 +12,7 @@
align_terms,
reconstruct_object,
)
+from pandas.core.computation.expr import Expr
from pandas.core.computation.ops import (
MATHOPS,
REDUCTIONS,
@@ -26,13 +27,13 @@ class NumExprClobberingError(NameError):
pass
-def _check_ne_builtin_clash(expr):
+def _check_ne_builtin_clash(expr: Expr) -> None:
"""
Attempt to prevent foot-shooting in a helpful way.
Parameters
----------
- terms : Term
+ expr : Expr
Terms can contain
"""
names = expr.names
diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py
index 51fcbb02fd926..57ba478a9157b 100644
--- a/pandas/core/computation/eval.py
+++ b/pandas/core/computation/eval.py
@@ -1,9 +1,9 @@
"""
Top level ``eval`` module.
"""
+from __future__ import annotations
import tokenize
-from typing import Optional
import warnings
from pandas._libs.lib import no_default
@@ -14,13 +14,14 @@
PARSERS,
Expr,
)
+from pandas.core.computation.ops import BinOp
from pandas.core.computation.parsing import tokenize_string
from pandas.core.computation.scope import ensure_scope
from pandas.io.formats.printing import pprint_thing
-def _check_engine(engine: Optional[str]) -> str:
+def _check_engine(engine: str | None) -> str:
"""
Make sure a valid engine is passed.
@@ -161,9 +162,9 @@ def _check_for_locals(expr: str, stack_level: int, parser: str):
def eval(
- expr,
- parser="pandas",
- engine: Optional[str] = None,
+ expr: str | BinOp, # we leave BinOp out of the docstr bc it isn't for users
+ parser: str = "pandas",
+ engine: str | None = None,
truediv=no_default,
local_dict=None,
global_dict=None,
@@ -309,10 +310,12 @@ def eval(
stacklevel=2,
)
+ exprs: list[str | BinOp]
if isinstance(expr, str):
_check_expression(expr)
exprs = [e.strip() for e in expr.splitlines() if e.strip() != ""]
else:
+ # ops.BinOp; for internal compat, not intended to be passed by users
exprs = [expr]
multi_line = len(exprs) > 1
diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py
index 891642bf61d16..0e6a7551ab399 100644
--- a/pandas/core/computation/pytables.py
+++ b/pandas/core/computation/pytables.py
@@ -546,6 +546,7 @@ class PyTablesExpr(expr.Expr):
_visitor: PyTablesExprVisitor | None
env: PyTablesScope
+ expr: str
def __init__(
self,
@@ -570,7 +571,7 @@ def __init__(
local_dict = where.env.scope
_where = where.expr
- elif isinstance(where, (list, tuple)):
+ elif is_list_like(where):
where = list(where)
for idx, w in enumerate(where):
if isinstance(w, PyTablesExpr):
@@ -580,6 +581,7 @@ def __init__(
where[idx] = w
_where = " & ".join(f"({w})" for w in com.flatten(where))
else:
+ # _validate_where ensures we otherwise have a string
_where = where
self.expr = _where
diff --git a/pandas/core/computation/scope.py b/pandas/core/computation/scope.py
index ea92a33f242e9..09067e7eba6e5 100644
--- a/pandas/core/computation/scope.py
+++ b/pandas/core/computation/scope.py
@@ -106,9 +106,13 @@ class Scope:
"""
__slots__ = ["level", "scope", "target", "resolvers", "temps"]
+ level: int
+ scope: DeepChainMap
+ resolvers: DeepChainMap
+ temps: dict
def __init__(
- self, level, global_dict=None, local_dict=None, resolvers=(), target=None
+ self, level: int, global_dict=None, local_dict=None, resolvers=(), target=None
):
self.level = level + 1
@@ -146,8 +150,7 @@ def __init__(
# assumes that resolvers are going from outermost scope to inner
if isinstance(local_dict, Scope):
- # error: Cannot determine type of 'resolvers'
- resolvers += tuple(local_dict.resolvers.maps) # type: ignore[has-type]
+ resolvers += tuple(local_dict.resolvers.maps)
self.resolvers = DeepChainMap(*resolvers)
self.temps = {}
@@ -212,7 +215,7 @@ def resolve(self, key: str, is_local: bool):
raise UndefinedVariableError(key, is_local) from err
- def swapkey(self, old_key: str, new_key: str, new_value=None):
+ def swapkey(self, old_key: str, new_key: str, new_value=None) -> None:
"""
Replace a variable name, with a potentially new value.
@@ -238,7 +241,7 @@ def swapkey(self, old_key: str, new_key: str, new_value=None):
mapping[new_key] = new_value # type: ignore[index]
return
- def _get_vars(self, stack, scopes: list[str]):
+ def _get_vars(self, stack, scopes: list[str]) -> None:
"""
Get specifically scoped variables from a list of stack frames.
@@ -263,7 +266,7 @@ def _get_vars(self, stack, scopes: list[str]):
# scope after the loop
del frame
- def _update(self, level: int):
+ def _update(self, level: int) -> None:
"""
Update the current scope by going back `level` levels.
@@ -313,7 +316,7 @@ def ntemps(self) -> int:
return len(self.temps)
@property
- def full_scope(self):
+ def full_scope(self) -> DeepChainMap:
"""
Return the full scope for use with passing to engines transparently
as a mapping.
diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py
index ddc6e92b04927..4c73e5d594d2b 100644
--- a/pandas/core/reshape/pivot.py
+++ b/pandas/core/reshape/pivot.py
@@ -180,7 +180,6 @@ def __internal_pivot_table(
# TODO: why does test_pivot_table_doctest_case fail if
# we don't do this apparently-unnecessary setitem?
agged[v] = agged[v]
- pass
else:
agged[v] = maybe_downcast_to_dtype(agged[v], data[v].dtype)
diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py
index bb6928d2fd95a..c61864bbc0a76 100644
--- a/pandas/tests/io/pytables/test_store.py
+++ b/pandas/tests/io/pytables/test_store.py
@@ -673,17 +673,20 @@ def test_coordinates(setup_path):
tm.assert_frame_equal(result, expected)
# invalid
- msg = "cannot process expression"
- with pytest.raises(ValueError, match=msg):
+ msg = (
+ "where must be passed as a string, PyTablesExpr, "
+ "or list-like of PyTablesExpr"
+ )
+ with pytest.raises(TypeError, match=msg):
store.select("df", where=np.arange(len(df), dtype="float64"))
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(TypeError, match=msg):
store.select("df", where=np.arange(len(df) + 1))
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(TypeError, match=msg):
store.select("df", where=np.arange(len(df)), start=5)
- with pytest.raises(ValueError, match=msg):
+ with pytest.raises(TypeError, match=msg):
store.select("df", where=np.arange(len(df)), start=5, stop=10)
# selection with filter
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41007 | 2021-04-17T21:47:41Z | 2021-04-19T13:53:19Z | 2021-04-19T13:53:19Z | 2021-04-19T14:49:41Z |
Bug in to_datetime raising ValueError with None and NaT and more than 50 elements | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 1c7942dfedafa..57516a7d039e6 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -813,6 +813,7 @@ Reshaping
- Bug in :meth:`DataFrame.stack` not preserving ``CategoricalDtype`` in a ``MultiIndex`` (:issue:`36991`)
- Bug in :func:`to_datetime` raising error when input sequence contains unhashable items (:issue:`39756`)
- Bug in :meth:`Series.explode` preserving index when ``ignore_index`` was ``True`` and values were scalars (:issue:`40487`)
+- Bug in :func:`to_datetime` raising ``ValueError`` when :class:`Series` contains ``None`` and ``NaT`` and has more than 50 elements (:issue:`39882`)
Sparse
^^^^^^
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py
index 77bbde62d607e..102cdf4334510 100644
--- a/pandas/core/tools/datetimes.py
+++ b/pandas/core/tools/datetimes.py
@@ -84,6 +84,7 @@
Scalar = Union[int, float, str]
DatetimeScalar = TypeVar("DatetimeScalar", Scalar, datetime)
DatetimeScalarOrArrayConvertible = Union[DatetimeScalar, ArrayConvertible]
+start_caching_at = 50
# ---------------------------------------------------------------------
@@ -130,7 +131,7 @@ def should_cache(
# default realization
if check_count is None:
# in this case, the gain from caching is negligible
- if len(arg) <= 50:
+ if len(arg) <= start_caching_at:
return False
if len(arg) <= 5000:
@@ -193,6 +194,9 @@ def _maybe_cache(
if len(unique_dates) < len(arg):
cache_dates = convert_listlike(unique_dates, format)
cache_array = Series(cache_dates, index=unique_dates)
+ if not cache_array.is_unique:
+ # GH#39882 in case of None and NaT we get duplicates
+ cache_array = cache_array.drop_duplicates()
return cache_array
diff --git a/pandas/tests/series/methods/test_convert_dtypes.py b/pandas/tests/series/methods/test_convert_dtypes.py
index 8283bcd16dbad..81203b944fa92 100644
--- a/pandas/tests/series/methods/test_convert_dtypes.py
+++ b/pandas/tests/series/methods/test_convert_dtypes.py
@@ -13,6 +13,7 @@
# for most cases), and the specific cases where the result deviates from
# this default. Those overrides are defined as a dict with (keyword, val) as
# dictionary key. In case of multiple items, the last override takes precedence.
+
test_cases = [
(
# data
diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py
index cefbea529e366..3e0c12c6a22cc 100644
--- a/pandas/tests/tools/test_to_datetime.py
+++ b/pandas/tests/tools/test_to_datetime.py
@@ -43,6 +43,7 @@
import pandas._testing as tm
from pandas.core.arrays import DatetimeArray
from pandas.core.tools import datetimes as tools
+from pandas.core.tools.datetimes import start_caching_at
class TestTimeConversionFormats:
@@ -956,6 +957,19 @@ def test_to_datetime_cache_scalar(self):
expected = Timestamp("20130101 00:00:00")
assert result == expected
+ def test_convert_object_to_datetime_with_cache(self):
+ # GH#39882
+ ser = Series(
+ [None] + [NaT] * start_caching_at + [Timestamp("2012-07-26")],
+ dtype="object",
+ )
+ result = to_datetime(ser, errors="coerce")
+ expected = Series(
+ [NaT] * (start_caching_at + 1) + [Timestamp("2012-07-26")],
+ dtype="datetime64[ns]",
+ )
+ tm.assert_series_equal(result, expected)
+
@pytest.mark.parametrize(
"date, format",
[
| - [x] closes #39882
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
None and NaT are different for unique while convert_listlike casts None to NaT, hence causing dups
Not sure if we could do something better. | https://api.github.com/repos/pandas-dev/pandas/pulls/41006 | 2021-04-17T21:34:34Z | 2021-04-20T22:49:56Z | 2021-04-20T22:49:55Z | 2021-04-21T20:40:13Z |
fix: function _take_with_is_copy was defined final but overriden | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index bad42a85aeeee..d69e933164118 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -3626,7 +3626,6 @@ class max_speed
)
return self._constructor(new_data).__finalize__(self, method="take")
- @final
def _take_with_is_copy(self: FrameOrSeries, indices, axis=0) -> FrameOrSeries:
"""
Internal version of the `take` method that sets the `_is_copy`
diff --git a/pandas/core/series.py b/pandas/core/series.py
index cbec0024d5f9e..4d50c3100a12c 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -863,7 +863,7 @@ def take(self, indices, axis=0, is_copy=None, **kwargs) -> Series:
result = self._constructor(new_values, index=new_index, fastpath=True)
return result.__finalize__(self, method="take")
- def _take_with_is_copy(self, indices, axis=0):
+ def _take_with_is_copy(self, indices, axis=0) -> Series:
"""
Internal version of the `take` method that sets the `_is_copy`
attribute to keep track of the parent dataframe (using in indexing
| - [x] closes #40974
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41004 | 2021-04-17T20:27:04Z | 2021-04-19T17:22:29Z | 2021-04-19T17:22:28Z | 2021-04-19T17:22:38Z |
CI: suppress warnings | diff --git a/pandas/tests/io/pytables/test_categorical.py b/pandas/tests/io/pytables/test_categorical.py
index 177abdeedb88b..4928a70f90960 100644
--- a/pandas/tests/io/pytables/test_categorical.py
+++ b/pandas/tests/io/pytables/test_categorical.py
@@ -17,7 +17,14 @@
ensure_clean_store,
)
-pytestmark = [pytest.mark.single, td.skip_array_manager_not_yet_implemented]
+pytestmark = [
+ pytest.mark.single,
+ td.skip_array_manager_not_yet_implemented,
+ # pytables https://github.com/PyTables/PyTables/issues/822
+ pytest.mark.filterwarnings(
+ "ignore:a closed node found in the registry:UserWarning"
+ ),
+]
def test_categorical(setup_path):
diff --git a/setup.cfg b/setup.cfg
index 610b30e4422a9..8cdec8ab9feed 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -137,6 +137,7 @@ xfail_strict = True
filterwarnings =
error:Sparse:FutureWarning
error:The SparseArray:FutureWarning
+ ignore:unclosed transport <asyncio.sslproto:ResourceWarning
junit_family = xunit2
[codespell]
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41003 | 2021-04-17T20:17:48Z | 2021-04-19T13:53:57Z | 2021-04-19T13:53:57Z | 2021-04-19T14:46:40Z |
[ArrowStringArray] fix test_value_counts_na | diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index 52bdcd03d3b49..ecbb5367febc5 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -675,13 +675,18 @@ def value_counts(self, dropna: bool = True) -> Series:
vc = self._data.value_counts()
- # Index cannot hold ExtensionArrays yet
- index = Index(type(self)(vc.field(0)).astype(object))
+ values = vc.field(0)
+ counts = vc.field(1)
+ if dropna and self._data.null_count > 0:
+ mask = values.is_valid()
+ values = values.filter(mask)
+ counts = counts.filter(mask)
+
# No missing values so we can adhere to the interface and return a numpy array.
- counts = np.array(vc.field(1))
+ counts = np.array(counts)
- if dropna and self._data.null_count > 0:
- raise NotImplementedError("yo")
+ # Index cannot hold ExtensionArrays yet
+ index = Index(type(self)(values)).astype(object)
return Series(counts, index=index).astype("Int64")
diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py
index 2fec1925149ad..2b2db49c62ba2 100644
--- a/pandas/tests/arrays/string_/test_string.py
+++ b/pandas/tests/arrays/string_/test_string.py
@@ -476,12 +476,7 @@ def test_arrow_roundtrip(dtype, dtype_object):
assert result.loc[2, "a"] is pd.NA
-def test_value_counts_na(dtype, request):
- if dtype == "arrow_string":
- reason = "TypeError: boolean value of NA is ambiguous"
- mark = pytest.mark.xfail(reason=reason)
- request.node.add_marker(mark)
-
+def test_value_counts_na(dtype):
arr = pd.array(["a", "b", "a", pd.NA], dtype=dtype)
result = arr.value_counts(dropna=False)
expected = pd.Series([2, 1, 1], index=["a", "b", pd.NA], dtype="Int64")
@@ -492,12 +487,7 @@ def test_value_counts_na(dtype, request):
tm.assert_series_equal(result, expected)
-def test_value_counts_with_normalize(dtype, request):
- if dtype == "arrow_string":
- reason = "TypeError: boolean value of NA is ambiguous"
- mark = pytest.mark.xfail(reason=reason)
- request.node.add_marker(mark)
-
+def test_value_counts_with_normalize(dtype):
s = pd.Series(["a", "b", "a", pd.NA], dtype=dtype)
result = s.value_counts(normalize=True)
expected = pd.Series([2, 1], index=["a", "b"], dtype="Float64") / 3
| https://api.github.com/repos/pandas-dev/pandas/pulls/41002 | 2021-04-17T20:00:27Z | 2021-04-19T14:00:20Z | 2021-04-19T14:00:20Z | 2021-04-19T15:51:02Z | |
[ArrowStringArray] fix test_repeat_with_null | diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py
index dc4550484fa3b..b794690ccc5af 100644
--- a/pandas/core/strings/object_array.py
+++ b/pandas/core/strings/object_array.py
@@ -198,6 +198,7 @@ def scalar_rep(x):
return self._str_map(scalar_rep, dtype=str)
else:
from pandas.core.arrays.string_ import StringArray
+ from pandas.core.arrays.string_arrow import ArrowStringArray
def rep(x, r):
if x is libmissing.NA:
@@ -209,9 +210,9 @@ def rep(x, r):
repeats = np.asarray(repeats, dtype=object)
result = libops.vec_binop(np.asarray(self), repeats, rep)
- if isinstance(self, StringArray):
+ if isinstance(self, (StringArray, ArrowStringArray)):
# Not going through map, so we have to do this here.
- result = StringArray._from_sequence(result)
+ result = type(self)._from_sequence(result)
return result
def _str_match(
diff --git a/pandas/tests/strings/test_strings.py b/pandas/tests/strings/test_strings.py
index a809446f0bc06..06b22f00a38cf 100644
--- a/pandas/tests/strings/test_strings.py
+++ b/pandas/tests/strings/test_strings.py
@@ -136,14 +136,8 @@ def test_repeat():
tm.assert_series_equal(rs, xp)
-def test_repeat_with_null(nullable_string_dtype, request):
+def test_repeat_with_null(nullable_string_dtype):
# GH: 31632
-
- if nullable_string_dtype == "arrow_string":
- reason = 'Attribute "dtype" are different'
- mark = pytest.mark.xfail(reason=reason)
- request.node.add_marker(mark)
-
ser = Series(["a", None], dtype=nullable_string_dtype)
result = ser.str.repeat([3, 4])
expected = Series(["aaa", None], dtype=nullable_string_dtype)
| https://api.github.com/repos/pandas-dev/pandas/pulls/41001 | 2021-04-17T18:15:39Z | 2021-04-19T14:00:40Z | 2021-04-19T14:00:40Z | 2021-04-19T15:35:53Z | |
REF: remove how arg from maybe_cast_result | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index 6726374dbe30e..e91927d87d318 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -55,7 +55,6 @@
ensure_str,
is_bool,
is_bool_dtype,
- is_categorical_dtype,
is_complex,
is_complex_dtype,
is_datetime64_dtype,
@@ -79,6 +78,7 @@
pandas_dtype,
)
from pandas.core.dtypes.dtypes import (
+ CategoricalDtype,
DatetimeTZDtype,
ExtensionDtype,
IntervalDtype,
@@ -359,15 +359,15 @@ def trans(x):
return result
-def maybe_cast_result(
+def maybe_cast_pointwise_result(
result: ArrayLike,
dtype: DtypeObj,
numeric_only: bool = False,
- how: str = "",
same_dtype: bool = True,
) -> ArrayLike:
"""
- Try casting result to a different type if appropriate
+ Try casting result of a pointwise operation back to the original dtype if
+ appropriate.
Parameters
----------
@@ -377,8 +377,6 @@ def maybe_cast_result(
Input Series from which result was calculated.
numeric_only : bool, default False
Whether to cast only numerics or datetimes as well.
- how : str, default ""
- How the result was computed.
same_dtype : bool, default True
Specify dtype when calling _from_sequence
@@ -387,12 +385,12 @@ def maybe_cast_result(
result : array-like
result maybe casted to the dtype.
"""
- dtype = maybe_cast_result_dtype(dtype, how)
assert not is_scalar(result)
if isinstance(dtype, ExtensionDtype):
- if not is_categorical_dtype(dtype) and dtype.kind != "M":
+ if not isinstance(dtype, (CategoricalDtype, DatetimeTZDtype)):
+ # TODO: avoid this special-casing
# We have to special case categorical so as not to upcast
# things like counts back to categorical
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py
index 702d67b198e8d..54a10b9b62ec4 100644
--- a/pandas/core/groupby/ops.py
+++ b/pandas/core/groupby/ops.py
@@ -36,7 +36,7 @@
from pandas.util._decorators import cache_readonly
from pandas.core.dtypes.cast import (
- maybe_cast_result,
+ maybe_cast_pointwise_result,
maybe_cast_result_dtype,
maybe_downcast_to_dtype,
)
@@ -797,7 +797,7 @@ def _aggregate_series_pure_python(self, obj: Series, func: F):
result[label] = res
out = lib.maybe_convert_objects(result, try_float=False)
- out = maybe_cast_result(out, obj.dtype, numeric_only=True)
+ out = maybe_cast_pointwise_result(out, obj.dtype, numeric_only=True)
return out, counts
diff --git a/pandas/core/series.py b/pandas/core/series.py
index cbec0024d5f9e..fd115a550fa77 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -60,7 +60,7 @@
from pandas.core.dtypes.cast import (
convert_dtypes,
maybe_box_native,
- maybe_cast_result,
+ maybe_cast_pointwise_result,
validate_numeric_casting,
)
from pandas.core.dtypes.common import (
@@ -3070,22 +3070,26 @@ def combine(self, other, func, fill_value=None) -> Series:
# so do this element by element
new_index = self.index.union(other.index)
new_name = ops.get_op_result_name(self, other)
- new_values = []
- for idx in new_index:
+ new_values = np.empty(len(new_index), dtype=object)
+ for i, idx in enumerate(new_index):
lv = self.get(idx, fill_value)
rv = other.get(idx, fill_value)
with np.errstate(all="ignore"):
- new_values.append(func(lv, rv))
+ new_values[i] = func(lv, rv)
else:
# Assume that other is a scalar, so apply the function for
# each element in the Series
new_index = self.index
+ new_values = np.empty(len(new_index), dtype=object)
with np.errstate(all="ignore"):
- new_values = [func(lv, other) for lv in self._values]
+ new_values[:] = [func(lv, other) for lv in self._values]
new_name = self.name
- res_values = sanitize_array(new_values, None)
- res_values = maybe_cast_result(res_values, self.dtype, same_dtype=False)
+ # try_float=False is to match _aggregate_series_pure_python
+ res_values = lib.maybe_convert_objects(new_values, try_float=False)
+ res_values = maybe_cast_pointwise_result(
+ res_values, self.dtype, same_dtype=False
+ )
return self._constructor(res_values, index=new_index, name=new_name)
def combine_first(self, other) -> Series:
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/41000 | 2021-04-17T14:47:59Z | 2021-04-19T14:01:50Z | 2021-04-19T14:01:50Z | 2021-04-19T14:44:06Z |
Regression modifying obj with all false indexer | diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py
index 82971e460a8a2..313ec5af4fe42 100644
--- a/pandas/core/indexing.py
+++ b/pandas/core/indexing.py
@@ -48,6 +48,7 @@
from pandas.core.construction import array as pd_array
from pandas.core.indexers import (
check_array_indexer,
+ is_empty_indexer,
is_exact_shape_match,
is_list_like_indexer,
length_of_indexer,
@@ -1872,7 +1873,11 @@ def _setitem_single_column(self, loc: int, value, plane_indexer):
# GH#6149 (null slice), GH#10408 (full bounds)
if com.is_null_slice(pi) or com.is_full_slice(pi, len(self.obj)):
ser = value
- elif is_array_like(value) and is_exact_shape_match(ser, value):
+ elif (
+ is_array_like(value)
+ and is_exact_shape_match(ser, value)
+ and not is_empty_indexer(pi, value)
+ ):
if is_list_like(pi):
ser = value[np.argsort(pi)]
else:
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py
index 1d41426b93db6..9c153777c320a 100644
--- a/pandas/tests/frame/indexing/test_setitem.py
+++ b/pandas/tests/frame/indexing/test_setitem.py
@@ -888,6 +888,14 @@ def test_setitem_boolean_indexing(self):
with pytest.raises(ValueError, match="Item wrong length"):
df1[df1.index[:-1] > 2] = -1
+ def test_loc_setitem_all_false_boolean_two_blocks(self):
+ # GH#40885
+ df = DataFrame({"a": [1, 2], "b": [3, 4], "c": "a"})
+ expected = df.copy()
+ indexer = Series([False, False], name="c")
+ df.loc[indexer, ["b"]] = DataFrame({"b": [5, 6]}, index=[0, 1])
+ tm.assert_frame_equal(df, expected)
+
class TestDataFrameSetitemCopyViewSemantics:
def test_setitem_always_copy(self, float_frame):
| - [x] closes #40885
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
Regression on master so no whatsnew
| https://api.github.com/repos/pandas-dev/pandas/pulls/40999 | 2021-04-17T14:43:17Z | 2021-04-19T14:02:53Z | 2021-04-19T14:02:52Z | 2021-04-19T23:20:21Z |
[ArrowStringArray] BUG: fix test_astype_string for Float32Dtype | diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py
index 8d3a8feb89d67..50e8cc4c82e0d 100644
--- a/pandas/core/arrays/interval.py
+++ b/pandas/core/arrays/interval.py
@@ -829,6 +829,7 @@ def astype(self, dtype, copy: bool = True):
"""
from pandas import Index
from pandas.core.arrays.string_ import StringDtype
+ from pandas.core.arrays.string_arrow import ArrowStringDtype
if dtype is not None:
dtype = pandas_dtype(dtype)
@@ -851,7 +852,7 @@ def astype(self, dtype, copy: bool = True):
return self._shallow_copy(new_left, new_right)
elif is_categorical_dtype(dtype):
return Categorical(np.asarray(self), dtype=dtype)
- elif isinstance(dtype, StringDtype):
+ elif isinstance(dtype, (StringDtype, ArrowStringDtype)):
return dtype.construct_array_type()._from_sequence(self, copy=False)
# TODO: This try/except will be repeated.
diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index 180ed51e7fd2b..1692afbf1fc84 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -228,10 +228,21 @@ def _chk_pyarrow_available(cls) -> None:
@classmethod
def _from_sequence(cls, scalars, dtype: Dtype | None = None, copy: bool = False):
+ from pandas.core.arrays.masked import BaseMaskedArray
+
cls._chk_pyarrow_available()
- # convert non-na-likes to str, and nan-likes to ArrowStringDtype.na_value
- scalars = lib.ensure_string_array(scalars, copy=False)
- return cls(pa.array(scalars, type=pa.string(), from_pandas=True))
+
+ if isinstance(scalars, BaseMaskedArray):
+ # avoid costly conversion to object dtype in ensure_string_array and
+ # numerical issues with Float32Dtype
+ na_values = scalars._mask
+ result = scalars._data
+ result = lib.ensure_string_array(result, copy=copy, convert_na_value=False)
+ return cls(pa.array(result, mask=na_values, type=pa.string()))
+
+ # convert non-na-likes to str
+ result = lib.ensure_string_array(scalars, copy=copy)
+ return cls(pa.array(result, type=pa.string(), from_pandas=True))
@classmethod
def _from_sequence_of_strings(
diff --git a/pandas/tests/extension/base/casting.py b/pandas/tests/extension/base/casting.py
index 7c5ef5b3b27d3..47f4f7585243d 100644
--- a/pandas/tests/extension/base/casting.py
+++ b/pandas/tests/extension/base/casting.py
@@ -43,10 +43,10 @@ def test_astype_str(self, data):
expected = pd.Series([str(x) for x in data[:5]], dtype=str)
self.assert_series_equal(result, expected)
- def test_astype_string(self, data):
+ def test_astype_string(self, data, nullable_string_dtype):
# GH-33465
- result = pd.Series(data[:5]).astype("string")
- expected = pd.Series([str(x) for x in data[:5]], dtype="string")
+ result = pd.Series(data[:5]).astype(nullable_string_dtype)
+ expected = pd.Series([str(x) for x in data[:5]], dtype=nullable_string_dtype)
self.assert_series_equal(result, expected)
def test_to_numpy(self, data):
| this also fixes Interval, but that test doesn't fail in #39908 for a single StringDtype parameterized by storage.
| https://api.github.com/repos/pandas-dev/pandas/pulls/40998 | 2021-04-17T11:41:39Z | 2021-04-30T17:24:25Z | 2021-04-30T17:24:25Z | 2021-04-30T17:57:25Z |
CLN: remove CategoricalIndex.unique | diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index 5b98b956e33e6..c085d68b36bc3 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -386,15 +386,6 @@ def fillna(self, value, downcast=None):
return type(self)._simple_new(cat, name=self.name)
- @doc(Index.unique)
- def unique(self, level=None):
- if level is not None:
- self._validate_index_level(level)
- result = self._values.unique()
- # Use _simple_new instead of _shallow_copy to ensure we keep dtype
- # of result, not self.
- return type(self)._simple_new(result, name=self.name)
-
def reindex(
self, target, method=None, level=None, limit=None, tolerance=None
) -> tuple[Index, np.ndarray | None]:
diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py
index b11ec06120e0c..d28bcd6c5497a 100644
--- a/pandas/core/indexes/extension.py
+++ b/pandas/core/indexes/extension.py
@@ -331,7 +331,7 @@ def _get_unique_index(self):
return self
result = self._data.unique()
- return self._shallow_copy(result)
+ return type(self)._simple_new(result, name=self.name)
@doc(Index.map)
def map(self, mapper, na_action=None):
| made possible by #38140 | https://api.github.com/repos/pandas-dev/pandas/pulls/40995 | 2021-04-17T02:25:15Z | 2021-04-19T14:10:34Z | 2021-04-19T14:10:34Z | 2021-04-19T14:40:54Z |
REGR: memory_map with non-UTF8 encoding | diff --git a/doc/source/whatsnew/v1.2.5.rst b/doc/source/whatsnew/v1.2.5.rst
index 16f9284802407..60e146b2212eb 100644
--- a/doc/source/whatsnew/v1.2.5.rst
+++ b/doc/source/whatsnew/v1.2.5.rst
@@ -15,7 +15,7 @@ including other versions of pandas.
Fixed regressions
~~~~~~~~~~~~~~~~~
- Regression in :func:`concat` between two :class:`DataFrames` where one has an :class:`Index` that is all-None and the other is :class:`DatetimeIndex` incorrectly raising (:issue:`40841`)
--
+- Regression in :func:`read_csv` when using ``memory_map=True`` with an non-UTF8 encoding (:issue:`40986`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/io/common.py b/pandas/io/common.py
index 00966d39dd99d..06b00a9cbb4eb 100644
--- a/pandas/io/common.py
+++ b/pandas/io/common.py
@@ -618,7 +618,12 @@ def get_handle(
# memory mapping needs to be the first step
handle, memory_map, handles = _maybe_memory_map(
- handle, memory_map, ioargs.encoding, ioargs.mode, errors
+ handle,
+ memory_map,
+ ioargs.encoding,
+ ioargs.mode,
+ errors,
+ ioargs.compression["method"] not in _compression_to_extension,
)
is_path = isinstance(handle, str)
@@ -820,7 +825,18 @@ class _MMapWrapper(abc.Iterator):
"""
- def __init__(self, f: IO):
+ def __init__(
+ self,
+ f: IO,
+ encoding: str = "utf-8",
+ errors: str = "strict",
+ decode: bool = True,
+ ):
+ self.encoding = encoding
+ self.errors = errors
+ self.decoder = codecs.getincrementaldecoder(encoding)(errors=errors)
+ self.decode = decode
+
self.attributes = {}
for attribute in ("seekable", "readable", "writeable"):
if not hasattr(f, attribute):
@@ -836,19 +852,30 @@ def __getattr__(self, name: str):
def __iter__(self) -> _MMapWrapper:
return self
+ def read(self, size: int = -1) -> str | bytes:
+ # CSV c-engine uses read instead of iterating
+ content: bytes = self.mmap.read(size)
+ if self.decode:
+ # memory mapping is applied before compression. Encoding should
+ # be applied to the de-compressed data.
+ return content.decode(self.encoding, errors=self.errors)
+ return content
+
def __next__(self) -> str:
newbytes = self.mmap.readline()
# readline returns bytes, not str, but Python's CSV reader
# expects str, so convert the output to str before continuing
- newline = newbytes.decode("utf-8")
+ newline = self.decoder.decode(newbytes)
# mmap doesn't raise if reading past the allocated
# data but instead returns an empty string, so raise
# if that is returned
if newline == "":
raise StopIteration
- return newline
+
+ # IncrementalDecoder seems to push newline to the next line
+ return newline.lstrip("\n")
def _maybe_memory_map(
@@ -857,6 +884,7 @@ def _maybe_memory_map(
encoding: str,
mode: str,
errors: str | None,
+ decode: bool,
) -> tuple[FileOrBuffer, bool, list[Buffer]]:
"""Try to memory map file/buffer."""
handles: list[Buffer] = []
@@ -877,7 +905,10 @@ def _maybe_memory_map(
try:
# error: Argument 1 to "_MMapWrapper" has incompatible type "Union[IO[Any],
# RawIOBase, BufferedIOBase, TextIOBase, mmap]"; expected "IO[Any]"
- wrapped = cast(mmap.mmap, _MMapWrapper(handle)) # type: ignore[arg-type]
+ wrapped = cast(
+ mmap.mmap,
+ _MMapWrapper(handle, encoding, errors, decode), # type: ignore[arg-type]
+ )
handle.close()
handles.remove(handle)
handles.append(wrapped)
diff --git a/pandas/io/parsers/c_parser_wrapper.py b/pandas/io/parsers/c_parser_wrapper.py
index abf6128699a21..fb110706c3fb4 100644
--- a/pandas/io/parsers/c_parser_wrapper.py
+++ b/pandas/io/parsers/c_parser_wrapper.py
@@ -30,25 +30,6 @@ def __init__(self, src: FilePathOrBuffer, **kwds):
assert self.handles is not None
for key in ("storage_options", "encoding", "memory_map", "compression"):
kwds.pop(key, None)
- if self.handles.is_mmap and hasattr(self.handles.handle, "mmap"):
- # error: Item "IO[Any]" of "Union[IO[Any], RawIOBase, BufferedIOBase,
- # TextIOBase, TextIOWrapper, mmap]" has no attribute "mmap"
-
- # error: Item "RawIOBase" of "Union[IO[Any], RawIOBase, BufferedIOBase,
- # TextIOBase, TextIOWrapper, mmap]" has no attribute "mmap"
-
- # error: Item "BufferedIOBase" of "Union[IO[Any], RawIOBase, BufferedIOBase,
- # TextIOBase, TextIOWrapper, mmap]" has no attribute "mmap"
-
- # error: Item "TextIOBase" of "Union[IO[Any], RawIOBase, BufferedIOBase,
- # TextIOBase, TextIOWrapper, mmap]" has no attribute "mmap"
-
- # error: Item "TextIOWrapper" of "Union[IO[Any], RawIOBase, BufferedIOBase,
- # TextIOBase, TextIOWrapper, mmap]" has no attribute "mmap"
-
- # error: Item "mmap" of "Union[IO[Any], RawIOBase, BufferedIOBase,
- # TextIOBase, TextIOWrapper, mmap]" has no attribute "mmap"
- self.handles.handle = self.handles.handle.mmap # type: ignore[union-attr]
try:
self._reader = parsers.TextReader(self.handles.handle, **kwds)
diff --git a/pandas/tests/io/parser/test_encoding.py b/pandas/tests/io/parser/test_encoding.py
index 89ece3b1a7300..006438df2a5e0 100644
--- a/pandas/tests/io/parser/test_encoding.py
+++ b/pandas/tests/io/parser/test_encoding.py
@@ -220,3 +220,20 @@ def test_parse_encoded_special_characters(encoding):
expected = DataFrame(data=[[":foo", 0], ["bar", 1], ["baz", 2]], columns=["a", "b"])
tm.assert_frame_equal(result, expected)
+
+
+@pytest.mark.parametrize("encoding", ["utf-8", None, "utf-16", "cp1255", "latin-1"])
+def test_encoding_memory_map(all_parsers, encoding):
+ # GH40986
+ parser = all_parsers
+ expected = DataFrame(
+ {
+ "name": ["Raphael", "Donatello", "Miguel Angel", "Leonardo"],
+ "mask": ["red", "purple", "orange", "blue"],
+ "weapon": ["sai", "bo staff", "nunchunk", "katana"],
+ }
+ )
+ with tm.ensure_clean() as file:
+ expected.to_csv(file, index=False, encoding=encoding)
+ df = parser.read_csv(file, encoding=encoding, memory_map=True)
+ tm.assert_frame_equal(df, expected)
| - [x] closes #40986
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
My best guess is that `memory_map=True` always assumed UTF-8 with the python engine. Now that the c and python engine use the same IO code, the c engine assumed UTF-8 as well.
| https://api.github.com/repos/pandas-dev/pandas/pulls/40994 | 2021-04-17T02:09:57Z | 2021-04-26T12:20:57Z | 2021-04-26T12:20:56Z | 2021-06-05T20:50:11Z |
Deprecate joining over a different number of levels | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 1a11fffbf6b4e..f7463218096e5 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -601,6 +601,7 @@ Deprecations
- Deprecated :meth:`.Styler.set_na_rep` and :meth:`.Styler.set_precision` in favour of :meth:`.Styler.format` with ``na_rep`` and ``precision`` as existing and new input arguments respectively (:issue:`40134`, :issue:`40425`)
- Deprecated allowing partial failure in :meth:`Series.transform` and :meth:`DataFrame.transform` when ``func`` is list-like or dict-like and raises anything but ``TypeError``; ``func`` raising anything but a ``TypeError`` will raise in a future version (:issue:`40211`)
- Deprecated support for ``np.ma.mrecords.MaskedRecords`` in the :class:`DataFrame` constructor, pass ``{name: data[name] for name in data.dtype.names}`` instead (:issue:`40363`)
+- Deprecated using :func:`merge` or :func:`join` on a different number of levels (:issue:`34862`)
- Deprecated the use of ``**kwargs`` in :class:`.ExcelWriter`; use the keyword argument ``engine_kwargs`` instead (:issue:`40430`)
- Deprecated the ``level`` keyword for :class:`DataFrame` and :class:`Series` aggregations; use groupby instead (:issue:`39983`)
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 8cee0dd2abb88..b2fe18bba43f4 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -669,11 +669,11 @@ def __init__(
# warn user when merging between different levels
if _left.columns.nlevels != _right.columns.nlevels:
msg = (
- "merging between different levels can give an unintended "
- f"result ({left.columns.nlevels} levels on the left,"
+ "merging between different levels is deprecated and will be removed "
+ f"in a future version. ({left.columns.nlevels} levels on the left,"
f"{right.columns.nlevels} on the right)"
)
- warnings.warn(msg, UserWarning)
+ warnings.warn(msg, FutureWarning, stacklevel=3)
self._validate_specification()
diff --git a/pandas/tests/frame/methods/test_join.py b/pandas/tests/frame/methods/test_join.py
index 1c7f7e3ff674a..36fd5d399c300 100644
--- a/pandas/tests/frame/methods/test_join.py
+++ b/pandas/tests/frame/methods/test_join.py
@@ -338,14 +338,14 @@ def test_merge_join_different_levels(self):
# merge
columns = ["a", "b", ("c", "c1")]
expected = DataFrame(columns=columns, data=[[1, 11, 33], [0, 22, 44]])
- with tm.assert_produces_warning(UserWarning):
+ with tm.assert_produces_warning(FutureWarning):
result = pd.merge(df1, df2, on="a")
tm.assert_frame_equal(result, expected)
# join, see discussion in GH#12219
columns = ["a", "b", ("a", ""), ("c", "c1")]
expected = DataFrame(columns=columns, data=[[1, 11, 0, 44], [0, 22, 1, 33]])
- with tm.assert_produces_warning(UserWarning):
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
result = df1.join(df2, on="a")
tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py
index fb161e38c7155..2201da8ccb0d2 100644
--- a/pandas/tests/reshape/merge/test_join.py
+++ b/pandas/tests/reshape/merge/test_join.py
@@ -417,7 +417,7 @@ def test_join_hierarchical_mixed(self):
other_df = DataFrame([(1, 2, 3), (7, 10, 6)], columns=["a", "b", "d"])
other_df.set_index("a", inplace=True)
# GH 9455, 12219
- with tm.assert_produces_warning(UserWarning):
+ with tm.assert_produces_warning(FutureWarning):
result = merge(new_df, other_df, left_index=True, right_index=True)
assert ("b", "mean") in result
assert "b" in result
| - [x] closes #34862
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
I think deprecating this is a good idea, I stumbled across this accidentally this week and found this really odd | https://api.github.com/repos/pandas-dev/pandas/pulls/40993 | 2021-04-17T00:22:07Z | 2021-04-20T22:47:54Z | 2021-04-20T22:47:54Z | 2021-04-21T20:40:07Z |
Deprecate suffixes in merge producing duplicate columns | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 1c7942dfedafa..8f900d16ce0ad 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -571,6 +571,7 @@ Deprecations
- Deprecated support for ``np.ma.mrecords.MaskedRecords`` in the :class:`DataFrame` constructor, pass ``{name: data[name] for name in data.dtype.names}`` instead (:issue:`40363`)
- Deprecated the use of ``**kwargs`` in :class:`.ExcelWriter`; use the keyword argument ``engine_kwargs`` instead (:issue:`40430`)
- Deprecated the ``level`` keyword for :class:`DataFrame` and :class:`Series` aggregations; use groupby instead (:issue:`39983`)
+- Deprecated :func:`merge` producing duplicated columns through the ``suffixes`` keyword and already existing columns (:issue:`22818`)
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py
index 8cee0dd2abb88..5a13506a42011 100644
--- a/pandas/core/reshape/merge.py
+++ b/pandas/core/reshape/merge.py
@@ -2311,4 +2311,22 @@ def renamer(x, suffix):
lrenamer = partial(renamer, suffix=lsuffix)
rrenamer = partial(renamer, suffix=rsuffix)
- return (left._transform_index(lrenamer), right._transform_index(rrenamer))
+ llabels = left._transform_index(lrenamer)
+ rlabels = right._transform_index(rrenamer)
+
+ dups = []
+ if not llabels.is_unique:
+ # Only warn when duplicates are caused because of suffixes, already duplicated
+ # columns in origin should not warn
+ dups = llabels[(llabels.duplicated()) & (~left.duplicated())].tolist()
+ if not rlabels.is_unique:
+ dups.extend(rlabels[(rlabels.duplicated()) & (~right.duplicated())].tolist())
+ if dups:
+ warnings.warn(
+ f"Passing 'suffixes' which cause duplicate columns {set(dups)} in the "
+ f"result is deprecated and will raise a MergeError in a future version.",
+ FutureWarning,
+ stacklevel=4,
+ )
+
+ return llabels, rlabels
diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py
index fb161e38c7155..166aa3f5e3263 100644
--- a/pandas/tests/reshape/merge/test_join.py
+++ b/pandas/tests/reshape/merge/test_join.py
@@ -629,7 +629,8 @@ def test_join_dups(self):
dta = x.merge(y, left_index=True, right_index=True).merge(
z, left_index=True, right_index=True, how="outer"
)
- dta = dta.merge(w, left_index=True, right_index=True)
+ with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
+ dta = dta.merge(w, left_index=True, right_index=True)
expected = concat([x, y, z, w], axis=1)
expected.columns = ["x_x", "y_x", "x_y", "y_y", "x_x", "y_x", "x_y", "y_y"]
tm.assert_frame_equal(dta, expected)
diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py
index 9699a0dec4891..1495a34274a94 100644
--- a/pandas/tests/reshape/merge/test_merge.py
+++ b/pandas/tests/reshape/merge/test_merge.py
@@ -2409,3 +2409,40 @@ def test_merge_result_empty_index_and_on():
result = merge(df2, df1, left_index=True, right_on=["b"])
tm.assert_frame_equal(result, expected)
+
+
+def test_merge_suffixes_produce_dup_columns_warns():
+ # GH#22818
+ left = DataFrame({"a": [1, 2, 3], "b": 1, "b_x": 2})
+ right = DataFrame({"a": [1, 2, 3], "b": 2})
+ expected = DataFrame(
+ [[1, 1, 2, 2], [2, 1, 2, 2], [3, 1, 2, 2]], columns=["a", "b_x", "b_x", "b_y"]
+ )
+ with tm.assert_produces_warning(FutureWarning):
+ result = merge(left, right, on="a")
+ tm.assert_frame_equal(result, expected)
+
+ with tm.assert_produces_warning(FutureWarning):
+ merge(right, left, on="a", suffixes=("_y", "_x"))
+ tm.assert_frame_equal(result, expected)
+
+
+def test_merge_duplicate_columns_with_suffix_no_warning():
+ # GH#22818
+ # Do not raise warning when duplicates are caused by duplicates in origin
+ left = DataFrame([[1, 1, 1], [2, 2, 2]], columns=["a", "b", "b"])
+ right = DataFrame({"a": [1, 3], "b": 2})
+ result = merge(left, right, on="a")
+ expected = DataFrame([[1, 1, 1, 2]], columns=["a", "b_x", "b_x", "b_y"])
+ tm.assert_frame_equal(result, expected)
+
+
+def test_merge_duplicate_columns_with_suffix_causing_another_duplicate():
+ # GH#22818
+ # This should raise warning because suffixes cause another collision
+ left = DataFrame([[1, 1, 1, 1], [2, 2, 2, 2]], columns=["a", "b", "b", "b_x"])
+ right = DataFrame({"a": [1, 3], "b": 2})
+ with tm.assert_produces_warning(FutureWarning):
+ result = merge(left, right, on="a")
+ expected = DataFrame([[1, 1, 1, 1, 2]], columns=["a", "b_x", "b_x", "b_x", "b_y"])
+ tm.assert_frame_equal(result, expected)
| - [x] closes #22818
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
I think we should not allow these column collisions at all. Hence deprecating and raising in 2.0
Alternative here would be to add an ``errors`` keyword to the merge and join functions as @simonjayhawkins mentioned in the op. | https://api.github.com/repos/pandas-dev/pandas/pulls/40991 | 2021-04-16T23:50:24Z | 2021-04-20T22:47:30Z | 2021-04-20T22:47:29Z | 2021-04-21T20:39:54Z |
TYP: libperiod | diff --git a/pandas/_libs/tslibs/period.pyi b/pandas/_libs/tslibs/period.pyi
new file mode 100644
index 0000000000000..49e630d605310
--- /dev/null
+++ b/pandas/_libs/tslibs/period.pyi
@@ -0,0 +1,158 @@
+from typing import Literal
+
+import numpy as np
+
+from pandas._libs.tslibs.nattype import NaTType
+from pandas._libs.tslibs.offsets import BaseOffset
+from pandas._libs.tslibs.timestamps import Timestamp
+from pandas._typing import (
+ Frequency,
+ Timezone,
+)
+
+INVALID_FREQ_ERR_MSG: str
+DIFFERENT_FREQ: str
+
+class IncompatibleFrequency(ValueError): ...
+
+def periodarr_to_dt64arr(
+ periodarr: np.ndarray, # const int64_t[:]
+ freq: int,
+) -> np.ndarray: ... # np.ndarray[np.int64]
+
+def period_asfreq_arr(
+ arr: np.ndarray, # ndarray[int64_t] arr,
+ freq1: int,
+ freq2: int,
+ end: bool,
+) -> np.ndarray: ... # np.ndarray[np.int64]
+
+def get_period_field_arr(
+ field: str,
+ arr: np.ndarray, # const int64_t[:]
+ freq: int,
+) -> np.ndarray: ... # np.ndarray[np.int64]
+
+def from_ordinals(
+ values: np.ndarray, # const int64_t[:]
+ freq: Frequency,
+) -> np.ndarray: ... # np.ndarray[np.int64]
+
+def extract_ordinals(
+ values: np.ndarray, # np.ndarray[object]
+ freq: Frequency | int,
+) -> np.ndarray: ... # np.ndarray[np.int64]
+
+def extract_freq(
+ values: np.ndarray, # np.ndarray[object]
+) -> BaseOffset: ...
+
+# exposed for tests
+def period_asfreq(ordinal: int, freq1: int, freq2: int, end: bool) -> int: ...
+
+def period_ordinal(
+ y: int, m: int, d: int, h: int, min: int, s: int, us: int, ps: int, freq: int
+) -> int: ...
+
+def freq_to_dtype_code(freq: BaseOffset) -> int: ...
+def validate_end_alias(how: str) -> Literal["E", "S"]: ...
+
+class Period:
+ ordinal: int # int64_t
+ freq: BaseOffset
+
+ # error: "__new__" must return a class instance (got "Union[Period, NaTType]")
+ def __new__( # type: ignore[misc]
+ cls,
+ value=None,
+ freq=None,
+ ordinal=None,
+ year=None,
+ month=None,
+ quarter=None,
+ day=None,
+ hour=None,
+ minute=None,
+ second=None,
+ ) -> Period | NaTType: ...
+
+ @classmethod
+ def _maybe_convert_freq(cls, freq) -> BaseOffset: ...
+
+ @classmethod
+ def _from_ordinal(cls, ordinal: int, freq) -> Period: ...
+
+ @classmethod
+ def now(cls, freq=...) -> Period: ...
+
+ def strftime(self, fmt: str) -> str: ...
+
+ def to_timestamp(
+ self,
+ freq: str | BaseOffset | None =...,
+ how: str = ...,
+ tz: Timezone | None = ...,
+ ) -> Timestamp: ...
+
+ def asfreq(self, freq, how=...) -> Period: ...
+
+ @property
+ def freqstr(self) -> str: ...
+
+ @property
+ def is_leap_year(self) -> bool: ...
+
+ @property
+ def daysinmonth(self) -> int: ...
+
+ @property
+ def days_in_month(self) -> int: ...
+
+ @property
+ def qyear(self) -> int: ...
+
+ @property
+ def quarter(self) -> int: ...
+
+ @property
+ def day_of_year(self) -> int: ...
+
+ @property
+ def weekday(self) -> int: ...
+
+ @property
+ def day_of_week(self) -> int: ...
+
+ @property
+ def week(self) -> int: ...
+
+ @property
+ def weekofyear(self) -> int: ...
+
+ @property
+ def second(self) -> int: ...
+
+ @property
+ def minute(self) -> int: ...
+
+ @property
+ def hour(self) -> int: ...
+
+ @property
+ def day(self) -> int: ...
+
+ @property
+ def month(self) -> int: ...
+
+ @property
+ def year(self) -> int: ...
+
+ @property
+ def end_time(self) -> Timestamp: ...
+
+ @property
+ def start_time(self) -> Timestamp: ...
+
+ def __sub__(self, other) -> Period | BaseOffset: ...
+
+ def __add__(self, other) -> Period: ...
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx
index 165f51d06af6d..0bb431bc8e1cd 100644
--- a/pandas/_libs/tslibs/period.pyx
+++ b/pandas/_libs/tslibs/period.pyx
@@ -1445,7 +1445,7 @@ def from_ordinals(const int64_t[:] values, freq):
@cython.wraparound(False)
@cython.boundscheck(False)
-def extract_ordinals(ndarray[object] values, freq):
+def extract_ordinals(ndarray[object] values, freq) -> np.ndarray:
# TODO: Change type to const object[:] when Cython supports that.
cdef:
@@ -1483,7 +1483,7 @@ def extract_ordinals(ndarray[object] values, freq):
return ordinals.base # .base to access underlying np.ndarray
-def extract_freq(ndarray[object] values):
+def extract_freq(ndarray[object] values) -> BaseOffset:
# TODO: Change type to const object[:] when Cython supports that.
cdef:
@@ -2539,7 +2539,7 @@ cdef int64_t _ordinal_from_fields(int year, int month, quarter, int day,
minute, second, 0, 0, base)
-def validate_end_alias(how):
+def validate_end_alias(how: str) -> str: # Literal["E", "S"]
how_dict = {'S': 'S', 'E': 'E',
'START': 'S', 'FINISH': 'E',
'BEGIN': 'S', 'END': 'E'}
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py
index 93df88aba2cba..c7548d008efc6 100644
--- a/pandas/core/arrays/datetimelike.py
+++ b/pandas/core/arrays/datetimelike.py
@@ -584,6 +584,8 @@ def _validate_shift_value(self, fill_value):
elif isinstance(fill_value, self._recognized_scalars):
fill_value = self._scalar_type(fill_value)
else:
+ new_fill: DatetimeLikeScalar
+
# only warn if we're not going to raise
if self._scalar_type is Period and lib.is_integer(fill_value):
# kludge for #31971 since Period(integer) tries to cast to str
diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py
index a9c94b615f49c..e9322b06b96d2 100644
--- a/pandas/core/arrays/period.py
+++ b/pandas/core/arrays/period.py
@@ -295,9 +295,17 @@ def _generate_range(cls, start, end, periods, freq, fields):
# -----------------------------------------------------------------
# DatetimeLike Interface
- def _unbox_scalar(self, value: Period | NaTType, setitem: bool = False) -> np.int64:
+ # error: Argument 1 of "_unbox_scalar" is incompatible with supertype
+ # "DatetimeLikeArrayMixin"; supertype defines the argument type as
+ # "Union[Union[Period, Any, Timedelta], NaTType]"
+ def _unbox_scalar( # type: ignore[override]
+ self,
+ value: Period | NaTType,
+ setitem: bool = False,
+ ) -> np.int64:
if value is NaT:
- return np.int64(value.value)
+ # error: Item "Period" of "Union[Period, NaTType]" has no attribute "value"
+ return np.int64(value.value) # type: ignore[union-attr]
elif isinstance(value, self._scalar_type):
self._check_compatible_with(value, setitem=setitem)
return np.int64(value.ordinal)
@@ -482,9 +490,9 @@ def to_timestamp(self, freq=None, how: str = "start") -> DatetimeArray:
freq = Period._maybe_convert_freq(freq)
base = freq._period_dtype_code
- new_data = self.asfreq(freq, how=how)
+ new_parr = self.asfreq(freq, how=how)
- new_data = libperiod.periodarr_to_dt64arr(new_data.asi8, base)
+ new_data = libperiod.periodarr_to_dt64arr(new_parr.asi8, base)
return DatetimeArray(new_data)._with_freq("infer")
# --------------------------------------------------------------------
@@ -910,7 +918,7 @@ def raise_on_incompatible(left, right):
def period_array(
- data: Sequence[Period | None] | AnyArrayLike,
+ data: Sequence[Period | str | None] | AnyArrayLike,
freq: str | Tick | None = None,
copy: bool = False,
) -> PeriodArray:
diff --git a/pandas/core/resample.py b/pandas/core/resample.py
index 213c20294025d..aae6314968695 100644
--- a/pandas/core/resample.py
+++ b/pandas/core/resample.py
@@ -1734,7 +1734,8 @@ def _get_period_bins(self, ax: PeriodIndex):
# Get offset for bin edge (not label edge) adjustment
start_offset = Period(start, self.freq) - Period(p_start, self.freq)
- bin_shift = start_offset.n % freq_mult
+ # error: Item "Period" of "Union[Period, Any]" has no attribute "n"
+ bin_shift = start_offset.n % freq_mult # type: ignore[union-attr]
start = p_start
labels = binner = period_range(
@@ -1903,17 +1904,17 @@ def _get_period_range_edges(
raise TypeError("'first' and 'last' must be instances of type Period")
# GH 23882
- first = first.to_timestamp()
- last = last.to_timestamp()
- adjust_first = not freq.is_on_offset(first)
- adjust_last = freq.is_on_offset(last)
+ first_ts = first.to_timestamp()
+ last_ts = last.to_timestamp()
+ adjust_first = not freq.is_on_offset(first_ts)
+ adjust_last = freq.is_on_offset(last_ts)
- first, last = _get_timestamp_range_edges(
- first, last, freq, closed=closed, origin=origin, offset=offset
+ first_ts, last_ts = _get_timestamp_range_edges(
+ first_ts, last_ts, freq, closed=closed, origin=origin, offset=offset
)
- first = (first + int(adjust_first) * freq).to_period(freq)
- last = (last - int(adjust_last) * freq).to_period(freq)
+ first = (first_ts + int(adjust_first) * freq).to_period(freq)
+ last = (last_ts - int(adjust_last) * freq).to_period(freq)
return first, last
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/40990 | 2021-04-16T21:30:41Z | 2021-05-05T12:52:29Z | 2021-05-05T12:52:29Z | 2021-05-05T14:47:17Z |
Bug in loc returning multiindex in wrong oder with duplicated indexer | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index d357e4a633347..e29e740ddf8fe 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -871,6 +871,7 @@ Indexing
- Bug in :meth:`DataFrame.loc.__setitem__` when setting-with-expansion incorrectly raising when the index in the expanding axis contains duplicates (:issue:`40096`)
- Bug in :meth:`DataFrame.loc` incorrectly matching non-boolean index elements (:issue:`20432`)
- Bug in :meth:`Series.__delitem__` with ``ExtensionDtype`` incorrectly casting to ``ndarray`` (:issue:`40386`)
+- Bug in :meth:`DataFrame.loc` returning :class:`MultiIndex` in wrong order if indexer has duplicates (:issue:`40978`)
- Bug in :meth:`DataFrame.__setitem__` raising ``TypeError`` when using a str subclass as the column name with a :class:`DatetimeIndex` (:issue:`37366`)
Missing
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 1a3719233a1da..532e39487ad7b 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -3446,6 +3446,7 @@ def _reorder_indexer(
new_order = np.arange(n)[indexer]
elif is_list_like(k):
# Generate a map with all level codes as sorted initially
+ k = algos.unique(k)
key_order_map = np.ones(len(self.levels[i]), dtype=np.uint64) * len(
self.levels[i]
)
diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py
index 0c6f2faf77f00..cf1ab3eadc7a4 100644
--- a/pandas/tests/indexing/multiindex/test_loc.py
+++ b/pandas/tests/indexing/multiindex/test_loc.py
@@ -764,6 +764,28 @@ def test_loc_getitem_index_differently_ordered_slice_none():
tm.assert_frame_equal(result, expected)
+@pytest.mark.parametrize("indexer", [[1, 2, 7, 6, 2, 3, 8, 7], [1, 2, 7, 6, 3, 8]])
+def test_loc_getitem_index_differently_ordered_slice_none_duplicates(indexer):
+ # GH#40978
+ df = DataFrame(
+ [1] * 8,
+ index=MultiIndex.from_tuples(
+ [(1, 1), (1, 2), (1, 7), (1, 6), (2, 2), (2, 3), (2, 8), (2, 7)]
+ ),
+ columns=["a"],
+ )
+ result = df.loc[(slice(None), indexer), :]
+ expected = DataFrame(
+ [1] * 8,
+ index=[[1, 1, 2, 1, 2, 1, 2, 2], [1, 2, 2, 7, 7, 6, 3, 8]],
+ columns=["a"],
+ )
+ tm.assert_frame_equal(result, expected)
+
+ result = df.loc[df.index.isin(indexer, level=1), :]
+ tm.assert_frame_equal(result, df)
+
+
def test_loc_getitem_drops_levels_for_one_row_dataframe():
# GH#10521
mi = MultiIndex.from_arrays([["x"], ["y"], ["z"]], names=["a", "b", "c"])
| - [x] closes #40978
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
This fixes the ordering, but I am not sure if an indexer with duplicates in this case should return the same as an indexer which is unique with the same elements. | https://api.github.com/repos/pandas-dev/pandas/pulls/40987 | 2021-04-16T20:26:55Z | 2021-05-26T02:04:16Z | 2021-05-26T02:04:15Z | 2021-05-27T10:26:39Z |
TYP: Signature of "reindex" incompatible with supertype "NDFrame" | diff --git a/pandas/core/series.py b/pandas/core/series.py
index f0f5bd7c3e2b2..a53d65edabec2 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -4604,8 +4604,17 @@ def set_axis(self, labels, axis: Axis = 0, inplace: bool = False):
optional_labels=_shared_doc_kwargs["optional_labels"],
optional_axis=_shared_doc_kwargs["optional_axis"],
)
- def reindex(self, index=None, **kwargs):
- return super().reindex(index=index, **kwargs)
+ def reindex(self, *args, **kwargs) -> Series:
+ if len(args) > 1:
+ raise TypeError("Only one positional argument ('index') is allowed")
+ if args:
+ (index,) = args
+ if "index" in kwargs:
+ raise TypeError(
+ "'index' passed as both positional and keyword argument"
+ )
+ kwargs.update({"index": index})
+ return super().reindex(**kwargs)
@deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "labels"])
def drop(
diff --git a/pandas/tests/series/methods/test_reindex.py b/pandas/tests/series/methods/test_reindex.py
index be9f96c8b509a..4350a5d9ac989 100644
--- a/pandas/tests/series/methods/test_reindex.py
+++ b/pandas/tests/series/methods/test_reindex.py
@@ -348,6 +348,31 @@ def test_reindex_periodindex_with_object(p_values, o_values, values, expected_va
tm.assert_series_equal(result, expected)
+def test_reindex_too_many_args():
+ # GH 40980
+ ser = Series([1, 2])
+ with pytest.raises(
+ TypeError, match=r"Only one positional argument \('index'\) is allowed"
+ ):
+ ser.reindex([2, 3], False)
+
+
+def test_reindex_double_index():
+ # GH 40980
+ ser = Series([1, 2])
+ msg = r"'index' passed as both positional and keyword argument"
+ with pytest.raises(TypeError, match=msg):
+ ser.reindex([2, 3], index=[3, 4])
+
+
+def test_reindex_no_posargs():
+ # GH 40980
+ ser = Series([1, 2])
+ result = ser.reindex(index=[1, 0])
+ expected = Series([2, 1], index=[1, 0])
+ tm.assert_series_equal(result, expected)
+
+
@pytest.mark.parametrize("values", [[["a"], ["x"]], [[], []]])
def test_reindex_empty_with_level(values):
# GH41170
| - [ ] closes #40980
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/40984 | 2021-04-16T15:46:51Z | 2021-11-26T15:05:13Z | 2021-11-26T15:05:13Z | 2021-11-26T17:39:52Z |
REF: enforce annotation in maybe_downcast_to_dtype | diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index a373b57accaa9..6726374dbe30e 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -4,7 +4,6 @@
from __future__ import annotations
-from contextlib import suppress
from datetime import (
date,
datetime,
@@ -29,7 +28,6 @@
NaT,
OutOfBoundsDatetime,
OutOfBoundsTimedelta,
- Period,
Timedelta,
Timestamp,
conversion,
@@ -87,7 +85,6 @@
PeriodDtype,
)
from pandas.core.dtypes.generic import (
- ABCDataFrame,
ABCExtensionArray,
ABCSeries,
)
@@ -249,9 +246,6 @@ def maybe_downcast_to_dtype(result: ArrayLike, dtype: str | np.dtype) -> ArrayLi
try to cast to the specified dtype (e.g. convert back to bool/int
or could be an astype of float64->float32
"""
- if isinstance(result, ABCDataFrame):
- # see test_pivot_table_doctest_case
- return result
do_round = False
if isinstance(dtype, str):
@@ -278,15 +272,9 @@ def maybe_downcast_to_dtype(result: ArrayLike, dtype: str | np.dtype) -> ArrayLi
dtype = np.dtype(dtype)
- elif dtype.type is Period:
- from pandas.core.arrays import PeriodArray
-
- with suppress(TypeError):
- # e.g. TypeError: int() argument must be a string, a
- # bytes-like object or a number, not 'Period
-
- # error: "dtype[Any]" has no attribute "freq"
- return PeriodArray(result, freq=dtype.freq) # type: ignore[attr-defined]
+ if not isinstance(dtype, np.dtype):
+ # enforce our signature annotation
+ raise TypeError(dtype) # pragma: no cover
converted = maybe_downcast_numeric(result, dtype, do_round)
if converted is not result:
@@ -295,15 +283,7 @@ def maybe_downcast_to_dtype(result: ArrayLike, dtype: str | np.dtype) -> ArrayLi
# a datetimelike
# GH12821, iNaT is cast to float
if dtype.kind in ["M", "m"] and result.dtype.kind in ["i", "f"]:
- if isinstance(dtype, DatetimeTZDtype):
- # convert to datetime and change timezone
- i8values = result.astype("i8", copy=False)
- cls = dtype.construct_array_type()
- # equiv: DatetimeArray(i8values).tz_localize("UTC").tz_convert(dtype.tz)
- dt64values = i8values.view("M8[ns]")
- result = cls._simple_new(dt64values, dtype=dtype)
- else:
- result = result.astype(dtype)
+ result = result.astype(dtype)
return result
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 37fc5de95b3d2..38766d2856cfe 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -7213,13 +7213,14 @@ def combine(
else:
# if we have different dtypes, possibly promote
new_dtype = find_common_type([this_dtype, other_dtype])
- if not is_dtype_equal(this_dtype, new_dtype):
- series = series.astype(new_dtype)
- if not is_dtype_equal(other_dtype, new_dtype):
- otherSeries = otherSeries.astype(new_dtype)
+ series = series.astype(new_dtype, copy=False)
+ otherSeries = otherSeries.astype(new_dtype, copy=False)
arr = func(series, otherSeries)
- arr = maybe_downcast_to_dtype(arr, new_dtype)
+ if isinstance(new_dtype, np.dtype):
+ # if new_dtype is an EA Dtype, then `func` is expected to return
+ # the correct dtype without any additional casting
+ arr = maybe_downcast_to_dtype(arr, new_dtype)
result[col] = arr
diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py
index 795f5250012cb..ddc6e92b04927 100644
--- a/pandas/core/reshape/pivot.py
+++ b/pandas/core/reshape/pivot.py
@@ -174,7 +174,15 @@ def __internal_pivot_table(
and v in agged
and not is_integer_dtype(agged[v])
):
- agged[v] = maybe_downcast_to_dtype(agged[v], data[v].dtype)
+ if isinstance(agged[v], ABCDataFrame):
+ # exclude DataFrame case bc maybe_downcast_to_dtype expects
+ # ArrayLike
+ # TODO: why does test_pivot_table_doctest_case fail if
+ # we don't do this apparently-unnecessary setitem?
+ agged[v] = agged[v]
+ pass
+ else:
+ agged[v] = maybe_downcast_to_dtype(agged[v], data[v].dtype)
table = agged
diff --git a/pandas/tests/dtypes/cast/test_downcast.py b/pandas/tests/dtypes/cast/test_downcast.py
index 0c3e9841eba3e..5217b38f155c8 100644
--- a/pandas/tests/dtypes/cast/test_downcast.py
+++ b/pandas/tests/dtypes/cast/test_downcast.py
@@ -5,11 +5,7 @@
from pandas.core.dtypes.cast import maybe_downcast_to_dtype
-from pandas import (
- DatetimeIndex,
- Series,
- Timestamp,
-)
+from pandas import Series
import pandas._testing as tm
@@ -77,7 +73,7 @@ def test_downcast_conversion_nan(float_dtype):
def test_downcast_conversion_empty(any_real_dtype):
dtype = any_real_dtype
arr = np.array([], dtype=dtype)
- result = maybe_downcast_to_dtype(arr, "int64")
+ result = maybe_downcast_to_dtype(arr, np.dtype("int64"))
tm.assert_numpy_array_equal(result, np.array([], dtype=np.int64))
@@ -89,15 +85,3 @@ def test_datetime_likes_nan(klass):
exp = np.array([1, 2, klass("NaT")], dtype)
res = maybe_downcast_to_dtype(arr, dtype)
tm.assert_numpy_array_equal(res, exp)
-
-
-@pytest.mark.parametrize("as_asi", [True, False])
-def test_datetime_with_timezone(as_asi):
- # see gh-15426
- ts = Timestamp("2016-01-01 12:00:00", tz="US/Pacific")
- exp = DatetimeIndex([ts, ts])._data
-
- obj = exp.asi8 if as_asi else exp
- res = maybe_downcast_to_dtype(obj, exp.dtype)
-
- tm.assert_datetime_array_equal(res, exp)
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/40982 | 2021-04-16T14:57:25Z | 2021-04-16T19:02:10Z | 2021-04-16T19:02:10Z | 2021-04-16T21:25:37Z |
TST: use expected_html for to_html tests | diff --git a/pandas/tests/io/formats/data/html/gh13828_expected_output.html b/pandas/tests/io/formats/data/html/gh13828_expected_output.html
new file mode 100644
index 0000000000000..690d638c31d5b
--- /dev/null
+++ b/pandas/tests/io/formats/data/html/gh13828_expected_output.html
@@ -0,0 +1,21 @@
+<table border="1" class="dataframe">
+ <thead>
+ <tr style="text-align: right;">
+ <th></th>
+ <th>Group</th>
+ <th>Data</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <th>0</th>
+ <td>A</td>
+ <td>1.22</td>
+ </tr>
+ <tr>
+ <th>1</th>
+ <td>A</td>
+ <td>{na_rep}</td>
+ </tr>
+ </tbody>
+</table>
diff --git a/pandas/tests/io/formats/data/html/gh40024_expected_output.html b/pandas/tests/io/formats/data/html/gh40024_expected_output.html
new file mode 100644
index 0000000000000..0877c29525d2c
--- /dev/null
+++ b/pandas/tests/io/formats/data/html/gh40024_expected_output.html
@@ -0,0 +1,18 @@
+<table border="1" class="dataframe">
+ <thead>
+ <tr style="text-align: right;">
+ <th></th>
+ <th>x</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <th>0</th>
+ <td>1,000</td>
+ </tr>
+ <tr>
+ <th>1</th>
+ <td>test</td>
+ </tr>
+ </tbody>
+</table>
diff --git a/pandas/tests/io/formats/test_to_html.py b/pandas/tests/io/formats/test_to_html.py
index ec2f109900f3a..a61e77bec9828 100644
--- a/pandas/tests/io/formats/test_to_html.py
+++ b/pandas/tests/io/formats/test_to_html.py
@@ -851,7 +851,7 @@ def test_to_html_multilevel(multiindex_year_month_day_dataframe_random_data):
@pytest.mark.parametrize("na_rep", ["NaN", "Ted"])
-def test_to_html_na_rep_and_float_format(na_rep):
+def test_to_html_na_rep_and_float_format(na_rep, datapath):
# https://github.com/pandas-dev/pandas/issues/13828
df = DataFrame(
[
@@ -861,51 +861,14 @@ def test_to_html_na_rep_and_float_format(na_rep):
columns=["Group", "Data"],
)
result = df.to_html(na_rep=na_rep, float_format="{:.2f}".format)
- expected = f"""<table border="1" class="dataframe">
- <thead>
- <tr style="text-align: right;">
- <th></th>
- <th>Group</th>
- <th>Data</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <th>0</th>
- <td>A</td>
- <td>1.22</td>
- </tr>
- <tr>
- <th>1</th>
- <td>A</td>
- <td>{na_rep}</td>
- </tr>
- </tbody>
-</table>"""
+ expected = expected_html(datapath, "gh13828_expected_output")
+ expected = expected.format(na_rep=na_rep)
assert result == expected
-def test_to_html_float_format_object_col():
+def test_to_html_float_format_object_col(datapath):
# GH#40024
df = DataFrame(data={"x": [1000.0, "test"]})
result = df.to_html(float_format=lambda x: f"{x:,.0f}")
- expected = """<table border="1" class="dataframe">
- <thead>
- <tr style="text-align: right;">
- <th></th>
- <th>x</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <th>0</th>
- <td>1,000</td>
- </tr>
- <tr>
- <th>1</th>
- <td>test</td>
- </tr>
- </tbody>
-</table>"""
-
+ expected = expected_html(datapath, "gh40024_expected_output")
assert result == expected
| xref https://github.com/pandas-dev/pandas/pull/40850#discussion_r611022208 | https://api.github.com/repos/pandas-dev/pandas/pulls/40981 | 2021-04-16T14:33:54Z | 2021-04-16T15:57:20Z | 2021-04-16T15:57:20Z | 2021-04-16T16:03:33Z |
TYP: Signature of "rename" incompatible with supertype "NDFrame" | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 76f68fdaa7845..803d1c914c954 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -5073,10 +5073,6 @@ def drop(
errors=errors,
)
- @rewrite_axis_style_signature(
- "mapper",
- [("copy", True), ("inplace", False), ("level", None), ("errors", "ignore")],
- )
def rename(
self,
mapper: Renamer | None = None,
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py
index faa32b31a73d7..1dafe1618a9f8 100644
--- a/pandas/core/groupby/groupby.py
+++ b/pandas/core/groupby/groupby.py
@@ -2082,7 +2082,8 @@ def size(self) -> DataFrame | Series:
result = self._obj_1d_constructor(result)
if not self.as_index:
- result = result.rename("size").reset_index()
+ # Item "None" of "Optional[Series]" has no attribute "reset_index"
+ result = result.rename("size").reset_index() # type: ignore[union-attr]
return self._reindex_output(result, fill_value=0)
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 03fac7cceabb7..d5909b8659903 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -4468,14 +4468,16 @@ def align(
def rename(
self,
- index=None,
+ mapper=None,
*,
+ index=None,
+ columns=None,
axis=None,
copy=True,
inplace=False,
level=None,
errors="ignore",
- ):
+ ) -> Series | None:
"""
Alter Series index labels or name.
@@ -4491,7 +4493,7 @@ def rename(
----------
axis : {0 or "index"}
Unused. Accepted for compatibility with DataFrame method only.
- index : scalar, hashable sequence, dict-like or function, optional
+ mapper : scalar, hashable sequence, dict-like or function, optional
Functions or dict-like are transformations to apply to
the index.
Scalar or hashable sequence-like will alter the ``Series.name``
@@ -4539,12 +4541,16 @@ def rename(
# Make sure we raise if an invalid 'axis' is passed.
axis = self._get_axis_number(axis)
- if callable(index) or is_dict_like(index):
+ if index is not None and mapper is not None:
+ raise TypeError("Cannot specify both 'mapper' and 'index'")
+ if mapper is None:
+ mapper = index
+ if callable(mapper) or is_dict_like(mapper):
return super().rename(
- index, copy=copy, inplace=inplace, level=level, errors=errors
+ mapper, copy=copy, inplace=inplace, level=level, errors=errors
)
else:
- return self._set_name(index, inplace=inplace)
+ return self._set_name(mapper, inplace=inplace)
@overload
def set_axis(
diff --git a/pandas/io/json/_normalize.py b/pandas/io/json/_normalize.py
index 2c2c127394fb6..36a7949a9f1e3 100644
--- a/pandas/io/json/_normalize.py
+++ b/pandas/io/json/_normalize.py
@@ -517,7 +517,11 @@ def _recursive_extract(data, path, seen_meta, level=0):
result = DataFrame(records)
if record_prefix is not None:
- result = result.rename(columns=lambda x: f"{record_prefix}{x}")
+ # Incompatible types in assignment (expression has type "Optional[DataFrame]",
+ # variable has type "DataFrame")
+ result = result.rename( # type: ignore[assignment]
+ columns=lambda x: f"{record_prefix}{x}"
+ )
# Data types, a problem
for k, v in meta_vals.items():
diff --git a/pandas/tests/series/methods/test_rename.py b/pandas/tests/series/methods/test_rename.py
index a78abfa63cff4..3425dd8f019e7 100644
--- a/pandas/tests/series/methods/test_rename.py
+++ b/pandas/tests/series/methods/test_rename.py
@@ -105,6 +105,19 @@ def test_rename_callable(self):
assert result.name == expected.name
+ def test_rename_method_and_index(self):
+ # GH 40977
+ ser = Series([1, 2])
+ with pytest.raises(TypeError, match="Cannot specify both 'mapper' and 'index'"):
+ ser.rename(str, index=str)
+
+ def test_rename_none(self):
+ # GH 40977
+ ser = Series([1, 2], name="foo")
+ result = ser.rename(None)
+ expected = Series([1, 2])
+ tm.assert_series_equal(result, expected)
+
def test_rename_series_with_multiindex(self):
# issue #43659
arrays = [
| - [x] closes #40977
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
---
@WillAyd this should still be backwards compatible, it just makes the signature compatible with its parent's | https://api.github.com/repos/pandas-dev/pandas/pulls/40979 | 2021-04-16T14:17:39Z | 2021-11-26T15:36:25Z | 2021-11-26T15:36:25Z | 2021-11-26T17:44:30Z |
TYP add some missing types to series | diff --git a/pandas/core/series.py b/pandas/core/series.py
index 5c605a6b441c6..1944e5e6196b4 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -1019,7 +1019,7 @@ def _get_value(self, label, takeable: bool = False):
loc = self.index.get_loc(label)
return self.index._get_values_for_loc(self, loc, label)
- def __setitem__(self, key, value):
+ def __setitem__(self, key, value) -> None:
key = com.apply_if_callable(key, self)
cacher_needs_updating = self._check_is_chained_assignment_possible()
@@ -1058,7 +1058,7 @@ def __setitem__(self, key, value):
if cacher_needs_updating:
self._maybe_update_cacher()
- def _set_with_engine(self, key, value):
+ def _set_with_engine(self, key, value) -> None:
# fails with AttributeError for IntervalIndex
loc = self.index._engine.get_loc(key)
# error: Argument 1 to "validate_numeric_casting" has incompatible type
@@ -1094,7 +1094,7 @@ def _set_with(self, key, value):
else:
self.loc[key] = value
- def _set_labels(self, key, value):
+ def _set_labels(self, key, value) -> None:
key = com.asarray_tuplesafe(key)
indexer: np.ndarray = self.index.get_indexer(key)
mask = indexer == -1
@@ -1102,7 +1102,7 @@ def _set_labels(self, key, value):
raise KeyError(f"{key[mask]} not in index")
self._set_values(indexer, value)
- def _set_values(self, key, value):
+ def _set_values(self, key, value) -> None:
if isinstance(key, Series):
key = key._values
| Noticed this while working on #40973
Those without any types won't be checked by `mypy`
e.g.:
```console
$ cat t.py
from typing import final
class Foo:
@final
def foo(x) -> None:
pass
class Bar(Foo):
def foo(x):
pass
$ mypy t.py
Success: no issues found in 1 source file
```
Adding in `-> None`:
```console
$ cat t.py
from typing import final
class Foo:
@final
def foo(x) -> None:
pass
class Bar(Foo):
def foo(x) -> None:
pass
$ mypy t.py
t.py:9: error: Cannot override final attribute "foo" (previously declared in base class "Foo") [misc]
Found 1 error in 1 file (checked 1 source file)
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/40975 | 2021-04-16T10:21:50Z | 2021-04-16T16:54:14Z | 2021-04-16T16:54:14Z | 2021-04-16T17:31:23Z |
BUG: Fix pd.read_orc raising AttributeError | diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst
index b6351ac2232ff..89b21d1984ad3 100644
--- a/doc/source/getting_started/install.rst
+++ b/doc/source/getting_started/install.rst
@@ -362,6 +362,21 @@ pyarrow 0.15.0 Parquet, ORC, and feather reading /
pyreadstat SPSS files (.sav) reading
========================= ================== =============================================================
+.. _install.warn_orc:
+
+.. warning::
+
+ * If you want to use :func:`~pandas.read_orc`, it is highly recommended to install pyarrow using conda.
+ The following is a summary of the environment in which :func:`~pandas.read_orc` can work.
+
+ ========================= ================== =============================================================
+ System Conda PyPI
+ ========================= ================== =============================================================
+ Linux Successful Failed(pyarrow==3.0 Successful)
+ macOS Successful Failed
+ Windows Failed Failed
+ ========================= ================== =============================================================
+
Access data in the cloud
^^^^^^^^^^^^^^^^^^^^^^^^
diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst
index 3b7a6037a9715..5148bb87b0eb0 100644
--- a/doc/source/user_guide/io.rst
+++ b/doc/source/user_guide/io.rst
@@ -5443,6 +5443,11 @@ Similar to the :ref:`parquet <io.parquet>` format, the `ORC Format <https://orc.
for data frames. It is designed to make reading data frames efficient. pandas provides *only* a reader for the
ORC format, :func:`~pandas.read_orc`. This requires the `pyarrow <https://arrow.apache.org/docs/python/>`__ library.
+.. warning::
+
+ * It is *highly recommended* to install pyarrow using conda due to some issues occurred by pyarrow.
+ * :func:`~pandas.read_orc` is not supported on Windows yet, you can find valid environments on :ref:`install optional dependencies <install.warn_orc>`.
+
.. _io.sql:
SQL queries
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 85d9acff353be..58f46206b6d57 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -783,6 +783,7 @@ I/O
- Bug in :func:`read_sas` raising ``ValueError`` when ``datetimes`` were null (:issue:`39725`)
- Bug in :func:`read_excel` dropping empty values from single-column spreadsheets (:issue:`39808`)
- Bug in :meth:`DataFrame.to_string` misplacing the truncation column when ``index=False`` (:issue:`40907`)
+- Bug in :func:`read_orc` always raising ``AttributeError`` (:issue:`40918`)
Period
^^^^^^
diff --git a/pandas/io/orc.py b/pandas/io/orc.py
index db14a07e4b91b..6bdb4df806b5c 100644
--- a/pandas/io/orc.py
+++ b/pandas/io/orc.py
@@ -1,10 +1,10 @@
""" orc compat """
from __future__ import annotations
-import distutils
from typing import TYPE_CHECKING
from pandas._typing import FilePathOrBuffer
+from pandas.compat._optional import import_optional_dependency
from pandas.io.common import get_handle
@@ -42,13 +42,16 @@ def read_orc(
Returns
-------
DataFrame
+
+ Notes
+ -------
+ Before using this function you should read the :ref:`user guide about ORC <io.orc>`
+ and :ref:`install optional dependencies <install.warn_orc>`.
"""
# we require a newer version of pyarrow than we support for parquet
- import pyarrow
- if distutils.version.LooseVersion(pyarrow.__version__) < "0.13.0":
- raise ImportError("pyarrow must be >= 0.13.0 for read_orc")
+ orc = import_optional_dependency("pyarrow.orc")
with get_handle(path, "rb", is_text=False) as handles:
- orc_file = pyarrow.orc.ORCFile(handles.handle)
+ orc_file = orc.ORCFile(handles.handle)
return orc_file.read(columns=columns, **kwargs).to_pandas()
diff --git a/pandas/tests/io/test_orc.py b/pandas/tests/io/test_orc.py
index a1f9c6f6af51a..f34e9b940317d 100644
--- a/pandas/tests/io/test_orc.py
+++ b/pandas/tests/io/test_orc.py
@@ -9,7 +9,6 @@
from pandas import read_orc
import pandas._testing as tm
-pytest.importorskip("pyarrow", minversion="0.13.0")
pytest.importorskip("pyarrow.orc")
pytestmark = pytest.mark.filterwarnings(
| - [x] closes #40918
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
---
I am not sure if this is a reasonable solution. Cause If users install PyArrow from PyPI on MacOS or Win10(works fine on Linux), it will always raise an `AttributeError` exception.
Should we add some operating system requirments to `pd.read_orc`? ([Related to PyArrow's JIRA #7811](https://issues.apache.org/jira/browse/ARROW-7811)).
| https://api.github.com/repos/pandas-dev/pandas/pulls/40970 | 2021-04-16T06:25:47Z | 2021-04-21T12:41:03Z | 2021-04-21T12:41:02Z | 2021-04-25T02:41:50Z |
Updated qcut for Float64DType Issue #40730 | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 85d9acff353be..4ef8fe116596f 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -695,7 +695,7 @@ Conversion
- Bug in :class:`Index` construction silently ignoring a passed ``dtype`` when the data cannot be cast to that dtype (:issue:`21311`)
- Bug in :meth:`StringArray.astype` falling back to numpy and raising when converting to ``dtype='categorical'`` (:issue:`40450`)
- Bug in :class:`DataFrame` construction with a dictionary containing an arraylike with ``ExtensionDtype`` and ``copy=True`` failing to make a copy (:issue:`38939`)
--
+- Bug in :meth:`qcut` raising error when taking ``Float64DType`` as input (:issue:`40730`)
Strings
^^^^^^^
diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py
index 41e1ff41d9ba2..7b9c3883d74e3 100644
--- a/pandas/core/reshape/tile.py
+++ b/pandas/core/reshape/tile.py
@@ -24,8 +24,8 @@
is_datetime_or_timedelta_dtype,
is_extension_array_dtype,
is_integer,
- is_integer_dtype,
is_list_like,
+ is_numeric_dtype,
is_scalar,
is_timedelta64_dtype,
)
@@ -488,7 +488,7 @@ def _coerce_to_type(x):
# 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.dtype) and is_integer_dtype(x.dtype):
+ elif is_extension_array_dtype(x.dtype) and is_numeric_dtype(x.dtype):
x = x.to_numpy(dtype=np.float64, na_value=np.nan)
if dtype is not None:
diff --git a/pandas/tests/reshape/test_qcut.py b/pandas/tests/reshape/test_qcut.py
index 7996c15ae8e64..c12d28f6f1380 100644
--- a/pandas/tests/reshape/test_qcut.py
+++ b/pandas/tests/reshape/test_qcut.py
@@ -293,8 +293,8 @@ def test_qcut_bool_coercion_to_int(bins, box, compare):
@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)
+def test_qcut_nullable_integer(q, any_nullable_numeric_dtype):
+ arr = pd.array(np.arange(100), dtype=any_nullable_numeric_dtype)
arr[::2] = pd.NA
result = qcut(arr, q)
| This PR is used to address #40730 . qcut is now able to support both intdtype and floatdtype | https://api.github.com/repos/pandas-dev/pandas/pulls/40969 | 2021-04-16T04:14:58Z | 2021-04-26T12:04:15Z | 2021-04-26T12:04:15Z | 2021-04-26T12:04:23Z |
CLN: de-duplicate reindex/align code | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index bb8de35d22462..cbc353eead464 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -8813,15 +8813,7 @@ def _align_frame(
right = right.fillna(method=method, axis=fill_axis, limit=limit)
# if DatetimeIndex have different tz, convert to UTC
- if is_datetime64tz_dtype(left.index.dtype):
- if left.index.tz != right.index.tz:
- if join_index is not None:
- # GH#33671 ensure we don't change the index on
- # our original Series (NB: by default deep=False)
- left = left.copy()
- right = right.copy()
- left.index = join_index
- right.index = join_index
+ left, right = _align_as_utc(left, right, join_index)
return (
left.__finalize__(self),
@@ -8863,27 +8855,18 @@ def _align_series(
else:
# one has > 1 ndim
fdata = self._mgr
- if axis == 0:
- join_index = self.index
+ if axis in [0, 1]:
+ join_index = self.axes[axis]
lidx, ridx = None, None
- if not self.index.equals(other.index):
- join_index, lidx, ridx = self.index.join(
+ if not join_index.equals(other.index):
+ join_index, lidx, ridx = join_index.join(
other.index, how=join, level=level, return_indexers=True
)
if lidx is not None:
- fdata = fdata.reindex_indexer(join_index, lidx, axis=1)
+ bm_axis = self._get_block_manager_axis(axis)
+ fdata = fdata.reindex_indexer(join_index, lidx, axis=bm_axis)
- elif axis == 1:
- join_index = self.columns
- lidx, ridx = None, None
- if not self.columns.equals(other.index):
- join_index, lidx, ridx = self.columns.join(
- other.index, how=join, level=level, return_indexers=True
- )
-
- if lidx is not None:
- fdata = fdata.reindex_indexer(join_index, lidx, axis=0)
else:
raise ValueError("Must specify axis=0 or 1")
@@ -8905,15 +8888,7 @@ def _align_series(
# if DatetimeIndex have different tz, convert to UTC
if is_series or (not is_series and axis == 0):
- if is_datetime64tz_dtype(left.index.dtype):
- if left.index.tz != right.index.tz:
- if join_index is not None:
- # GH#33671 ensure we don't change the index on
- # our original Series (NB: by default deep=False)
- left = left.copy()
- right = right.copy()
- left.index = join_index
- right.index = join_index
+ left, right = _align_as_utc(left, right, join_index)
return (
left.__finalize__(self),
@@ -11887,3 +11862,23 @@ def _doc_params(cls):
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.
"""
+
+
+def _align_as_utc(
+ left: FrameOrSeries, right: FrameOrSeries, join_index: Index | None
+) -> tuple[FrameOrSeries, FrameOrSeries]:
+ """
+ If we are aligning timezone-aware DatetimeIndexes and the timezones
+ do not match, convert both to UTC.
+ """
+ if is_datetime64tz_dtype(left.index.dtype):
+ if left.index.tz != right.index.tz:
+ if join_index is not None:
+ # GH#33671 ensure we don't change the index on
+ # our original Series (NB: by default deep=False)
+ left = left.copy()
+ right = right.copy()
+ left.index = join_index
+ right.index = join_index
+
+ return left, right
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/40968 | 2021-04-15T20:54:49Z | 2021-04-16T01:09:45Z | 2021-04-16T01:09:45Z | 2021-04-16T01:14:56Z |
TST: Add test for union with duplicates | diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py
index c9d034361d8c4..75fc7a782772a 100644
--- a/pandas/tests/test_algos.py
+++ b/pandas/tests/test_algos.py
@@ -2418,10 +2418,16 @@ def test_diff_low_precision_int(self, dtype):
tm.assert_numpy_array_equal(result, expected)
-def test_union_with_duplicates():
+@pytest.mark.parametrize("op", [np.array, pd.array])
+def test_union_with_duplicates(op):
# GH#36289
- lvals = np.array([3, 1, 3, 4])
- rvals = np.array([2, 3, 1, 1])
- result = algos.union_with_duplicates(lvals, rvals)
- expected = np.array([3, 3, 1, 1, 4, 2])
- tm.assert_numpy_array_equal(result, expected)
+ lvals = op([3, 1, 3, 4])
+ rvals = op([2, 3, 1, 1])
+ expected = op([3, 3, 1, 1, 4, 2])
+ if isinstance(expected, np.ndarray):
+ result = algos.union_with_duplicates(lvals, rvals)
+ tm.assert_numpy_array_equal(result, expected)
+ else:
+ with tm.assert_produces_warning(RuntimeWarning):
+ result = algos.union_with_duplicates(lvals, rvals)
+ tm.assert_extension_array_equal(result, expected)
| - [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
| https://api.github.com/repos/pandas-dev/pandas/pulls/40967 | 2021-04-15T20:24:41Z | 2021-04-20T22:51:39Z | 2021-04-20T22:51:38Z | 2021-04-21T20:40:26Z |
REF: move union_categoricals call outside of cython | diff --git a/pandas/_libs/parsers.pyi b/pandas/_libs/parsers.pyi
index 1051c319b769b..18ae23e7fb90d 100644
--- a/pandas/_libs/parsers.pyi
+++ b/pandas/_libs/parsers.pyi
@@ -58,7 +58,6 @@ class TextReader:
true_values=...,
false_values=...,
allow_leading_cols: bool = ...,
- low_memory: bool = ...,
skiprows=...,
skipfooter: int = ..., # int64_t
verbose: bool = ...,
@@ -75,3 +74,4 @@ class TextReader:
def close(self) -> None: ...
def read(self, rows: int | None = ...) -> dict[int, ArrayLike]: ...
+ def read_low_memory(self, rows: int | None) -> list[dict[int, ArrayLike]]: ...
diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx
index 1a5ac31cc821b..2abb7e0ea3ac2 100644
--- a/pandas/_libs/parsers.pyx
+++ b/pandas/_libs/parsers.pyx
@@ -94,7 +94,6 @@ from pandas._libs.khash cimport (
)
from pandas.errors import (
- DtypeWarning,
EmptyDataError,
ParserError,
ParserWarning,
@@ -108,9 +107,7 @@ from pandas.core.dtypes.common import (
is_float_dtype,
is_integer_dtype,
is_object_dtype,
- pandas_dtype,
)
-from pandas.core.dtypes.concat import union_categoricals
cdef:
float64_t INF = <float64_t>np.inf
@@ -317,7 +314,7 @@ cdef class TextReader:
cdef public:
int64_t leading_cols, table_width, skipfooter, buffer_lines
- bint allow_leading_cols, mangle_dupe_cols, low_memory
+ bint allow_leading_cols, mangle_dupe_cols
bint delim_whitespace
object delimiter # bytes or str
object converters
@@ -362,7 +359,6 @@ cdef class TextReader:
true_values=None,
false_values=None,
bint allow_leading_cols=True,
- bint low_memory=False,
skiprows=None,
skipfooter=0, # int64_t
bint verbose=False,
@@ -479,7 +475,6 @@ cdef class TextReader:
self.na_filter = na_filter
self.verbose = verbose
- self.low_memory = low_memory
if float_precision == "round_trip":
# see gh-15140
@@ -492,12 +487,10 @@ cdef class TextReader:
raise ValueError(f'Unrecognized float_precision option: '
f'{float_precision}')
- if isinstance(dtype, dict):
- dtype = {k: pandas_dtype(dtype[k])
- for k in dtype}
- elif dtype is not None:
- dtype = pandas_dtype(dtype)
-
+ # Caller is responsible for ensuring we have one of
+ # - None
+ # - DtypeObj
+ # - dict[Any, DtypeObj]
self.dtype = dtype
# XXX
@@ -774,17 +767,18 @@ cdef class TextReader:
"""
rows=None --> read all rows
"""
- if self.low_memory:
- # Conserve intermediate space
- columns = self._read_low_memory(rows)
- else:
- # Don't care about memory usage
- columns = self._read_rows(rows, 1)
+ # Don't care about memory usage
+ columns = self._read_rows(rows, 1)
return columns
- # -> dict[int, "ArrayLike"]
- cdef _read_low_memory(self, rows):
+ def read_low_memory(self, rows: int | None)-> list[dict[int, "ArrayLike"]]:
+ """
+ rows=None --> read all rows
+ """
+ # Conserve intermediate space
+ # Caller is responsible for concatenating chunks,
+ # see c_parser_wrapper._concatenatve_chunks
cdef:
size_t rows_read = 0
list chunks = []
@@ -819,8 +813,7 @@ cdef class TextReader:
if len(chunks) == 0:
raise StopIteration
- # destructive to chunks
- return _concatenate_chunks(chunks)
+ return chunks
cdef _tokenize_rows(self, size_t nrows):
cdef:
@@ -1908,49 +1901,6 @@ cdef raise_parser_error(object base, parser_t *parser):
raise ParserError(message)
-# chunks: list[dict[int, "ArrayLike"]]
-# -> dict[int, "ArrayLike"]
-def _concatenate_chunks(list chunks) -> dict:
- cdef:
- list names = list(chunks[0].keys())
- object name
- list warning_columns = []
- object warning_names
- object common_type
-
- result = {}
- for name in names:
- arrs = [chunk.pop(name) for chunk in chunks]
- # Check each arr for consistent types.
- dtypes = {a.dtype for a in arrs}
- numpy_dtypes = {x for x in dtypes if not is_categorical_dtype(x)}
- if len(numpy_dtypes) > 1:
- common_type = np.find_common_type(numpy_dtypes, [])
- if common_type == object:
- warning_columns.append(str(name))
-
- dtype = dtypes.pop()
- if is_categorical_dtype(dtype):
- sort_categories = isinstance(dtype, str)
- result[name] = union_categoricals(arrs,
- sort_categories=sort_categories)
- else:
- if is_extension_array_dtype(dtype):
- array_type = dtype.construct_array_type()
- result[name] = array_type._concat_same_type(arrs)
- else:
- result[name] = np.concatenate(arrs)
-
- if warning_columns:
- warning_names = ','.join(warning_columns)
- warning_message = " ".join([
- f"Columns ({warning_names}) have mixed types."
- f"Specify dtype option on import or set low_memory=False."
- ])
- warnings.warn(warning_message, DtypeWarning, stacklevel=8)
- return result
-
-
# ----------------------------------------------------------------------
# NA values
def _compute_na_values():
diff --git a/pandas/io/parsers/c_parser_wrapper.py b/pandas/io/parsers/c_parser_wrapper.py
index fb110706c3fb4..fbf2a53207f75 100644
--- a/pandas/io/parsers/c_parser_wrapper.py
+++ b/pandas/io/parsers/c_parser_wrapper.py
@@ -1,5 +1,22 @@
+from __future__ import annotations
+
+import warnings
+
+import numpy as np
+
import pandas._libs.parsers as parsers
-from pandas._typing import FilePathOrBuffer
+from pandas._typing import (
+ ArrayLike,
+ FilePathOrBuffer,
+)
+from pandas.errors import DtypeWarning
+
+from pandas.core.dtypes.common import (
+ is_categorical_dtype,
+ pandas_dtype,
+)
+from pandas.core.dtypes.concat import union_categoricals
+from pandas.core.dtypes.dtypes import ExtensionDtype
from pandas.core.indexes.api import ensure_index_from_sequences
@@ -10,12 +27,16 @@
class CParserWrapper(ParserBase):
+ low_memory: bool
+
def __init__(self, src: FilePathOrBuffer, **kwds):
self.kwds = kwds
kwds = kwds.copy()
ParserBase.__init__(self, kwds)
+ self.low_memory = kwds.pop("low_memory", False)
+
# #2442
# error: Cannot determine type of 'index_col'
kwds["allow_leading_cols"] = (
@@ -31,6 +52,7 @@ def __init__(self, src: FilePathOrBuffer, **kwds):
for key in ("storage_options", "encoding", "memory_map", "compression"):
kwds.pop(key, None)
+ kwds["dtype"] = ensure_dtype_objs(kwds.get("dtype", None))
try:
self._reader = parsers.TextReader(self.handles.handle, **kwds)
except Exception:
@@ -187,7 +209,13 @@ def set_error_bad_lines(self, status):
def read(self, nrows=None):
try:
- data = self._reader.read(nrows)
+ if self.low_memory:
+ chunks = self._reader.read_low_memory(nrows)
+ # destructive to chunks
+ data = _concatenate_chunks(chunks)
+
+ else:
+ data = self._reader.read(nrows)
except StopIteration:
# error: Cannot determine type of '_first_chunk'
if self._first_chunk: # type: ignore[has-type]
@@ -294,7 +322,76 @@ def _get_index_names(self):
return names, idx_names
- def _maybe_parse_dates(self, values, index, try_parse_dates=True):
+ def _maybe_parse_dates(self, values, index: int, try_parse_dates=True):
if try_parse_dates and self._should_parse_dates(index):
values = self._date_conv(values)
return values
+
+
+def _concatenate_chunks(chunks: list[dict[int, ArrayLike]]) -> dict:
+ """
+ Concatenate chunks of data read with low_memory=True.
+
+ The tricky part is handling Categoricals, where different chunks
+ may have different inferred categories.
+ """
+ names = list(chunks[0].keys())
+ warning_columns = []
+
+ result = {}
+ for name in names:
+ arrs = [chunk.pop(name) for chunk in chunks]
+ # Check each arr for consistent types.
+ dtypes = {a.dtype for a in arrs}
+ # TODO: shouldn't we exclude all EA dtypes here?
+ numpy_dtypes = {x for x in dtypes if not is_categorical_dtype(x)}
+ if len(numpy_dtypes) > 1:
+ # error: Argument 1 to "find_common_type" has incompatible type
+ # "Set[Any]"; expected "Sequence[Union[dtype[Any], None, type,
+ # _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any,
+ # Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]]"
+ common_type = np.find_common_type(
+ numpy_dtypes, # type: ignore[arg-type]
+ [],
+ )
+ if common_type == object:
+ warning_columns.append(str(name))
+
+ dtype = dtypes.pop()
+ if is_categorical_dtype(dtype):
+ result[name] = union_categoricals(arrs, sort_categories=False)
+ else:
+ if isinstance(dtype, ExtensionDtype):
+ # TODO: concat_compat?
+ array_type = dtype.construct_array_type()
+ # error: Argument 1 to "_concat_same_type" of "ExtensionArray"
+ # has incompatible type "List[Union[ExtensionArray, ndarray]]";
+ # expected "Sequence[ExtensionArray]"
+ result[name] = array_type._concat_same_type(
+ arrs # type: ignore[arg-type]
+ )
+ else:
+ result[name] = np.concatenate(arrs)
+
+ if warning_columns:
+ warning_names = ",".join(warning_columns)
+ warning_message = " ".join(
+ [
+ f"Columns ({warning_names}) have mixed types."
+ f"Specify dtype option on import or set low_memory=False."
+ ]
+ )
+ warnings.warn(warning_message, DtypeWarning, stacklevel=8)
+ return result
+
+
+def ensure_dtype_objs(dtype):
+ """
+ Ensure we have either None, a dtype object, or a dictionary mapping to
+ dtype objects.
+ """
+ if isinstance(dtype, dict):
+ dtype = {k: pandas_dtype(dtype[k]) for k in dtype}
+ elif dtype is not None:
+ dtype = pandas_dtype(dtype)
+ return dtype
diff --git a/pandas/tests/io/parser/test_textreader.py b/pandas/tests/io/parser/test_textreader.py
index 104cf56419bfd..7f84c5e378d16 100644
--- a/pandas/tests/io/parser/test_textreader.py
+++ b/pandas/tests/io/parser/test_textreader.py
@@ -21,6 +21,7 @@
TextFileReader,
read_csv,
)
+from pandas.io.parsers.c_parser_wrapper import ensure_dtype_objs
class TestTextReader:
@@ -206,6 +207,8 @@ def test_numpy_string_dtype(self):
aaaaa,5"""
def _make_reader(**kwds):
+ if "dtype" in kwds:
+ kwds["dtype"] = ensure_dtype_objs(kwds["dtype"])
return TextReader(StringIO(data), delimiter=",", header=None, **kwds)
reader = _make_reader(dtype="S5,i4")
@@ -233,6 +236,8 @@ def test_pass_dtype(self):
4,d"""
def _make_reader(**kwds):
+ if "dtype" in kwds:
+ kwds["dtype"] = ensure_dtype_objs(kwds["dtype"])
return TextReader(StringIO(data), delimiter=",", **kwds)
reader = _make_reader(dtype={"one": "u1", 1: "S1"})
| There's no real perf bump to calling union_categoricals inside cython, better to do it in the python code where we can e.g. get the benefit of mypy. Plus gets us closer to dependency structure goals.
| https://api.github.com/repos/pandas-dev/pandas/pulls/40964 | 2021-04-15T17:04:55Z | 2021-04-28T14:53:58Z | 2021-04-28T14:53:58Z | 2021-04-28T15:54:28Z |
[ArrowStringArray] TST: more parameterised testing - part 4 | diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py
index d23c44733949a..bebe6948cff9c 100644
--- a/pandas/tests/series/methods/test_astype.py
+++ b/pandas/tests/series/methods/test_astype.py
@@ -10,6 +10,7 @@
import pytest
from pandas._libs.tslibs import iNaT
+import pandas.util._test_decorators as td
from pandas import (
NA,
@@ -246,25 +247,34 @@ def test_td64_series_astype_object(self):
assert result.dtype == np.object_
@pytest.mark.parametrize(
- "values",
+ "data, dtype",
[
- Series(["x", "y", "z"], dtype="string"),
- Series(["x", "y", "z"], dtype="category"),
- Series(3 * [Timestamp("2020-01-01", tz="UTC")]),
- Series(3 * [Interval(0, 1)]),
+ (["x", "y", "z"], "string"),
+ pytest.param(
+ ["x", "y", "z"],
+ "arrow_string",
+ marks=td.skip_if_no("pyarrow", min_version="1.0.0"),
+ ),
+ (["x", "y", "z"], "category"),
+ (3 * [Timestamp("2020-01-01", tz="UTC")], None),
+ (3 * [Interval(0, 1)], None),
],
)
@pytest.mark.parametrize("errors", ["raise", "ignore"])
- def test_astype_ignores_errors_for_extension_dtypes(self, values, errors):
+ def test_astype_ignores_errors_for_extension_dtypes(self, data, dtype, errors):
# https://github.com/pandas-dev/pandas/issues/35471
+
+ from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401
+
+ ser = Series(data, dtype=dtype)
if errors == "ignore":
- expected = values
- result = values.astype(float, errors="ignore")
+ expected = ser
+ result = ser.astype(float, errors="ignore")
tm.assert_series_equal(result, expected)
else:
msg = "(Cannot cast)|(could not convert)"
with pytest.raises((ValueError, TypeError), match=msg):
- values.astype(float, errors=errors)
+ ser.astype(float, errors=errors)
@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64])
def test_astype_from_float_to_str(self, dtype):
diff --git a/pandas/tests/series/methods/test_update.py b/pandas/tests/series/methods/test_update.py
index 4f585a6ea029a..9a64877cb92ff 100644
--- a/pandas/tests/series/methods/test_update.py
+++ b/pandas/tests/series/methods/test_update.py
@@ -1,6 +1,8 @@
import numpy as np
import pytest
+import pandas.util._test_decorators as td
+
from pandas import (
CategoricalDtype,
DataFrame,
@@ -9,6 +11,7 @@
Timestamp,
)
import pandas._testing as tm
+from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401
class TestUpdate:
@@ -82,37 +85,38 @@ def test_update_from_non_series(self, series, other, expected):
tm.assert_series_equal(series, expected)
@pytest.mark.parametrize(
- "result, target, expected",
+ "data, other, expected, dtype",
[
- (
- Series(["a", None], dtype="string"),
- Series([None, "b"], dtype="string"),
- Series(["a", "b"], dtype="string"),
- ),
- (
- Series([1, None], dtype="Int64"),
- Series([None, 2], dtype="Int64"),
- Series([1, 2], dtype="Int64"),
+ (["a", None], [None, "b"], ["a", "b"], "string"),
+ pytest.param(
+ ["a", None],
+ [None, "b"],
+ ["a", "b"],
+ "arrow_string",
+ marks=td.skip_if_no("pyarrow", min_version="1.0.0"),
),
+ ([1, None], [None, 2], [1, 2], "Int64"),
+ ([True, None], [None, False], [True, False], "boolean"),
(
- Series([True, None], dtype="boolean"),
- Series([None, False], dtype="boolean"),
- Series([True, False], dtype="boolean"),
+ ["a", None],
+ [None, "b"],
+ ["a", "b"],
+ CategoricalDtype(categories=["a", "b"]),
),
(
- Series(["a", None], dtype=CategoricalDtype(categories=["a", "b"])),
- Series([None, "b"], dtype=CategoricalDtype(categories=["a", "b"])),
- Series(["a", "b"], dtype=CategoricalDtype(categories=["a", "b"])),
- ),
- (
- Series([Timestamp(year=2020, month=1, day=1, tz="Europe/London"), NaT]),
- Series([NaT, Timestamp(year=2020, month=1, day=1, tz="Europe/London")]),
- Series([Timestamp(year=2020, month=1, day=1, tz="Europe/London")] * 2),
+ [Timestamp(year=2020, month=1, day=1, tz="Europe/London"), NaT],
+ [NaT, Timestamp(year=2020, month=1, day=1, tz="Europe/London")],
+ [Timestamp(year=2020, month=1, day=1, tz="Europe/London")] * 2,
+ "datetime64[ns, Europe/London]",
),
],
)
- def test_update_extension_array_series(self, result, target, expected):
- result.update(target)
+ def test_update_extension_array_series(self, data, other, expected, dtype):
+ result = Series(data, dtype=dtype)
+ other = Series(other, dtype=dtype)
+ expected = Series(expected, dtype=dtype)
+
+ result.update(other)
tm.assert_series_equal(result, expected)
def test_update_with_categorical_type(self):
diff --git a/pandas/tests/strings/test_find_replace.py b/pandas/tests/strings/test_find_replace.py
index ef27d582b4e0f..ab95b2071ae10 100644
--- a/pandas/tests/strings/test_find_replace.py
+++ b/pandas/tests/strings/test_find_replace.py
@@ -364,26 +364,28 @@ def test_match():
def test_fullmatch():
# GH 32806
- values = Series(["fooBAD__barBAD", "BAD_BADleroybrown", np.nan, "foo"])
- result = values.str.fullmatch(".*BAD[_]+.*BAD")
- exp = Series([True, False, np.nan, False])
- tm.assert_series_equal(result, exp)
-
- # Make sure that the new string arrays work
- string_values = Series(
- ["fooBAD__barBAD", "BAD_BADleroybrown", np.nan, "foo"], dtype="string"
- )
- result = string_values.str.fullmatch(".*BAD[_]+.*BAD")
- # Result is nullable boolean with StringDtype
- string_exp = Series([True, False, np.nan, False], dtype="boolean")
- tm.assert_series_equal(result, string_exp)
+ ser = Series(["fooBAD__barBAD", "BAD_BADleroybrown", np.nan, "foo"])
+ result = ser.str.fullmatch(".*BAD[_]+.*BAD")
+ expected = Series([True, False, np.nan, False])
+ tm.assert_series_equal(result, expected)
- values = Series(["ab", "AB", "abc", "ABC"])
- result = values.str.fullmatch("ab", case=False)
+ ser = Series(["ab", "AB", "abc", "ABC"])
+ result = ser.str.fullmatch("ab", case=False)
expected = Series([True, True, False, False])
tm.assert_series_equal(result, expected)
+def test_fullmatch_nullable_string_dtype(nullable_string_dtype):
+ ser = Series(
+ ["fooBAD__barBAD", "BAD_BADleroybrown", None, "foo"],
+ dtype=nullable_string_dtype,
+ )
+ result = ser.str.fullmatch(".*BAD[_]+.*BAD")
+ # Result is nullable boolean
+ expected = Series([True, False, np.nan, False], dtype="boolean")
+ tm.assert_series_equal(result, expected)
+
+
def test_findall():
values = Series(["fooBAD__barBAD", np.nan, "foo", "BAD"])
diff --git a/pandas/tests/strings/test_strings.py b/pandas/tests/strings/test_strings.py
index 95ac237597bc4..a809446f0bc06 100644
--- a/pandas/tests/strings/test_strings.py
+++ b/pandas/tests/strings/test_strings.py
@@ -136,17 +136,23 @@ def test_repeat():
tm.assert_series_equal(rs, xp)
-def test_repeat_with_null():
+def test_repeat_with_null(nullable_string_dtype, request):
# GH: 31632
- values = Series(["a", None], dtype="string")
- result = values.str.repeat([3, 4])
- exp = Series(["aaa", None], dtype="string")
- tm.assert_series_equal(result, exp)
- values = Series(["a", "b"], dtype="string")
- result = values.str.repeat([3, None])
- exp = Series(["aaa", None], dtype="string")
- tm.assert_series_equal(result, exp)
+ if nullable_string_dtype == "arrow_string":
+ reason = 'Attribute "dtype" are different'
+ mark = pytest.mark.xfail(reason=reason)
+ request.node.add_marker(mark)
+
+ ser = Series(["a", None], dtype=nullable_string_dtype)
+ result = ser.str.repeat([3, 4])
+ expected = Series(["aaa", None], dtype=nullable_string_dtype)
+ tm.assert_series_equal(result, expected)
+
+ ser = Series(["a", "b"], dtype=nullable_string_dtype)
+ result = ser.str.repeat([3, None])
+ expected = Series(["aaa", None], dtype=nullable_string_dtype)
+ tm.assert_series_equal(result, expected)
def test_empty_str_methods():
| still outstanding:
`test_astype_string` in `pandas/tests/extension/base/casting.py` requires separate PR with fix
`test_convert_dtypes` in `pandas/tests/frame/methods/test_convert_dtypes.py` requires discussion https://github.com/pandas-dev/pandas/pull/40747#issuecomment-812508672... probably need to include in (or follow on to #39908) to at least use the global default
`test_to_html_formatters` in `pandas/tests/io/formats/test_to_html.py`
paramaterisation where pd.StringArray is used directly... could potentially combine with #40962 and expose ArrowStringArray publicly
the changes here to `test_repeat_with_null` need a separate PR to fix so could be excluded here. | https://api.github.com/repos/pandas-dev/pandas/pulls/40963 | 2021-04-15T16:56:11Z | 2021-04-16T01:03:57Z | 2021-04-16T01:03:57Z | 2021-04-16T07:03:33Z |
[ArrowStringArray] CLN: imports | diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py
index fd47597b2191f..52bdcd03d3b49 100644
--- a/pandas/core/arrays/string_arrow.py
+++ b/pandas/core/arrays/string_arrow.py
@@ -25,19 +25,17 @@
from pandas.core.dtypes.base import ExtensionDtype
from pandas.core.dtypes.common import (
- is_object_dtype,
- is_string_dtype,
-)
-from pandas.core.dtypes.dtypes import register_extension_dtype
-from pandas.core.dtypes.missing import isna
-
-from pandas.api.types import (
is_array_like,
is_bool_dtype,
is_integer,
is_integer_dtype,
+ is_object_dtype,
is_scalar,
+ is_string_dtype,
)
+from pandas.core.dtypes.dtypes import register_extension_dtype
+from pandas.core.dtypes.missing import isna
+
from pandas.core import missing
from pandas.core.arraylike import OpsMixin
from pandas.core.arrays.base import ExtensionArray
| https://api.github.com/repos/pandas-dev/pandas/pulls/40961 | 2021-04-15T10:23:57Z | 2021-04-15T17:27:59Z | 2021-04-15T17:27:58Z | 2021-04-16T07:12:17Z | |
[ArrowStringArray] CLN: move and rename test_string_methods | diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py
index 749f3d0aee8a5..2fec1925149ad 100644
--- a/pandas/tests/arrays/string_/test_string.py
+++ b/pandas/tests/arrays/string_/test_string.py
@@ -1,4 +1,7 @@
-import operator
+"""
+This module tests the functionality of StringArray and ArrowStringArray.
+Tests for the str accessors are in pandas/tests/strings/test_string_array.py
+"""
import numpy as np
import pytest
@@ -88,23 +91,6 @@ def test_setitem_with_scalar_string(dtype):
tm.assert_extension_array_equal(arr, expected)
-@pytest.mark.parametrize(
- "input, method",
- [
- (["a", "b", "c"], operator.methodcaller("capitalize")),
- (["a b", "a bc. de"], operator.methodcaller("capitalize")),
- ],
-)
-def test_string_methods(input, method, dtype):
- a = pd.Series(input, dtype=dtype)
- b = pd.Series(input, dtype="object")
- result = method(a.str)
- expected = method(b.str)
-
- assert result.dtype.name == dtype
- tm.assert_series_equal(result.astype(object), expected)
-
-
def test_astype_roundtrip(dtype, request):
if dtype == "arrow_string":
reason = "ValueError: Could not convert object to NumPy datetime"
diff --git a/pandas/tests/strings/test_string_array.py b/pandas/tests/strings/test_string_array.py
index 23c9b14c5a36a..02ccb3a930557 100644
--- a/pandas/tests/strings/test_string_array.py
+++ b/pandas/tests/strings/test_string_array.py
@@ -1,3 +1,5 @@
+import operator
+
import numpy as np
import pytest
@@ -117,3 +119,20 @@ def test_str_get_stringarray_multiple_nans(nullable_string_dtype):
result = s.str.get(2)
expected = Series(pd.array([pd.NA, pd.NA, pd.NA, "c"], dtype=nullable_string_dtype))
tm.assert_series_equal(result, expected)
+
+
+@pytest.mark.parametrize(
+ "input, method",
+ [
+ (["a", "b", "c"], operator.methodcaller("capitalize")),
+ (["a b", "a bc. de"], operator.methodcaller("capitalize")),
+ ],
+)
+def test_capitalize(input, method, nullable_string_dtype):
+ a = Series(input, dtype=nullable_string_dtype)
+ b = Series(input, dtype="object")
+ result = method(a.str)
+ expected = method(b.str)
+
+ assert result.dtype.name == nullable_string_dtype
+ tm.assert_series_equal(result.astype(object), expected)
| follow-up to #40708
in #40708 the str accessor was enabled and tests changed in `pandas/tests/arrays/string_/test_string.py` and `pandas/tests/strings/test_string_array.py`
This PR colocates the str accessor test in `pandas/tests/arrays/string_/test_string.py` with those in `pandas/tests/strings/test_string_array.py` and renames it `test_string_methods` -> `test_capitalize` | https://api.github.com/repos/pandas-dev/pandas/pulls/40960 | 2021-04-15T09:11:13Z | 2021-04-15T17:49:44Z | 2021-04-15T17:49:44Z | 2021-04-16T07:11:28Z |
Add 'virt' and 'group' settings for arm64-graviton2 | diff --git a/.travis.yml b/.travis.yml
index 0098e3872bec7..540cd026a43d5 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -36,6 +36,8 @@ matrix:
include:
- arch: arm64-graviton2
+ virt: lxd
+ group: edge
env:
- JOB="3.7, arm64" PYTEST_WORKERS="auto" ENV_FILE="ci/deps/travis-37-arm64.yaml" PATTERN="(not slow and not network and not clipboard and not arm_slow)"
| https://github.com/pandas-dev/pandas/pull/40868 tried to change from `arm64` to `arm64-graviton2` but actually changed it to `amd64` because of the missing `virt` and `group` settings, as explained at https://blog.travis-ci.com/2020-09-11-arm-on-aws, section "Quick tips" | https://api.github.com/repos/pandas-dev/pandas/pulls/40959 | 2021-04-15T07:33:27Z | 2021-04-15T17:27:37Z | 2021-04-15T17:27:37Z | 2021-04-16T05:54:39Z |
CLN: refactor tests outside of class setup in `style/test_matplotlib.py` | diff --git a/pandas/tests/io/formats/style/test_matplotlib.py b/pandas/tests/io/formats/style/test_matplotlib.py
index f0158711664ce..496344c59ec04 100644
--- a/pandas/tests/io/formats/style/test_matplotlib.py
+++ b/pandas/tests/io/formats/style/test_matplotlib.py
@@ -10,218 +10,236 @@
pytest.importorskip("matplotlib")
pytest.importorskip("jinja2")
+from pandas.io.formats.style import Styler
-class TestStylerMatplotlibDep:
- def test_background_gradient(self):
- df = DataFrame([[1, 2], [2, 4]], columns=["A", "B"])
-
- for c_map in [None, "YlOrRd"]:
- result = df.style.background_gradient(cmap=c_map)._compute().ctx
- assert all("#" in x[0][1] for x in result.values())
- assert result[(0, 0)] == result[(0, 1)]
- assert result[(1, 0)] == result[(1, 1)]
-
- result = df.style.background_gradient(subset=IndexSlice[1, "A"])._compute().ctx
-
- assert result[(1, 0)] == [("background-color", "#fff7fb"), ("color", "#000000")]
-
- @pytest.mark.parametrize(
- "cmap, expected",
- [
- (
- "PuBu",
- {
- (4, 5): [("background-color", "#86b0d3"), ("color", "#000000")],
- (4, 6): [("background-color", "#83afd3"), ("color", "#f1f1f1")],
- },
- ),
- (
- "YlOrRd",
- {
- (4, 8): [("background-color", "#fd913e"), ("color", "#000000")],
- (4, 9): [("background-color", "#fd8f3d"), ("color", "#f1f1f1")],
- },
- ),
- (
- None,
- {
- (7, 0): [("background-color", "#48c16e"), ("color", "#f1f1f1")],
- (7, 1): [("background-color", "#4cc26c"), ("color", "#000000")],
- },
- ),
- ],
- )
- def test_text_color_threshold(self, cmap, expected):
- df = DataFrame(np.arange(100).reshape(10, 10))
- result = df.style.background_gradient(cmap=cmap, axis=None)._compute().ctx
- for k in expected.keys():
- assert result[k] == expected[k]
-
- def test_background_gradient_axis(self):
- df = DataFrame([[1, 2], [2, 4]], columns=["A", "B"])
-
- low = [("background-color", "#f7fbff"), ("color", "#000000")]
- high = [("background-color", "#08306b"), ("color", "#f1f1f1")]
- mid = [("background-color", "#abd0e6"), ("color", "#000000")]
- result = df.style.background_gradient(cmap="Blues", axis=0)._compute().ctx
- assert result[(0, 0)] == low
- assert result[(0, 1)] == low
- assert result[(1, 0)] == high
- assert result[(1, 1)] == high
-
- result = df.style.background_gradient(cmap="Blues", axis=1)._compute().ctx
- assert result[(0, 0)] == low
- assert result[(0, 1)] == high
- assert result[(1, 0)] == low
- assert result[(1, 1)] == high
-
- result = df.style.background_gradient(cmap="Blues", axis=None)._compute().ctx
- assert result[(0, 0)] == low
- assert result[(0, 1)] == mid
- assert result[(1, 0)] == mid
- assert result[(1, 1)] == high
-
- def test_background_gradient_vmin_vmax(self):
- # GH 12145
- df = DataFrame(range(5))
- ctx = df.style.background_gradient(vmin=1, vmax=3)._compute().ctx
- assert ctx[(0, 0)] == ctx[(1, 0)]
- assert ctx[(4, 0)] == ctx[(3, 0)]
-
- def test_background_gradient_int64(self):
- # GH 28869
- df1 = Series(range(3)).to_frame()
- df2 = Series(range(3), dtype="Int64").to_frame()
- ctx1 = df1.style.background_gradient()._compute().ctx
- ctx2 = df2.style.background_gradient()._compute().ctx
- assert ctx2[(0, 0)] == ctx1[(0, 0)]
- assert ctx2[(1, 0)] == ctx1[(1, 0)]
- assert ctx2[(2, 0)] == ctx1[(2, 0)]
-
- @pytest.mark.parametrize(
- "axis, gmap, expected",
- [
- (
- 0,
- [1, 2],
- {
- (0, 0): [("background-color", "#fff7fb"), ("color", "#000000")],
- (1, 0): [("background-color", "#023858"), ("color", "#f1f1f1")],
- (0, 1): [("background-color", "#fff7fb"), ("color", "#000000")],
- (1, 1): [("background-color", "#023858"), ("color", "#f1f1f1")],
- },
- ),
- (
- 1,
- [1, 2],
- {
- (0, 0): [("background-color", "#fff7fb"), ("color", "#000000")],
- (1, 0): [("background-color", "#fff7fb"), ("color", "#000000")],
- (0, 1): [("background-color", "#023858"), ("color", "#f1f1f1")],
- (1, 1): [("background-color", "#023858"), ("color", "#f1f1f1")],
- },
- ),
- (
- None,
- np.array([[2, 1], [1, 2]]),
- {
- (0, 0): [("background-color", "#023858"), ("color", "#f1f1f1")],
- (1, 0): [("background-color", "#fff7fb"), ("color", "#000000")],
- (0, 1): [("background-color", "#fff7fb"), ("color", "#000000")],
- (1, 1): [("background-color", "#023858"), ("color", "#f1f1f1")],
- },
- ),
- ],
- )
- def test_background_gradient_gmap_array(self, axis, gmap, expected):
- # tests when gmap is given as a sequence and converted to ndarray
- df = DataFrame([[0, 0], [0, 0]])
- result = df.style.background_gradient(axis=axis, gmap=gmap)._compute().ctx
- assert result == expected
-
- @pytest.mark.parametrize(
- "gmap, axis", [([1, 2, 3], 0), ([1, 2], 1), (np.array([[1, 2], [1, 2]]), None)]
- )
- def test_background_gradient_gmap_array_raises(self, gmap, axis):
- # test when gmap as converted ndarray is bad shape
- df = DataFrame([[0, 0, 0], [0, 0, 0]])
- msg = "supplied 'gmap' is not correct shape"
- with pytest.raises(ValueError, match=msg):
- df.style.background_gradient(gmap=gmap, axis=axis)._compute()
-
- @pytest.mark.parametrize(
- "gmap",
- [
- DataFrame( # reverse the columns
- [[2, 1], [1, 2]], columns=["B", "A"], index=["X", "Y"]
- ),
- DataFrame( # reverse the index
- [[2, 1], [1, 2]], columns=["A", "B"], index=["Y", "X"]
- ),
- DataFrame( # reverse the index and columns
- [[1, 2], [2, 1]], columns=["B", "A"], index=["Y", "X"]
- ),
- DataFrame( # add unnecessary columns
- [[1, 2, 3], [2, 1, 3]], columns=["A", "B", "C"], index=["X", "Y"]
- ),
- DataFrame( # add unnecessary index
- [[1, 2], [2, 1], [3, 3]], columns=["A", "B"], index=["X", "Y", "Z"]
- ),
- ],
- )
- @pytest.mark.parametrize(
- "subset, exp_gmap", # exp_gmap is underlying map DataFrame should conform to
- [
- (None, [[1, 2], [2, 1]]),
- (["A"], [[1], [2]]), # slice only column "A" in data and gmap
- (["B", "A"], [[2, 1], [1, 2]]), # reverse the columns in data
- (IndexSlice["X", :], [[1, 2]]), # slice only index "X" in data and gmap
- (IndexSlice[["Y", "X"], :], [[2, 1], [1, 2]]), # reverse the index in data
- ],
- )
- def test_background_gradient_gmap_dataframe_align(self, gmap, subset, exp_gmap):
- # test gmap given as DataFrame that it aligns to the the data including subset
- df = DataFrame([[0, 0], [0, 0]], columns=["A", "B"], index=["X", "Y"])
-
- expected = df.style.background_gradient(axis=None, gmap=exp_gmap, subset=subset)
- result = df.style.background_gradient(axis=None, gmap=gmap, subset=subset)
- assert expected._compute().ctx == result._compute().ctx
-
- @pytest.mark.parametrize(
- "gmap, axis, exp_gmap",
- [
- (Series([2, 1], index=["Y", "X"]), 0, [[1, 1], [2, 2]]), # revrse the index
- (Series([2, 1], index=["B", "A"]), 1, [[1, 2], [1, 2]]), # revrse the cols
- (Series([1, 2, 3], index=["X", "Y", "Z"]), 0, [[1, 1], [2, 2]]), # add idx
- (Series([1, 2, 3], index=["A", "B", "C"]), 1, [[1, 2], [1, 2]]), # add col
- ],
- )
- def test_background_gradient_gmap_series_align(self, gmap, axis, exp_gmap):
- # test gmap given as Series that it aligns to the the data including subset
- df = DataFrame([[0, 0], [0, 0]], columns=["A", "B"], index=["X", "Y"])
-
- expected = df.style.background_gradient(axis=None, gmap=exp_gmap)._compute()
- result = df.style.background_gradient(axis=axis, gmap=gmap)._compute()
- assert expected.ctx == result.ctx
-
- @pytest.mark.parametrize(
- "gmap, axis",
- [
- (DataFrame([[1, 2], [2, 1]], columns=["A", "B"], index=["X", "Y"]), 1),
- (DataFrame([[1, 2], [2, 1]], columns=["A", "B"], index=["X", "Y"]), 0),
- ],
- )
- def test_background_gradient_gmap_wrong_dataframe(self, gmap, axis):
- # test giving a gmap in DataFrame but with wrong axis
- df = DataFrame([[0, 0], [0, 0]], columns=["A", "B"], index=["X", "Y"])
- msg = "'gmap' is a DataFrame but underlying data for operations is a Series"
- with pytest.raises(ValueError, match=msg):
- df.style.background_gradient(gmap=gmap, axis=axis)._compute()
-
- def test_background_gradient_gmap_wrong_series(self):
- # test giving a gmap in Series form but with wrong axis
- df = DataFrame([[0, 0], [0, 0]], columns=["A", "B"], index=["X", "Y"])
- msg = "'gmap' is a Series but underlying data for operations is a DataFrame"
- gmap = Series([1, 2], index=["X", "Y"])
- with pytest.raises(ValueError, match=msg):
- df.style.background_gradient(gmap=gmap, axis=None)._compute()
+
+@pytest.fixture
+def df():
+ return DataFrame([[1, 2], [2, 4]], columns=["A", "B"])
+
+
+@pytest.fixture
+def styler(df):
+ return Styler(df, uuid_len=0)
+
+
+@pytest.fixture
+def df_blank():
+ return DataFrame([[0, 0], [0, 0]], columns=["A", "B"], index=["X", "Y"])
+
+
+@pytest.fixture
+def styler_blank(df_blank):
+ return Styler(df_blank, uuid_len=0)
+
+
+def test_background_gradient(styler):
+ for c_map in [None, "YlOrRd"]:
+ result = styler.background_gradient(cmap=c_map)._compute().ctx
+ assert all("#" in x[0][1] for x in result.values())
+ assert result[(0, 0)] == result[(0, 1)]
+ assert result[(1, 0)] == result[(1, 1)]
+
+
+def test_background_gradient_color(styler):
+ result = styler.background_gradient(subset=IndexSlice[1, "A"])._compute().ctx
+ assert result[(1, 0)] == [("background-color", "#fff7fb"), ("color", "#000000")]
+
+
+@pytest.mark.parametrize(
+ "axis, expected",
+ [
+ (0, ["low", "low", "high", "high"]),
+ (1, ["low", "high", "low", "high"]),
+ (None, ["low", "mid", "mid", "high"]),
+ ],
+)
+def test_background_gradient_axis(styler, axis, expected):
+ bg_colors = {
+ "low": [("background-color", "#f7fbff"), ("color", "#000000")],
+ "mid": [("background-color", "#abd0e6"), ("color", "#000000")],
+ "high": [("background-color", "#08306b"), ("color", "#f1f1f1")],
+ }
+ result = styler.background_gradient(cmap="Blues", axis=axis)._compute().ctx
+ for i, cell in enumerate([(0, 0), (0, 1), (1, 0), (1, 1)]):
+ assert result[cell] == bg_colors[expected[i]]
+
+
+@pytest.mark.parametrize(
+ "cmap, expected",
+ [
+ (
+ "PuBu",
+ {
+ (4, 5): [("background-color", "#86b0d3"), ("color", "#000000")],
+ (4, 6): [("background-color", "#83afd3"), ("color", "#f1f1f1")],
+ },
+ ),
+ (
+ "YlOrRd",
+ {
+ (4, 8): [("background-color", "#fd913e"), ("color", "#000000")],
+ (4, 9): [("background-color", "#fd8f3d"), ("color", "#f1f1f1")],
+ },
+ ),
+ (
+ None,
+ {
+ (7, 0): [("background-color", "#48c16e"), ("color", "#f1f1f1")],
+ (7, 1): [("background-color", "#4cc26c"), ("color", "#000000")],
+ },
+ ),
+ ],
+)
+def test_text_color_threshold(cmap, expected):
+ # GH 39888
+ df = DataFrame(np.arange(100).reshape(10, 10))
+ result = df.style.background_gradient(cmap=cmap, axis=None)._compute().ctx
+ for k in expected.keys():
+ assert result[k] == expected[k]
+
+
+def test_background_gradient_vmin_vmax():
+ # GH 12145
+ df = DataFrame(range(5))
+ ctx = df.style.background_gradient(vmin=1, vmax=3)._compute().ctx
+ assert ctx[(0, 0)] == ctx[(1, 0)]
+ assert ctx[(4, 0)] == ctx[(3, 0)]
+
+
+def test_background_gradient_int64():
+ # GH 28869
+ df1 = Series(range(3)).to_frame()
+ df2 = Series(range(3), dtype="Int64").to_frame()
+ ctx1 = df1.style.background_gradient()._compute().ctx
+ ctx2 = df2.style.background_gradient()._compute().ctx
+ assert ctx2[(0, 0)] == ctx1[(0, 0)]
+ assert ctx2[(1, 0)] == ctx1[(1, 0)]
+ assert ctx2[(2, 0)] == ctx1[(2, 0)]
+
+
+@pytest.mark.parametrize(
+ "axis, gmap, expected",
+ [
+ (
+ 0,
+ [1, 2],
+ {
+ (0, 0): [("background-color", "#fff7fb"), ("color", "#000000")],
+ (1, 0): [("background-color", "#023858"), ("color", "#f1f1f1")],
+ (0, 1): [("background-color", "#fff7fb"), ("color", "#000000")],
+ (1, 1): [("background-color", "#023858"), ("color", "#f1f1f1")],
+ },
+ ),
+ (
+ 1,
+ [1, 2],
+ {
+ (0, 0): [("background-color", "#fff7fb"), ("color", "#000000")],
+ (1, 0): [("background-color", "#fff7fb"), ("color", "#000000")],
+ (0, 1): [("background-color", "#023858"), ("color", "#f1f1f1")],
+ (1, 1): [("background-color", "#023858"), ("color", "#f1f1f1")],
+ },
+ ),
+ (
+ None,
+ np.array([[2, 1], [1, 2]]),
+ {
+ (0, 0): [("background-color", "#023858"), ("color", "#f1f1f1")],
+ (1, 0): [("background-color", "#fff7fb"), ("color", "#000000")],
+ (0, 1): [("background-color", "#fff7fb"), ("color", "#000000")],
+ (1, 1): [("background-color", "#023858"), ("color", "#f1f1f1")],
+ },
+ ),
+ ],
+)
+def test_background_gradient_gmap_array(styler_blank, axis, gmap, expected):
+ # tests when gmap is given as a sequence and converted to ndarray
+ result = styler_blank.background_gradient(axis=axis, gmap=gmap)._compute().ctx
+ assert result == expected
+
+
+@pytest.mark.parametrize(
+ "gmap, axis", [([1, 2, 3], 0), ([1, 2], 1), (np.array([[1, 2], [1, 2]]), None)]
+)
+def test_background_gradient_gmap_array_raises(gmap, axis):
+ # test when gmap as converted ndarray is bad shape
+ df = DataFrame([[0, 0, 0], [0, 0, 0]])
+ msg = "supplied 'gmap' is not correct shape"
+ with pytest.raises(ValueError, match=msg):
+ df.style.background_gradient(gmap=gmap, axis=axis)._compute()
+
+
+@pytest.mark.parametrize(
+ "gmap",
+ [
+ DataFrame( # reverse the columns
+ [[2, 1], [1, 2]], columns=["B", "A"], index=["X", "Y"]
+ ),
+ DataFrame( # reverse the index
+ [[2, 1], [1, 2]], columns=["A", "B"], index=["Y", "X"]
+ ),
+ DataFrame( # reverse the index and columns
+ [[1, 2], [2, 1]], columns=["B", "A"], index=["Y", "X"]
+ ),
+ DataFrame( # add unnecessary columns
+ [[1, 2, 3], [2, 1, 3]], columns=["A", "B", "C"], index=["X", "Y"]
+ ),
+ DataFrame( # add unnecessary index
+ [[1, 2], [2, 1], [3, 3]], columns=["A", "B"], index=["X", "Y", "Z"]
+ ),
+ ],
+)
+@pytest.mark.parametrize(
+ "subset, exp_gmap", # exp_gmap is underlying map DataFrame should conform to
+ [
+ (None, [[1, 2], [2, 1]]),
+ (["A"], [[1], [2]]), # slice only column "A" in data and gmap
+ (["B", "A"], [[2, 1], [1, 2]]), # reverse the columns in data
+ (IndexSlice["X", :], [[1, 2]]), # slice only index "X" in data and gmap
+ (IndexSlice[["Y", "X"], :], [[2, 1], [1, 2]]), # reverse the index in data
+ ],
+)
+def test_background_gradient_gmap_dataframe_align(styler_blank, gmap, subset, exp_gmap):
+ # test gmap given as DataFrame that it aligns to the the data including subset
+ expected = styler_blank.background_gradient(axis=None, gmap=exp_gmap, subset=subset)
+ result = styler_blank.background_gradient(axis=None, gmap=gmap, subset=subset)
+ assert expected._compute().ctx == result._compute().ctx
+
+
+@pytest.mark.parametrize(
+ "gmap, axis, exp_gmap",
+ [
+ (Series([2, 1], index=["Y", "X"]), 0, [[1, 1], [2, 2]]), # revrse the index
+ (Series([2, 1], index=["B", "A"]), 1, [[1, 2], [1, 2]]), # revrse the cols
+ (Series([1, 2, 3], index=["X", "Y", "Z"]), 0, [[1, 1], [2, 2]]), # add idx
+ (Series([1, 2, 3], index=["A", "B", "C"]), 1, [[1, 2], [1, 2]]), # add col
+ ],
+)
+def test_background_gradient_gmap_series_align(styler_blank, gmap, axis, exp_gmap):
+ # test gmap given as Series that it aligns to the the data including subset
+ expected = styler_blank.background_gradient(axis=None, gmap=exp_gmap)._compute()
+ result = styler_blank.background_gradient(axis=axis, gmap=gmap)._compute()
+ assert expected.ctx == result.ctx
+
+
+@pytest.mark.parametrize(
+ "gmap, axis",
+ [
+ (DataFrame([[1, 2], [2, 1]], columns=["A", "B"], index=["X", "Y"]), 1),
+ (DataFrame([[1, 2], [2, 1]], columns=["A", "B"], index=["X", "Y"]), 0),
+ ],
+)
+def test_background_gradient_gmap_wrong_dataframe(styler_blank, gmap, axis):
+ # test giving a gmap in DataFrame but with wrong axis
+ msg = "'gmap' is a DataFrame but underlying data for operations is a Series"
+ with pytest.raises(ValueError, match=msg):
+ styler_blank.background_gradient(gmap=gmap, axis=axis)._compute()
+
+
+def test_background_gradient_gmap_wrong_series(styler_blank):
+ # test giving a gmap in Series form but with wrong axis
+ msg = "'gmap' is a Series but underlying data for operations is a DataFrame"
+ gmap = Series([1, 2], index=["X", "Y"])
+ with pytest.raises(ValueError, match=msg):
+ styler_blank.background_gradient(gmap=gmap, axis=None)._compute()
| This is a refactor to remove the pytest class setup structure, reverting to class-less fixtures.
It also parametrises some of the tests.
No test is altered or removed.
```
def test_background_gradient(styler):
def test_background_gradient_color(styler):
def test_background_gradient_axis(styler, axis, expected):
def test_text_color_threshold(cmap, expected):
def test_background_gradient_vmin_vmax():
def test_background_gradient_int64():
def test_background_gradient_gmap_array(styler_blank, axis, gmap, expected):
def test_background_gradient_gmap_array_raises(gmap, axis):
def test_background_gradient_gmap_dataframe_align(styler_blank, gmap, subset, exp_gmap):
def test_background_gradient_gmap_series_align(styler_blank, gmap, axis, exp_gmap):
def test_background_gradient_gmap_wrong_dataframe(styler_blank, gmap, axis):
def test_background_gradient_gmap_wrong_series(styler_blank):
``` | https://api.github.com/repos/pandas-dev/pandas/pulls/40958 | 2021-04-15T07:26:55Z | 2021-04-15T17:49:00Z | 2021-04-15T17:49:00Z | 2021-04-15T21:55:44Z |
TYP: annotations | diff --git a/pandas/_libs/hashtable_class_helper.pxi.in b/pandas/_libs/hashtable_class_helper.pxi.in
index b80a127be970d..4dc5e7516db7e 100644
--- a/pandas/_libs/hashtable_class_helper.pxi.in
+++ b/pandas/_libs/hashtable_class_helper.pxi.in
@@ -791,7 +791,8 @@ cdef class StringHashTable(HashTable):
raise KeyError(key)
@cython.boundscheck(False)
- def get_indexer(self, ndarray[object] values):
+ def get_indexer(self, ndarray[object] values) -> ndarray:
+ # -> np.ndarray[np.intp]
cdef:
Py_ssize_t i, n = len(values)
ndarray[intp_t] labels = np.empty(n, dtype=np.intp)
diff --git a/pandas/_libs/lib.pyi b/pandas/_libs/lib.pyi
index 477c9fd655a4a..4c647056641f5 100644
--- a/pandas/_libs/lib.pyi
+++ b/pandas/_libs/lib.pyi
@@ -4,6 +4,7 @@
from typing import (
Any,
Callable,
+ Generator,
)
import numpy as np
@@ -52,8 +53,7 @@ def is_bool_array(values: np.ndarray, skipna: bool = False): ...
def fast_multiget(mapping: dict, keys: np.ndarray, default=np.nan) -> ArrayLike: ...
-# TODO: gen: Generator?
-def fast_unique_multiple_list_gen(gen: object, sort: bool = True) -> list: ...
+def fast_unique_multiple_list_gen(gen: Generator, sort: bool = True) -> list: ...
def fast_unique_multiple_list(lists: list, sort: bool = True) -> list: ...
def fast_unique_multiple(arrays: list, sort: bool = True) -> list: ...
@@ -90,10 +90,9 @@ def infer_datetimelike_array(
arr: np.ndarray # np.ndarray[object]
) -> str: ...
-# TODO: new_dtype -> np.dtype?
def astype_intsafe(
arr: np.ndarray, # np.ndarray[object]
- new_dtype,
+ new_dtype: np.dtype,
) -> np.ndarray: ...
def fast_zip(ndarrays: list) -> np.ndarray: ... # np.ndarray[object]
@@ -134,15 +133,13 @@ def memory_usage_of_objects(
) -> int: ... # np.int64
-# TODO: f: Callable?
-# TODO: dtype -> DtypeObj?
def map_infer_mask(
arr: np.ndarray,
f: Callable[[Any], Any],
mask: np.ndarray, # const uint8_t[:]
convert: bool = ...,
na_value: Any = ...,
- dtype: Any = ...,
+ dtype: np.dtype = ...,
) -> ArrayLike: ...
def indices_fast(
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx
index e816bd4cd4026..a5ed650d72911 100644
--- a/pandas/_libs/lib.pyx
+++ b/pandas/_libs/lib.pyx
@@ -633,7 +633,7 @@ def array_equivalent_object(left: object[:], right: object[:]) -> bool:
@cython.wraparound(False)
@cython.boundscheck(False)
-def astype_intsafe(ndarray[object] arr, new_dtype) -> ndarray:
+def astype_intsafe(ndarray[object] arr, cnp.dtype new_dtype) -> ndarray:
cdef:
Py_ssize_t i, n = len(arr)
object val
@@ -661,7 +661,8 @@ cpdef ndarray[object] ensure_string_array(
bint copy=True,
bint skipna=True,
):
- """Returns a new numpy array with object dtype and only strings and na values.
+ """
+ Returns a new numpy array with object dtype and only strings and na values.
Parameters
----------
@@ -679,7 +680,7 @@ cpdef ndarray[object] ensure_string_array(
Returns
-------
- ndarray
+ np.ndarray[object]
An array with the input array's elements casted to str or nan-like.
"""
cdef:
@@ -2452,7 +2453,8 @@ no_default = NoDefault.no_default # Sentinel indicating the default value.
@cython.boundscheck(False)
@cython.wraparound(False)
def map_infer_mask(ndarray arr, object f, const uint8_t[:] mask, bint convert=True,
- object na_value=no_default, object dtype=object) -> "ArrayLike":
+ object na_value=no_default, cnp.dtype dtype=np.dtype(object)
+ ) -> "ArrayLike":
"""
Substitute for np.vectorize with pandas-friendly dtype inference.
@@ -2472,7 +2474,7 @@ def map_infer_mask(ndarray arr, object f, const uint8_t[:] mask, bint convert=Tr
Returns
-------
- ndarray
+ np.ndarray or ExtensionArray
"""
cdef:
Py_ssize_t i, n
diff --git a/pandas/_libs/tslibs/fields.pyx b/pandas/_libs/tslibs/fields.pyx
index d6ca38e57d2d8..4d55967c1e135 100644
--- a/pandas/_libs/tslibs/fields.pyx
+++ b/pandas/_libs/tslibs/fields.pyx
@@ -93,7 +93,7 @@ def build_field_sarray(const int64_t[:] dtindex):
return out
-def month_position_check(fields, weekdays):
+def month_position_check(fields, weekdays) -> str | None:
cdef:
int32_t daysinmonth, y, m, d
bint calendar_end = True
@@ -755,7 +755,7 @@ cdef inline ndarray[int64_t] _roundup_int64(values, int64_t unit):
return _floor_int64(values + unit // 2, unit)
-def round_nsint64(values: np.ndarray, mode: RoundTo, nanos) -> np.ndarray:
+def round_nsint64(values: np.ndarray, mode: RoundTo, nanos: int) -> np.ndarray:
"""
Applies rounding mode at given frequency
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py
index 02731bd4fbbc1..5a2643dd531ed 100644
--- a/pandas/core/arrays/base.py
+++ b/pandas/core/arrays/base.py
@@ -609,7 +609,7 @@ def argsort(
Returns
-------
- ndarray
+ np.ndarray[np.intp]
Array of indices that sort ``self``. If NaN values are contained,
NaN values are placed at the end.
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index f2b5ad447a0cf..272cf19be559c 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -1599,7 +1599,7 @@ def argsort(self, ascending=True, kind="quicksort", **kwargs):
Returns
-------
- numpy.array
+ np.ndarray[np.intp]
See Also
--------
diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py
index ee68f5558a651..087ce415cc4ba 100644
--- a/pandas/core/arrays/timedeltas.py
+++ b/pandas/core/arrays/timedeltas.py
@@ -135,10 +135,10 @@ class TimedeltaArray(dtl.TimelikeOps):
# define my properties & methods for delegation
_other_ops: list[str] = []
_bool_ops: list[str] = []
- _object_ops = ["freq"]
- _field_ops = ["days", "seconds", "microseconds", "nanoseconds"]
- _datetimelike_ops = _field_ops + _object_ops + _bool_ops
- _datetimelike_methods = [
+ _object_ops: list[str] = ["freq"]
+ _field_ops: list[str] = ["days", "seconds", "microseconds", "nanoseconds"]
+ _datetimelike_ops: list[str] = _field_ops + _object_ops + _bool_ops
+ _datetimelike_methods: list[str] = [
"to_pytimedelta",
"total_seconds",
"round",
diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py
index 5656323b82fb7..f56e13775460b 100644
--- a/pandas/core/indexes/api.py
+++ b/pandas/core/indexes/api.py
@@ -164,7 +164,7 @@ def _get_combined_index(
return index
-def union_indexes(indexes, sort=True) -> Index:
+def union_indexes(indexes, sort: bool = True) -> Index:
"""
Return the union of indexes.
@@ -273,7 +273,7 @@ def _sanitize_and_check(indexes):
return indexes, "array"
-def all_indexes_same(indexes):
+def all_indexes_same(indexes) -> bool:
"""
Determine if all indexes contain the same elements.
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index c79518702169a..310ee4c3a63e3 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -215,7 +215,7 @@ def join(
return cast(F, join)
-def disallow_kwargs(kwargs: dict[str, Any]):
+def disallow_kwargs(kwargs: dict[str, Any]) -> None:
if kwargs:
raise TypeError(f"Unexpected keyword arguments {repr(set(kwargs))}")
@@ -626,7 +626,7 @@ def _maybe_check_unique(self) -> None:
raise DuplicateLabelError(msg)
@final
- def _format_duplicate_message(self):
+ def _format_duplicate_message(self) -> DataFrame:
"""
Construct the DataFrame for a DuplicateLabelError.
@@ -789,7 +789,7 @@ def __array_wrap__(self, result, context=None):
return Index(result, **attrs)
@cache_readonly
- def dtype(self):
+ def dtype(self) -> DtypeObj:
"""
Return the dtype object of the underlying data.
"""
@@ -1064,11 +1064,11 @@ def copy(
return new_index
@final
- def __copy__(self, **kwargs):
+ def __copy__(self: _IndexT, **kwargs) -> _IndexT:
return self.copy(**kwargs)
@final
- def __deepcopy__(self, memo=None):
+ def __deepcopy__(self: _IndexT, memo=None) -> _IndexT:
"""
Parameters
----------
@@ -1354,7 +1354,7 @@ def to_series(self, index=None, name: Hashable = None) -> Series:
return Series(self._values.copy(), index=index, name=name)
- def to_frame(self, index: bool = True, name=None) -> DataFrame:
+ def to_frame(self, index: bool = True, name: Hashable = None) -> DataFrame:
"""
Create a DataFrame with a column containing the Index.
@@ -1426,7 +1426,7 @@ def name(self):
return self._name
@name.setter
- def name(self, value):
+ def name(self, value: Hashable):
if self._no_setting_name:
# Used in MultiIndex.levels to avoid silently ignoring name updates.
raise RuntimeError(
@@ -2367,7 +2367,7 @@ def _is_all_dates(self) -> bool:
@cache_readonly
@final
- def is_all_dates(self):
+ def is_all_dates(self) -> bool:
"""
Whether or not the index values only consist of dates.
"""
@@ -3380,7 +3380,7 @@ def get_loc(self, key, method=None, tolerance=None):
Returns
-------
- indexer : ndarray of int
+ indexer : np.ndarray[np.intp]
Integers from 0 to n - 1 indicating that the index at these
positions matches the corresponding target values. Missing values
in the target are marked by -1.
@@ -4610,7 +4610,7 @@ def _can_hold_identifiers_and_holds_name(self, name) -> bool:
return name in self
return False
- def append(self, other) -> Index:
+ def append(self, other: Index | Sequence[Index]) -> Index:
"""
Append a collection of Index options together.
@@ -4627,7 +4627,9 @@ def append(self, other) -> Index:
if isinstance(other, (list, tuple)):
to_concat += list(other)
else:
- to_concat.append(other)
+ # error: Argument 1 to "append" of "list" has incompatible type
+ # "Union[Index, Sequence[Index]]"; expected "Index"
+ to_concat.append(other) # type: ignore[arg-type]
for obj in to_concat:
if not isinstance(obj, Index):
@@ -5181,11 +5183,11 @@ def set_value(self, arr, key, value):
Returns
-------
- indexer : ndarray of int
+ indexer : np.ndarray[np.intp]
Integers from 0 to n - 1 indicating that the index at these
positions matches the corresponding target values. Missing values
in the target are marked by -1.
- missing : ndarray of int
+ missing : np.ndarray[np.intp]
An indexer into the target of the values not found.
These correspond to the -1 in the indexer array.
"""
@@ -5227,7 +5229,7 @@ def get_indexer_for(self, target, **kwargs) -> np.ndarray:
Returns
-------
- numpy.ndarray
+ np.ndarray[np.intp]
List of indices.
"""
if self._index_as_unique:
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index 724caebd69c23..5b98b956e33e6 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -457,8 +457,8 @@ def reindex(
# in which case we are going to conform to the passed Categorical
new_target = np.asarray(new_target)
if is_categorical_dtype(target):
- new_target = Categorical(new_target, dtype=target.dtype)
- new_target = type(self)._simple_new(new_target, name=self.name)
+ cat = Categorical(new_target, dtype=target.dtype)
+ new_target = type(self)._simple_new(cat, name=self.name)
else:
new_target = Index(new_target, name=self.name)
diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py
index 9f02196466ebf..f77f28deecf57 100644
--- a/pandas/core/indexes/datetimes.py
+++ b/pandas/core/indexes/datetimes.py
@@ -391,7 +391,7 @@ def _is_comparable_dtype(self, dtype: DtypeObj) -> bool:
# --------------------------------------------------------------------
# Rendering Methods
- def _mpl_repr(self):
+ def _mpl_repr(self) -> np.ndarray:
# how to represent ourselves to matplotlib
return ints_to_pydatetime(self.asi8, self.tz)
@@ -448,7 +448,7 @@ def _maybe_utc_convert(self, other: Index) -> tuple[DatetimeIndex, Index]:
# --------------------------------------------------------------------
- def _get_time_micros(self):
+ def _get_time_micros(self) -> np.ndarray:
"""
Return the number of microseconds since midnight.
@@ -541,7 +541,7 @@ def to_series(self, keep_tz=lib.no_default, index=None, name=None):
return Series(values, index=index, name=name)
- def snap(self, freq="S"):
+ def snap(self, freq="S") -> DatetimeIndex:
"""
Snap time stamps to nearest occurring frequency.
@@ -891,7 +891,7 @@ def indexer_at_time(self, time, asof: bool = False) -> np.ndarray:
else:
time_micros = self._get_time_micros()
micros = _time_to_micros(time)
- return (micros == time_micros).nonzero()[0]
+ return (time_micros == micros).nonzero()[0]
def indexer_between_time(
self, start_time, end_time, include_start: bool = True, include_end: bool = True
diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py
index f7ab09e4f176f..171ab57264f85 100644
--- a/pandas/core/indexes/interval.py
+++ b/pandas/core/indexes/interval.py
@@ -390,7 +390,7 @@ def from_tuples(
# --------------------------------------------------------------------
@cache_readonly
- def _engine(self):
+ def _engine(self) -> IntervalTree:
left = self._maybe_convert_i8(self.left)
right = self._maybe_convert_i8(self.right)
return IntervalTree(left, right, closed=self.closed)
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 5b4f3e1bb9e09..59ff128713aca 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -2673,6 +2673,7 @@ def _get_indexer(
limit: int | None = None,
tolerance=None,
) -> np.ndarray:
+ # returned ndarray is np.intp
# empty indexer
if not len(target):
diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py
index 8e8c67927c20f..1e974063bd839 100644
--- a/pandas/core/indexes/range.py
+++ b/pandas/core/indexes/range.py
@@ -249,7 +249,7 @@ def _format_with_header(self, header: list[str], na_rep: str = "NaN") -> list[st
)
@property
- def start(self):
+ def start(self) -> int:
"""
The value of the `start` parameter (``0`` if this was not supplied).
"""
@@ -257,7 +257,7 @@ def start(self):
return self._range.start
@property
- def _start(self):
+ def _start(self) -> int:
"""
The value of the `start` parameter (``0`` if this was not supplied).
@@ -272,14 +272,14 @@ def _start(self):
return self.start
@property
- def stop(self):
+ def stop(self) -> int:
"""
The value of the `stop` parameter.
"""
return self._range.stop
@property
- def _stop(self):
+ def _stop(self) -> int:
"""
The value of the `stop` parameter.
@@ -295,7 +295,7 @@ def _stop(self):
return self.stop
@property
- def step(self):
+ def step(self) -> int:
"""
The value of the `step` parameter (``1`` if this was not supplied).
"""
@@ -303,7 +303,7 @@ def step(self):
return self._range.step
@property
- def _step(self):
+ def _step(self) -> int:
"""
The value of the `step` parameter (``1`` if this was not supplied).
@@ -405,6 +405,7 @@ def _get_indexer(
limit: int | None = None,
tolerance=None,
) -> np.ndarray:
+ # -> np.ndarray[np.intp]
if com.any_not_none(method, tolerance, limit):
return super()._get_indexer(
target, method=method, tolerance=tolerance, limit=limit
@@ -522,7 +523,7 @@ def argsort(self, *args, **kwargs) -> np.ndarray:
Returns
-------
- argsorted : numpy array
+ np.ndarray[np.intp]
See Also
--------
@@ -532,9 +533,9 @@ def argsort(self, *args, **kwargs) -> np.ndarray:
nv.validate_argsort(args, kwargs)
if self._range.step > 0:
- result = np.arange(len(self))
+ result = np.arange(len(self), dtype=np.intp)
else:
- result = np.arange(len(self) - 1, -1, -1)
+ result = np.arange(len(self) - 1, -1, -1, dtype=np.intp)
if not ascending:
result = result[::-1]
@@ -759,7 +760,7 @@ def symmetric_difference(self, other, result_name: Hashable = None, sort=None):
# --------------------------------------------------------------------
- def _concat(self, indexes, name: Hashable):
+ def _concat(self, indexes: list[Index], name: Hashable):
"""
Overriding parent method for the case of all RangeIndex instances.
@@ -780,7 +781,8 @@ def _concat(self, indexes, name: Hashable):
non_empty_indexes = [obj for obj in indexes if len(obj)]
for obj in non_empty_indexes:
- rng: range = obj._range
+ # error: "Index" has no attribute "_range"
+ rng: range = obj._range # type: ignore[attr-defined]
if start is None:
# This is set by the first non-empty index
@@ -808,7 +810,12 @@ def _concat(self, indexes, name: Hashable):
if non_empty_indexes:
# Get the stop value from "next" or alternatively
# from the last non-empty index
- stop = non_empty_indexes[-1].stop if next_ is None else next_
+ # error: "Index" has no attribute "stop"
+ stop = (
+ non_empty_indexes[-1].stop # type: ignore[attr-defined]
+ if next_ is None
+ else next_
+ )
return RangeIndex(start, stop, step).rename(name)
# Here all "indexes" had 0 length, i.e. were empty.
diff --git a/pandas/core/series.py b/pandas/core/series.py
index 5c605a6b441c6..fac87515c7d96 100644
--- a/pandas/core/series.py
+++ b/pandas/core/series.py
@@ -2756,13 +2756,15 @@ def __rmatmul__(self, other):
return self.dot(np.transpose(other))
@doc(base.IndexOpsMixin.searchsorted, klass="Series")
- def searchsorted(self, value, side="left", sorter=None):
+ def searchsorted(self, value, side="left", sorter=None) -> np.ndarray:
return algorithms.searchsorted(self._values, value, side=side, sorter=sorter)
# -------------------------------------------------------------------
# Combination
- def append(self, to_append, ignore_index=False, verify_integrity=False):
+ def append(
+ self, to_append, ignore_index: bool = False, verify_integrity: bool = False
+ ):
"""
Concatenate two or more Series.
@@ -2846,7 +2848,7 @@ def append(self, to_append, ignore_index=False, verify_integrity=False):
to_concat, ignore_index=ignore_index, verify_integrity=verify_integrity
)
- def _binop(self, other, func, level=None, fill_value=None):
+ def _binop(self, other: Series, func, level=None, fill_value=None):
"""
Perform generic binary operation with optional fill value.
@@ -3609,7 +3611,7 @@ def argsort(self, axis=0, kind="quicksort", order=None) -> Series:
Returns
-------
- Series
+ Series[np.intp]
Positions of values within the sort order with -1 indicating
nan values.
@@ -3730,7 +3732,7 @@ def nlargest(self, n=5, keep="first") -> Series:
"""
return algorithms.SelectNSeries(self, n=n, keep=keep).nlargest()
- def nsmallest(self, n=5, keep="first") -> Series:
+ def nsmallest(self, n: int = 5, keep: str = "first") -> Series:
"""
Return the smallest `n` elements.
@@ -3942,7 +3944,7 @@ def explode(self, ignore_index: bool = False) -> Series:
return self._constructor(values, index=index, name=self.name)
- def unstack(self, level=-1, fill_value=None):
+ def unstack(self, level=-1, fill_value=None) -> DataFrame:
"""
Unstack, also known as pivot, Series with MultiIndex to produce DataFrame.
@@ -4294,7 +4296,11 @@ def _reduce(
with np.errstate(all="ignore"):
return op(delegate, skipna=skipna, **kwds)
- def _reindex_indexer(self, new_index, indexer, copy):
+ def _reindex_indexer(
+ self, new_index: Index | None, indexer: np.ndarray | None, copy: bool
+ ) -> Series:
+ # Note: new_index is None iff indexer is None
+ # if not None, indexer is np.intp
if indexer is None:
if copy:
return self.copy()
| getting close to ... who am i kidding, no we're not. | https://api.github.com/repos/pandas-dev/pandas/pulls/40955 | 2021-04-14T22:38:27Z | 2021-04-16T19:08:33Z | 2021-04-16T19:08:33Z | 2021-04-16T21:22:12Z |
Add keyword sort to pivot_table | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 38a1802340c69..afe6a3296f04d 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -219,6 +219,7 @@ Other enhancements
- :meth:`pandas.read_csv` and :meth:`pandas.read_json` expose the argument ``encoding_errors`` to control how encoding errors are handled (:issue:`39450`)
- :meth:`.GroupBy.any` and :meth:`.GroupBy.all` use Kleene logic with nullable data types (:issue:`37506`)
- :meth:`.GroupBy.any` and :meth:`.GroupBy.all` return a ``BooleanDtype`` for columns with nullable data types (:issue:`33449`)
+- Add keyword ``sort`` to :func:`pivot_table` to allow non-sorting of the result (:issue:`39143`)
-
.. ---------------------------------------------------------------------------
diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 045776c3f5c50..7224a055fc148 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -7664,6 +7664,11 @@ def pivot(self, index=None, columns=None, values=None) -> DataFrame:
.. versionchanged:: 0.25.0
+ sort : bool, default True
+ Specifies if the result should be sorted.
+
+ .. versionadded:: 1.3.0
+
Returns
-------
DataFrame
@@ -7767,6 +7772,7 @@ def pivot_table(
dropna=True,
margins_name="All",
observed=False,
+ sort=True,
) -> DataFrame:
from pandas.core.reshape.pivot import pivot_table
@@ -7781,6 +7787,7 @@ def pivot_table(
dropna=dropna,
margins_name=margins_name,
observed=observed,
+ sort=sort,
)
def stack(self, level: Level = -1, dropna: bool = True):
diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py
index 795f5250012cb..e324534e0433f 100644
--- a/pandas/core/reshape/pivot.py
+++ b/pandas/core/reshape/pivot.py
@@ -64,6 +64,7 @@ def pivot_table(
dropna=True,
margins_name="All",
observed=False,
+ sort=True,
) -> DataFrame:
index = _convert_by(index)
columns = _convert_by(columns)
@@ -83,6 +84,7 @@ def pivot_table(
dropna=dropna,
margins_name=margins_name,
observed=observed,
+ sort=sort,
)
pieces.append(_table)
keys.append(getattr(func, "__name__", func))
@@ -101,6 +103,7 @@ def pivot_table(
dropna,
margins_name,
observed,
+ sort,
)
return table.__finalize__(data, method="pivot_table")
@@ -116,6 +119,7 @@ def __internal_pivot_table(
dropna: bool,
margins_name: str,
observed: bool,
+ sort: bool,
) -> DataFrame:
"""
Helper of :func:`pandas.pivot_table` for any non-list ``aggfunc``.
@@ -157,7 +161,7 @@ def __internal_pivot_table(
pass
values = list(values)
- grouped = data.groupby(keys, observed=observed)
+ grouped = data.groupby(keys, observed=observed, sort=sort)
agged = grouped.agg(aggfunc)
if dropna and isinstance(agged, ABCDataFrame) and len(agged.columns):
agged = agged.dropna(how="all")
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py
index 20aa0c9e2ee9a..3d1c3b81c492f 100644
--- a/pandas/tests/reshape/test_pivot.py
+++ b/pandas/tests/reshape/test_pivot.py
@@ -2115,6 +2115,28 @@ def test_pivot_table_doctest_case(self):
expected = DataFrame(vals, columns=cols, index=index)
tm.assert_frame_equal(table, expected)
+ def test_pivot_table_sort_false(self):
+ # GH#39143
+ df = DataFrame(
+ {
+ "a": ["d1", "d4", "d3"],
+ "col": ["a", "b", "c"],
+ "num": [23, 21, 34],
+ "year": ["2018", "2018", "2019"],
+ }
+ )
+ result = df.pivot_table(
+ index=["a", "col"], columns="year", values="num", aggfunc="sum", sort=False
+ )
+ expected = DataFrame(
+ [[23, np.nan], [21, np.nan], [np.nan, 34]],
+ columns=Index(["2018", "2019"], name="year"),
+ index=MultiIndex.from_arrays(
+ [["d1", "d4", "d3"], ["a", "b", "c"]], names=["a", "col"]
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
class TestPivot:
def test_pivot(self):
| - [x] closes #39143
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
This adds support for sort=False to pivot_table if we want to do this | https://api.github.com/repos/pandas-dev/pandas/pulls/40954 | 2021-04-14T21:14:15Z | 2021-04-20T23:23:08Z | 2021-04-20T23:23:07Z | 2021-04-21T20:40:35Z |
Clarify docs for MultiIndex drops and levels | diff --git a/pandas/core/frame.py b/pandas/core/frame.py
index 38766d2856cfe..f9ad737bff46c 100644
--- a/pandas/core/frame.py
+++ b/pandas/core/frame.py
@@ -4749,7 +4749,8 @@ def drop(
Remove rows or columns by specifying label names and corresponding
axis, or by specifying directly index or column names. When using a
multi-index, labels on different levels can be removed by specifying
- the level.
+ the level. See the `user guide <advanced.shown_levels>`
+ for more information about the now unused levels.
Parameters
----------
| - [x] closes #36227
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
I did something like this in the past but this got lost back then between prs.
| https://api.github.com/repos/pandas-dev/pandas/pulls/40953 | 2021-04-14T20:29:23Z | 2021-04-20T22:50:55Z | 2021-04-20T22:50:55Z | 2021-04-21T20:40:19Z |
BUG: various groupby ewm times issues | diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst
index 38a1802340c69..065390820d7e6 100644
--- a/doc/source/whatsnew/v1.3.0.rst
+++ b/doc/source/whatsnew/v1.3.0.rst
@@ -787,6 +787,9 @@ Groupby/resample/rolling
- Bug in :class:`core.window.ewm.ExponentialMovingWindow` when calling ``__getitem__`` would incorrectly raise a ``ValueError`` when providing ``times`` (:issue:`40164`)
- Bug in :class:`core.window.ewm.ExponentialMovingWindow` when calling ``__getitem__`` would not retain ``com``, ``span``, ``alpha`` or ``halflife`` attributes (:issue:`40164`)
- :class:`core.window.ewm.ExponentialMovingWindow` now raises a ``NotImplementedError`` when specifying ``times`` with ``adjust=False`` due to an incorrect calculation (:issue:`40098`)
+- Bug in :meth:`core.window.ewm.ExponentialMovingWindowGroupby.mean` where the times argument was ignored when ``engine='numba'`` (:issue:`40951`)
+- Bug in :meth:`core.window.ewm.ExponentialMovingWindowGroupby.mean` where the wrong times were used in case of multiple groups (:issue:`40951`)
+- Bug in :class:`core.window.ewm.ExponentialMovingWindowGroupby` where the times vector and values became out of sync for non-trivial groups (:issue:`40951`)
- Bug in :meth:`Series.asfreq` and :meth:`DataFrame.asfreq` dropping rows when the index is not sorted (:issue:`39805`)
- Bug in aggregation functions for :class:`DataFrame` not respecting ``numeric_only`` argument when ``level`` keyword was given (:issue:`40660`)
- Bug in :class:`core.window.RollingGroupby` where ``as_index=False`` argument in ``groupby`` was ignored (:issue:`39433`)
diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx
index 46041b6a37a17..8c8629ad6f032 100644
--- a/pandas/_libs/window/aggregations.pyx
+++ b/pandas/_libs/window/aggregations.pyx
@@ -1485,8 +1485,7 @@ def ewma(const float64_t[:] vals, const int64_t[:] start, const int64_t[:] end,
com : float64
adjust : bool
ignore_na : bool
- times : ndarray (float64 type)
- halflife : float64
+ deltas : ndarray (float64 type)
Returns
-------
@@ -1495,7 +1494,7 @@ def ewma(const float64_t[:] vals, const int64_t[:] start, const int64_t[:] end,
cdef:
Py_ssize_t i, j, s, e, nobs, win_size, N = len(vals), M = len(start)
- const float64_t[:] sub_vals
+ const float64_t[:] sub_deltas, sub_vals
ndarray[float64_t] sub_output, output = np.empty(N, dtype=float)
float64_t alpha, old_wt_factor, new_wt, weighted_avg, old_wt, cur
bint is_observation
@@ -1511,6 +1510,9 @@ def ewma(const float64_t[:] vals, const int64_t[:] start, const int64_t[:] end,
s = start[j]
e = end[j]
sub_vals = vals[s:e]
+ # note that len(deltas) = len(vals) - 1 and deltas[i] is to be used in
+ # conjunction with vals[i+1]
+ sub_deltas = deltas[s:e - 1]
win_size = len(sub_vals)
sub_output = np.empty(win_size, dtype=float)
@@ -1528,7 +1530,7 @@ def ewma(const float64_t[:] vals, const int64_t[:] start, const int64_t[:] end,
if weighted_avg == weighted_avg:
if is_observation or not ignore_na:
- old_wt *= old_wt_factor ** deltas[i - 1]
+ old_wt *= old_wt_factor ** sub_deltas[i - 1]
if is_observation:
# avoid numerical errors on constant series
diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py
index 67bcdb0a387dd..eee9cb3976e39 100644
--- a/pandas/core/window/ewm.py
+++ b/pandas/core/window/ewm.py
@@ -78,6 +78,38 @@ def get_center_of_mass(
return float(comass)
+def _calculate_deltas(
+ times: str | np.ndarray | FrameOrSeries | None,
+ halflife: float | TimedeltaConvertibleTypes | None,
+) -> np.ndarray:
+ """
+ Return the diff of the times divided by the half-life. These values are used in
+ the calculation of the ewm mean.
+
+ Parameters
+ ----------
+ times : str, np.ndarray, Series, default None
+ Times corresponding to the observations. Must be monotonically increasing
+ and ``datetime64[ns]`` dtype.
+ halflife : float, str, timedelta, optional
+ Half-life specifying the decay
+
+ Returns
+ -------
+ np.ndarray
+ Diff of the times divided by the half-life
+ """
+ # error: Item "str" of "Union[str, ndarray, FrameOrSeries, None]" has no
+ # attribute "view"
+ # error: Item "None" of "Union[str, ndarray, FrameOrSeries, None]" has no
+ # attribute "view"
+ _times = np.asarray(
+ times.view(np.int64), dtype=np.float64 # type: ignore[union-attr]
+ )
+ _halflife = float(Timedelta(halflife).value)
+ return np.diff(_times) / _halflife
+
+
class ExponentialMovingWindow(BaseWindow):
r"""
Provide exponential weighted (EW) functions.
@@ -268,15 +300,7 @@ def __init__(
)
if isna(self.times).any():
raise ValueError("Cannot convert NaT values to integer")
- # error: Item "str" of "Union[str, ndarray, FrameOrSeries, None]" has no
- # attribute "view"
- # error: Item "None" of "Union[str, ndarray, FrameOrSeries, None]" has no
- # attribute "view"
- _times = np.asarray(
- self.times.view(np.int64), dtype=np.float64 # type: ignore[union-attr]
- )
- _halflife = float(Timedelta(self.halflife).value)
- self._deltas = np.diff(_times) / _halflife
+ self._deltas = _calculate_deltas(self.times, self.halflife)
# Halflife is no longer applicable when calculating COM
# But allow COM to still be calculated if the user passes other decay args
if common.count_not_none(self.com, self.span, self.alpha) > 0:
@@ -585,6 +609,17 @@ class ExponentialMovingWindowGroupby(BaseWindowGroupby, ExponentialMovingWindow)
_attributes = ExponentialMovingWindow._attributes + BaseWindowGroupby._attributes
+ def __init__(self, obj, *args, _grouper=None, **kwargs):
+ super().__init__(obj, *args, _grouper=_grouper, **kwargs)
+
+ if not obj.empty and self.times is not None:
+ # sort the times and recalculate the deltas according to the groups
+ groupby_order = np.concatenate(list(self._grouper.indices.values()))
+ self._deltas = _calculate_deltas(
+ self.times.take(groupby_order), # type: ignore[union-attr]
+ self.halflife,
+ )
+
def _get_window_indexer(self) -> GroupbyIndexer:
"""
Return an indexer class that will compute the window start and end bounds
@@ -628,10 +663,7 @@ def mean(self, engine=None, engine_kwargs=None):
"""
if maybe_use_numba(engine):
groupby_ewma_func = generate_numba_groupby_ewma_func(
- engine_kwargs,
- self._com,
- self.adjust,
- self.ignore_na,
+ engine_kwargs, self._com, self.adjust, self.ignore_na, self._deltas
)
return self._apply(
groupby_ewma_func,
diff --git a/pandas/core/window/numba_.py b/pandas/core/window/numba_.py
index c9107c8ed0aa7..d84dea7ee622c 100644
--- a/pandas/core/window/numba_.py
+++ b/pandas/core/window/numba_.py
@@ -85,6 +85,7 @@ def generate_numba_groupby_ewma_func(
com: float,
adjust: bool,
ignore_na: bool,
+ deltas: np.ndarray,
):
"""
Generate a numba jitted groupby ewma function specified by values
@@ -97,6 +98,7 @@ def generate_numba_groupby_ewma_func(
com : float
adjust : bool
ignore_na : bool
+ deltas : numpy.ndarray
Returns
-------
@@ -141,7 +143,9 @@ def groupby_ewma(
if is_observation or not ignore_na:
- old_wt *= old_wt_factor
+ # note that len(deltas) = len(vals) - 1 and deltas[i] is to be
+ # used in conjunction with vals[i+1]
+ old_wt *= old_wt_factor ** deltas[start + j - 1]
if is_observation:
# avoid numerical errors on constant series
diff --git a/pandas/tests/window/conftest.py b/pandas/tests/window/conftest.py
index d394a4b2be548..b1f1bb7086149 100644
--- a/pandas/tests/window/conftest.py
+++ b/pandas/tests/window/conftest.py
@@ -13,6 +13,7 @@
Series,
bdate_range,
notna,
+ to_datetime,
)
@@ -302,6 +303,31 @@ def frame():
)
+@pytest.fixture
+def times_frame():
+ """Frame for testing times argument in EWM groupby."""
+ return DataFrame(
+ {
+ "A": ["a", "b", "c", "a", "b", "c", "a", "b", "c", "a"],
+ "B": [0, 0, 0, 1, 1, 1, 2, 2, 2, 3],
+ "C": to_datetime(
+ [
+ "2020-01-01",
+ "2020-01-01",
+ "2020-01-01",
+ "2020-01-02",
+ "2020-01-10",
+ "2020-01-22",
+ "2020-01-03",
+ "2020-01-23",
+ "2020-01-23",
+ "2020-01-04",
+ ]
+ ),
+ }
+ )
+
+
@pytest.fixture
def series():
"""Make mocked series as fixture."""
diff --git a/pandas/tests/window/test_groupby.py b/pandas/tests/window/test_groupby.py
index 51a6288598c32..5d7fc50620ef8 100644
--- a/pandas/tests/window/test_groupby.py
+++ b/pandas/tests/window/test_groupby.py
@@ -926,3 +926,63 @@ def test_pairwise_methods(self, method, expected_data):
expected = df.groupby("A").apply(lambda x: getattr(x.ewm(com=1.0), method)())
tm.assert_frame_equal(result, expected)
+
+ def test_times(self, times_frame):
+ # GH 40951
+ halflife = "23 days"
+ result = times_frame.groupby("A").ewm(halflife=halflife, times="C").mean()
+ expected = DataFrame(
+ {
+ "B": [
+ 0.0,
+ 0.507534,
+ 1.020088,
+ 1.537661,
+ 0.0,
+ 0.567395,
+ 1.221209,
+ 0.0,
+ 0.653141,
+ 1.195003,
+ ]
+ },
+ index=MultiIndex.from_tuples(
+ [
+ ("a", 0),
+ ("a", 3),
+ ("a", 6),
+ ("a", 9),
+ ("b", 1),
+ ("b", 4),
+ ("b", 7),
+ ("c", 2),
+ ("c", 5),
+ ("c", 8),
+ ],
+ names=["A", None],
+ ),
+ )
+ tm.assert_frame_equal(result, expected)
+
+ def test_times_vs_apply(self, times_frame):
+ # GH 40951
+ halflife = "23 days"
+ result = times_frame.groupby("A").ewm(halflife=halflife, times="C").mean()
+ expected = (
+ times_frame.groupby("A")
+ .apply(lambda x: x.ewm(halflife=halflife, times="C").mean())
+ .iloc[[0, 3, 6, 9, 1, 4, 7, 2, 5, 8]]
+ .reset_index(drop=True)
+ )
+ tm.assert_frame_equal(result.reset_index(drop=True), expected)
+
+ def test_times_array(self, times_frame):
+ # GH 40951
+ halflife = "23 days"
+ result = times_frame.groupby("A").ewm(halflife=halflife, times="C").mean()
+ expected = (
+ times_frame.groupby("A")
+ .ewm(halflife=halflife, times=times_frame["C"].values)
+ .mean()
+ )
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/window/test_numba.py b/pandas/tests/window/test_numba.py
index f64d242a4e820..06b34201e0dba 100644
--- a/pandas/tests/window/test_numba.py
+++ b/pandas/tests/window/test_numba.py
@@ -8,6 +8,7 @@
DataFrame,
Series,
option_context,
+ to_datetime,
)
import pandas._testing as tm
from pandas.core.util.numba_ import NUMBA_FUNC_CACHE
@@ -145,6 +146,30 @@ def test_cython_vs_numba(self, nogil, parallel, nopython, ignore_na, adjust):
tm.assert_frame_equal(result, expected)
+ def test_cython_vs_numba_times(self, nogil, parallel, nopython, ignore_na):
+ # GH 40951
+ halflife = "23 days"
+ times = to_datetime(
+ [
+ "2020-01-01",
+ "2020-01-01",
+ "2020-01-02",
+ "2020-01-10",
+ "2020-02-23",
+ "2020-01-03",
+ ]
+ )
+ df = DataFrame({"A": ["a", "b", "a", "b", "b", "a"], "B": [0, 0, 1, 1, 2, 2]})
+ gb_ewm = df.groupby("A").ewm(
+ halflife=halflife, adjust=True, ignore_na=ignore_na, times=times
+ )
+
+ engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython}
+ result = gb_ewm.mean(engine="numba", engine_kwargs=engine_kwargs)
+ expected = gb_ewm.mean(engine="cython")
+
+ tm.assert_frame_equal(result, expected)
+
@td.skip_if_no("numba", "0.46.0")
def test_use_global_config():
| - [x] closes #40951
- [x] tests added / passed
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [x] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/40952 | 2021-04-14T19:55:40Z | 2021-04-16T18:42:55Z | 2021-04-16T18:42:55Z | 2021-04-16T18:43:53Z |
TYP: Index.reindex | diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py
index 705a279638097..c79518702169a 100644
--- a/pandas/core/indexes/base.py
+++ b/pandas/core/indexes/base.py
@@ -3762,7 +3762,9 @@ def _validate_can_reindex(self, indexer: np.ndarray) -> None:
if not self._index_as_unique and len(indexer):
raise ValueError("cannot reindex from a duplicate axis")
- def reindex(self, target, method=None, level=None, limit=None, tolerance=None):
+ def reindex(
+ self, target, method=None, level=None, limit=None, tolerance=None
+ ) -> tuple[Index, np.ndarray | None]:
"""
Create index with target's values.
@@ -3774,7 +3776,7 @@ def reindex(self, target, method=None, level=None, limit=None, tolerance=None):
-------
new_index : pd.Index
Resulting index.
- indexer : np.ndarray or None
+ indexer : np.ndarray[np.intp] or None
Indices of output values in original index.
"""
# GH6552: preserve names when reindexing to non-named target
@@ -3815,7 +3817,9 @@ def reindex(self, target, method=None, level=None, limit=None, tolerance=None):
return target, indexer
- def _reindex_non_unique(self, target):
+ def _reindex_non_unique(
+ self, target: Index
+ ) -> tuple[Index, np.ndarray, np.ndarray | None]:
"""
Create a new index with target's values (move/add/delete values as
necessary) use with non-unique Index and a possibly non-unique target.
@@ -3828,8 +3832,9 @@ def _reindex_non_unique(self, target):
-------
new_index : pd.Index
Resulting index.
- indexer : np.ndarray or None
+ indexer : np.ndarray[np.intp]
Indices of output values in original index.
+ new_indexer : np.ndarray[np.intp] or None
"""
target = ensure_index(target)
@@ -3858,13 +3863,13 @@ def _reindex_non_unique(self, target):
# GH#38906
if not len(self):
- new_indexer = np.arange(0)
+ new_indexer = np.arange(0, dtype=np.intp)
# a unique indexer
elif target.is_unique:
# see GH5553, make sure we use the right indexer
- new_indexer = np.arange(len(indexer))
+ new_indexer = np.arange(len(indexer), dtype=np.intp)
new_indexer[cur_indexer] = np.arange(len(cur_labels))
new_indexer[missing_indexer] = -1
@@ -3876,7 +3881,7 @@ def _reindex_non_unique(self, target):
indexer[~check] = -1
# reset the new indexer to account for the new size
- new_indexer = np.arange(len(self.take(indexer)))
+ new_indexer = np.arange(len(self.take(indexer)), dtype=np.intp)
new_indexer[~check] = -1
if isinstance(self, ABCMultiIndex):
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py
index b5089621313b8..724caebd69c23 100644
--- a/pandas/core/indexes/category.py
+++ b/pandas/core/indexes/category.py
@@ -395,7 +395,9 @@ def unique(self, level=None):
# of result, not self.
return type(self)._simple_new(result, name=self.name)
- def reindex(self, target, method=None, level=None, limit=None, tolerance=None):
+ def reindex(
+ self, target, method=None, level=None, limit=None, tolerance=None
+ ) -> tuple[Index, np.ndarray | None]:
"""
Create index with target's values (move/add/delete values as necessary)
@@ -403,7 +405,7 @@ def reindex(self, target, method=None, level=None, limit=None, tolerance=None):
-------
new_index : pd.Index
Resulting index
- indexer : np.ndarray or None
+ indexer : np.ndarray[np.intp] or None
Indices of output values in original index
"""
@@ -440,7 +442,7 @@ def reindex(self, target, method=None, level=None, limit=None, tolerance=None):
if not isinstance(cats, CategoricalIndex) or (cats == -1).any():
# coerce to a regular index here!
result = Index(np.array(self), name=self.name)
- new_target, indexer, _ = result._reindex_non_unique(np.array(target))
+ new_target, indexer, _ = result._reindex_non_unique(target)
else:
codes = new_target.codes.copy()
@@ -462,25 +464,34 @@ def reindex(self, target, method=None, level=None, limit=None, tolerance=None):
return new_target, indexer
- def _reindex_non_unique(self, target):
+ # error: Return type "Tuple[Index, Optional[ndarray], Optional[ndarray]]"
+ # of "_reindex_non_unique" incompatible with return type
+ # "Tuple[Index, ndarray, Optional[ndarray]]" in supertype "Index"
+ def _reindex_non_unique( # type: ignore[override]
+ self, target: Index
+ ) -> tuple[Index, np.ndarray | None, np.ndarray | None]:
"""
reindex from a non-unique; which CategoricalIndex's are almost
always
"""
+ # TODO: rule out `indexer is None` here to make the signature
+ # match the parent class's signature. This should be equivalent
+ # to ruling out `self.equals(target)`
new_target, indexer = self.reindex(target)
new_indexer = None
check = indexer == -1
- if check.any():
- new_indexer = np.arange(len(self.take(indexer)))
+ # error: Item "bool" of "Union[Any, bool]" has no attribute "any"
+ if check.any(): # type: ignore[union-attr]
+ new_indexer = np.arange(len(self.take(indexer)), dtype=np.intp)
new_indexer[check] = -1
cats = self.categories.get_indexer(target)
if not (cats == -1).any():
# .reindex returns normal Index. Revert to CategoricalIndex if
# all targets are included in my categories
- new_target = Categorical(new_target, dtype=self.dtype)
- new_target = type(self)._simple_new(new_target, name=self.name)
+ cat = Categorical(new_target, dtype=self.dtype)
+ new_target = type(self)._simple_new(cat, name=self.name)
return new_target, indexer, new_indexer
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py
index 3305610a4022e..5b4f3e1bb9e09 100644
--- a/pandas/core/indexes/multi.py
+++ b/pandas/core/indexes/multi.py
@@ -2503,7 +2503,9 @@ def sortlevel(
return new_index, indexer
- def reindex(self, target, method=None, level=None, limit=None, tolerance=None):
+ def reindex(
+ self, target, method=None, level=None, limit=None, tolerance=None
+ ) -> tuple[MultiIndex, np.ndarray | None]:
"""
Create index with target's values (move/add/delete values as necessary)
@@ -2511,7 +2513,7 @@ def reindex(self, target, method=None, level=None, limit=None, tolerance=None):
-------
new_index : pd.MultiIndex
Resulting index
- indexer : np.ndarray or None
+ indexer : np.ndarray[np.intp] or None
Indices of output values in original index.
"""
| - [ ] closes #xxxx
- [ ] tests added / passed
- [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
- [ ] whatsnew entry
| https://api.github.com/repos/pandas-dev/pandas/pulls/40950 | 2021-04-14T19:15:25Z | 2021-04-16T01:07:49Z | 2021-04-16T01:07:49Z | 2021-04-16T01:15:17Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.